Skip to content

Commit

Permalink
fix(): add json resolution plugin for rollup to stencil.
Browse files Browse the repository at this point in the history
  • Loading branch information
jthoms1 committed Feb 13, 2018
1 parent 065ed4e commit 39dcfc6
Show file tree
Hide file tree
Showing 4 changed files with 247 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/compiler/bundle/rollup-bundle.ts
Expand Up @@ -8,6 +8,7 @@ import transpiledInMemoryPlugin from './rollup-plugins/transpiled-in-memory';
import bundleEntryFile from './rollup-plugins/bundle-entry-file';
import { InputOptions, OutputChunk, rollup } from 'rollup';
import nodeEnvVars from './rollup-plugins/node-env-vars';
import bundleJson from './rollup-plugins/json';


export async function createBundle(config: Config, compilerCtx: CompilerCtx, buildCtx: BuildCtx, entryModules: EntryModule[]) {
Expand All @@ -28,6 +29,7 @@ export async function createBundle(config: Config, compilerCtx: CompilerCtx, bui
include: 'node_modules/**',
sourceMap: false
}),
bundleJson(config),
globals(),
builtins(),
bundleEntryFile(config, entryModules),
Expand Down
195 changes: 195 additions & 0 deletions src/compiler/bundle/rollup-plugins/json.ts
@@ -0,0 +1,195 @@
import makeLegalIdentifier from './makeLegalIdentifier';
import { Config } from '../../../declarations';

export interface Options {
indent?: string;
preferConst?: boolean;
}
export interface ASTNode {
type: string;
sourceType?: string;
start: number | null;
end: number | null;
body?: any[];
declaration?: any;
}

export default function bundleJson(config: Config, options: Options = {}) {
const path = config.sys.path;

return {
name: 'json',

resolveId(importee: string, importer: string): any {
if (importer && importer.startsWith(config.collectionDir) && importee.endsWith('.json')) {
return path.resolve(
path.dirname(importer).replace(config.collectionDir, config.srcDir),
importee
);
}

return null;
},

transform(json: string, id: string) {
if (id.slice(-5) !== '.json') return null;

const data = JSON.parse(json);
let code = '';

const ast: ASTNode = {
type: 'Program',
sourceType: 'module',
start: 0,
end: null,
body: []
};

if (Object.prototype.toString.call(data) !== '[object Object]') {
code = `export default ${json};`;

ast.body.push({
type: 'ExportDefaultDeclaration',
start: 0,
end: code.length,
declaration: {
type: 'Literal',
start: 15,
end: code.length - 1,
value: null,
raw: 'null'
}
});
} else {
const indent = 'indent' in options ? options.indent : '\t';

const validKeys: string[] = [];
const invalidKeys: string[] = [];

Object.keys(data).forEach(key => {
if (key === makeLegalIdentifier(key)) {
validKeys.push(key);
} else {
invalidKeys.push(key);
}
});

let char = 0;

validKeys.forEach(key => {
const declarationType = options.preferConst ? 'const' : 'var';
const declaration = `export ${declarationType} ${key} = ${JSON.stringify(data[key])};`;

const start = char;
const end = start + declaration.length;

// generate fake AST node while we're here
ast.body.push({
type: 'ExportNamedDeclaration',
start: char,
end: char + declaration.length,
declaration: {
type: 'VariableDeclaration',
start: start + 7, // 'export '.length
end,
declarations: [
{
type: 'VariableDeclarator',
start: start + 7 + declarationType.length + 1, // `export ${declarationType} `.length
end: end - 1,
id: {
type: 'Identifier',
start: start + 7 + declarationType.length + 1, // `export ${declarationType} `.length
end: start + 7 + declarationType.length + 1 + key.length, // `export ${declarationType} ${key}`.length
name: key
},
init: {
type: 'Literal',
start: start +
7 +
declarationType.length +
1 +
key.length +
3, // `export ${declarationType} ${key} = `.length
end: end - 1,
value: null,
raw: 'null'
}
}
],
kind: declarationType
},
specifiers: [],
source: null
});

char = end + 1;
code += `${declaration}\n`;
});

const defaultExportNode: ASTNode = {
type: 'ExportDefaultDeclaration',
start: char,
end: null,
declaration: {
type: 'ObjectExpression',
start: char + 15,
end: null,
properties: []
}
};

char += 17 + indent.length; // 'export default {\n\t'.length'

const defaultExportRows = validKeys
.map(key => {
const row = `${key}: ${key}`;

const start = char;
const end = start + row.length;

defaultExportNode.declaration.properties.push({
type: 'Property',
start,
end,
method: false,
shorthand: false,
computed: false,
key: {
type: 'Identifier',
start,
end: start + key.length,
name: key
},
value: {
type: 'Identifier',
start: start + key.length + 2,
end,
name: key
},
kind: 'init'
});

char += row.length + (2 + indent.length); // ',\n\t'.length

return row;
})
.concat(
invalidKeys.map(key => `"${key}": ${JSON.stringify(data[key])}`)
);

code += `export default {\n${indent}${defaultExportRows.join(`,\n${indent}`)}\n};`;
ast.body.push(defaultExportNode);

const end = code.length;

defaultExportNode.declaration.end = end - 1;
defaultExportNode.end = end;
}

ast.end = code.length;

return { ast, code, map: { mappings: '' } };
}
};
}
17 changes: 17 additions & 0 deletions src/compiler/bundle/rollup-plugins/makeLegalIdentifier.ts
@@ -0,0 +1,17 @@
const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'.split( ' ' );
const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'.split( ' ' );

const blacklisted: { [ key: string]: boolean} = {};
reservedWords.concat(builtins).forEach(word => blacklisted[word] = true );

export default function makeLegalIdentifier(str: string) {
str = str
.replace( /-(\w)/g, ( _, letter ) => letter.toUpperCase() )
.replace( /[^$_a-zA-Z0-9]/g, '_' );

if ( /\d/.test( str[0] ) || blacklisted[str] ) {
str = `_${str}`;
}

return str;
}
33 changes: 33 additions & 0 deletions src/compiler/bundle/test/bundle-modules.spec.ts
Expand Up @@ -75,6 +75,39 @@ describe('bundle-module', () => {
);
});

it('should include json files', async () => {
c.config.bundles = [
{ components: ['cmp-a'] },
{ components: ['cmp-b'] }
];
await c.fs.writeFiles({
'/src/cmp-a.tsx': `
import json from './package.json';
console.log(json.thename);
@Component({ tag: 'cmp-a' }) export class CmpA {}
`,
'/src/cmp-b.tsx': `
import json from './package.json';
console.log(json.thename);
@Component({ tag: 'cmp-b' }) export class CmpB {}
`,
'/src/package.json': `
{
"thename": "test"
}
`
});
await c.fs.commit();

const r = await c.build();
expect(r.diagnostics).toEqual([]);
expectFilesWritten(r,
'/www/build/app/cmp-a.js',
'/www/build/app/cmp-b.js',
'/www/build/app/chunk1.js'
);
});

var c: TestingCompiler;

beforeEach(async () => {
Expand Down

0 comments on commit 39dcfc6

Please sign in to comment.