code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
onESMNodeFound (filePath, node, args) { let { output, code } = activeModules[filePath]; if (node.type === 'ImportDeclaration' || (args && args.source)) { output.overwrite(node.start, node.end, blanker(code, node.start, node.end)); return; } if (node.type === 'ExportDefaultDeclaration') { // Account for "export default function" and "export default(()=>{})" let offset = code[node.start + 14] === ' '? 15 : 14; if (node.declaration && node.declaration.id) { // Using + 15 to avoid "export default (() => {})" being converted // to "module.exports.default = () => {})" output.overwrite(node.start, node.start + offset, '', { contentOnly: true }); output.appendRight(node.declaration.end, `; __e__('default', function () { return ${node.declaration.id.name} });`); } else { output.overwrite(node.start, node.start + offset, `var __ex_default__ = `, { contentOnly: true }); let end = code[node.end - 1] === ';'? node.end - 1 : node.end; output.appendRight(end, `; __e__('default', function () { return __ex_default__ });`); } return; } if (node.type === 'ExportNamedDeclaration') { if (node.declaration) { // Remove 'export' keyword. output.overwrite(node.start, node.start + 7, '', { contentOnly: true }); let specifiers = '; ' + args.map(e => `__e__('${e.exported}', function () { return ${e.local} });`).join(''); output.appendRight(node.end, specifiers); } if (!node.declaration && node.specifiers) { if (!node.source) { // Export from statements are already blanked by the import section. output.overwrite(node.start, node.start + 6, '__e__(', { contentOnly: true }); node.specifiers.forEach(spec => { // { a as b, c }, need to preserve the variable incase it's from an import statement // This is important for live bindings to be able to be transformed. output.prependLeft(spec.local.start, spec.exported.name + ': function () { return '); if (spec.local.start !== spec.exported.start) { output.overwrite(spec.local.end, spec.exported.end, '', { contentOnly: true }); } output.appendRight(spec.exported.end, ' }'); }); if (code[node.end - 1] === ';') { output.prependLeft(node.end - 1, ')'); } else { output.appendRight(node.end, ');') } } } return; } if (node.type === 'ImportExpression') { if (!args.external) { if (typeof args.resolved.id === 'string' && path.isAbsolute(args.resolved.id.split(':').pop())) { // import('hello') --> require.dynamic('/hello.js'); output.overwrite(node.start, node.start + 6, 'require.dynamic', { contentOnly: true }); output.overwrite(node.source.start, node.source.end, '\'' + normalizePathDelimiter(args.resolved.id) + '\'', { contentOnly: true }); } } } }
@param {string} filePath @param {ESTree} node @param {any} args
onESMNodeFound
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
onESMImportLiveBinding (filePath, node, ancestors) { let { output, code } = activeModules[filePath]; let parent = ancestors[ancestors.length - 1]; if (parent.type === 'Property' && parent.shorthand) { output.prependLeft(node.start, node.name + ': '); } output.overwrite(node.start, node.end, '__i__.' + node.name, { contentOnly: true }) }
@param {string} filePath @param {ESTree} node @param {any} args
onESMImportLiveBinding
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
onESMLateInitFound (filePath, node, found) { let { output, code } = activeModules[filePath]; let transpiled = ';' + found.map(name => `__e__('${name}', function () { return typeof ${name} !== 'undefined' && ${name} })`).join(';') + ';'; output.appendRight(node.end, transpiled); }
@param {ESTree} node @param {string[]} found
onESMLateInitFound
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
onESMLeave (code, filePath, ast) { let { output } = activeModules[filePath]; let payload = { code: output.toString(), map: output.generateMap({ source: filePath }) }; delete activeModules[filePath]; return payload; }
@param {string} code @param {string} filePath @param {ESTree} ast @return {{ code: string, map: RollupSourceMap }}
onESMLeave
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
onGenerateModule (modules, filePath, config) { let { esmTransformedCode: code, map, imports, exports, externalImports, dynamicImports, syntheticNamedExports, hoist } = modules[filePath]; // Validate dependencies exist. imports.forEach(dep => { if (!modules[dep.source]) { throw new Error('File not found: ' + dep.source); } }); let hoisted = ''; if (hoist) { let ast = AcornParser.parse(code); let s = new MagicString(code); for (let i = 0; i < ast.body.length; i++) { let node = ast.body[i]; if (!node) { continue; } if (node.type === 'FunctionDeclaration') { hoisted += code.substring(node.start, node.end) + ';\n'; let export_match = exports.find(e => e.local === node.id.name) if (export_match) { hoisted += `__e__('${export_match.exported}', function () { return ${export_match.local} });`; } s.overwrite(node.start, node.end, blanker(code, node.start, node.end)); } else if (node.type === 'ClassDeclaration') { hoisted += 'var ' + node.id.name + ';\n'; s.prependLeft(node.start, node.id.name + ' = '); } else if (node.type === 'VariableDeclaration') { hoisted += 'var ' + node.declarations.flatMap(d => getVariableNames(d.id)).join(', ') + ';\n'; if (node.kind === 'var' || node.kind === 'let') { s.overwrite(node.start, node.start + 3, ' ;('); } if (node.kind === 'const') { s.overwrite(node.start, node.start + 5, ' ;('); } if (code[node.end - 1] === ';') { s.appendRight(node.end - 1, ')'); } else { s.appendRight(node.end, ');'); } } } code = s.toString(); } code = escapeCode(code); // Transform the source path so that they display well in the browser debugger. let sourcePath = path.relative(process.cwd(), filePath).replace(/\\/g, '/'); // Append source mapping information code += '\\\n'; if (map) { map.sourceRoot = 'nollup:///'; map.sources[map.sources.length - 1] = sourcePath; code += `\\n${ConvertSourceMap.fromObject(map).toComment()}\\n`; } code += `\\n//# sourceURL=nollup-int:///${sourcePath}`; let context = ( config.moduleContext? ( typeof config.moduleContext === 'function'? config.moduleContext(filePath) : config.moduleContext[filePath] ) : undefined ) || config.context; return ` function (__c__, __r__, __d__, __e__, require, module, __m__, __nollup__global__) { ${this.context.liveBindings? 'var __i__ = {};' : ''} ${this.context.liveBindings === 'with-scope'? 'with (__i__) {' : ''} ${imports.map((i, index) => { let namespace = `_i${index}`; return `var ${namespace}; ${this.context.liveBindings? '' : (!i.export? i.specifiers.map(s => 'var ' + s.local).join(';') : '')};` }).join('; ')} ${externalImports.map(i => { let namespace = `__nollup__external__${i.source.replace(/[\W]/g, '_')}__` return i.specifiers.map(s => { let output = ''; if (i.export) { if (s.imported === '*') { return getExportAllFrom(namespace); } return `__e__("${s.local}", function () { return ${namespace}${s.imported}__ });`; } if (s.imported === '*') output += `var ${s.local} = ${namespace};`; else output += `var ${s.local} = ${namespace}${s.imported}__;`; return output; }).join(';'); }).join('; ')} ${hoisted? hoisted : ''}; __d__(function () { ${imports.map((i, index) => { let namespace = `_i${index}()`; return i.specifiers.map(s => { let output = ''; if (!i.export) { let value = `${namespace}${s.imported === '*'? '' : `.${s.imported}`}`; if (this.context.liveBindings) { output = `!__i__.hasOwnProperty("${s.local}") && Object.defineProperty(__i__, "${s.local}", { get: function () { return ${value}}});`; } else { output = `${s.local} = ${value};`; } } if (i.export) { if (s.imported === '*') { output += getExportAllFrom(namespace); } else { output += `__e__("${s.local}", function () { return ${namespace}.${s.imported} });`; } } let import_exported = exports.find(e => e.local === s.local); if (!i.export && import_exported) { let local = this.context.liveBindings? `__i__["${import_exported.local}"]` : import_exported.local; output += `__e__("${import_exported.exported}", function () { return ${local} });`; } return output; }).join(';'); }).join('; ')} }, function () { "use strict"; eval('${code}'); ${syntheticNamedExports? getSyntheticExports(syntheticNamedExports) : ''} }.bind(${context})); ${this.context.liveBindings === 'with-scope'? '}' : ''} ${imports.map((i, index) => { let id = `_i${index}`; return `${id} = __c__(${modules[i.source].index}) && function () { return __r__(${modules[i.source].index}) }`; }).join('; ')} } `.trim(); }
@param {Object<string, NollupInternalModule>} modules @param {string} filePath @param {RollupConfigContainer} config @return {string}
onGenerateModule
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
onGenerateModulePreChunk (file, bundle, modules) { if (file.dynamicImports.length > 0) { return file.generatedCode.replace(/require\.dynamic\((\\)?\'(.*?)(\\)?\'\)/g, (match, escapeLeft, inner, escapeRight) => { let foundOutputChunk = bundle.find(b => { // Look for chunks only, not assets let facadeModuleId = /** @type {RollupOutputChunk} */ (b).facadeModuleId; if (facadeModuleId) { return normalizePathDelimiter(facadeModuleId) === inner } }); let fileName = foundOutputChunk? foundOutputChunk.fileName : ''; return 'require.dynamic(' + (escapeLeft? '\\' : '') + '\'' + fileName + (escapeRight? '\\' : '') +'\', ' + modules[path.normalize(inner)].index + ')'; }); } return file.generatedCode; }
@param {NollupInternalModule} file @param {RollupOutputFile[]} bundle @param {Object<string, NollupInternalModule>} modules @return {string}
onGenerateModulePreChunk
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
onGenerateChunk (modules, chunk, outputOptions, config, externalImports) { let files = Object.keys(chunk.modules).map(filePath => { let file = modules[filePath]; return file.index + ':' + file.code; }); let entryIndex = modules[chunk.facadeModuleId].index; let { format } = outputOptions; let plugins = config.plugins || []; if (chunk.isDynamicEntry) { return ` ${format === 'amd'? 'define(function (require, exports) {' : ''} ${createExternalImports(chunk, outputOptions, externalImports)} (function (global) { global.__nollup_dynamic_require_callback("${chunk.fileName}", ${entryIndex}, {${files}}); })(typeof globalThis !== 'undefined'? globalThis : ( typeof self !== 'undefined' ? self : this )); ${format === 'amd'? '});' : ''} `; } else { return [ format === 'amd'? 'define(function (require, exports) {' : '', createExternalImports(chunk, outputOptions, externalImports), ` ${(chunk.exports.length > 0 && (format === 'es' || format === 'amd'))? 'var __nollup_entry_exports = ' : ''} (function (modules, __nollup__global__) { function getRelativePath (from, to) { from = from === '.'? [] : from.split('/'); to = to.split('/'); var commonLength = from.length; for (var i = 0; i < from.length; i++) { if (from[i] !== to[i]) { commonLength = i; break; } } if (from.length - commonLength === 0) { return './' + to.slice(commonLength).join('/') } return from.slice(commonLength) .map(() => '..') .concat(to.slice(commonLength)) .join('/'); } var instances = {}; if (!__nollup__global__.__nollup__chunks__) __nollup__global__.__nollup__chunks__ = {}; var chunks = __nollup__global__.__nollup__chunks__; var create_module = function (number) { var module = { id: number, dependencies: [], dynamicDependencies: [], exports: {}, invalidate: false, __resolved: false, __resolving: false }; instances[number] = module; ${callNollupModuleInit(/** @type {NollupPlugin[]} */(plugins))} var localRequire = function (dep) { ${format === 'cjs'? ` if (typeof dep === 'string') { return require(dep); } if (!modules[dep]) { throw new Error([ 'Module not found: ' + dep, '- Module doesn\\'t exist in bundle.' ].join('\\n')); } `: ` if (typeof dep === 'string' || !modules[dep]) { throw new Error([ 'Module not found: ' + dep, '- Did you call "require" using a string?', '- Check if you\\'re using untransformed CommonJS.', '- If called with an id, module doesn\\'t exist in bundle.' ].join('\\n')); } `} return _require(module, dep); }; ${format === 'cjs'? ` for (var prop in require) { localRequire[prop] = require[prop]; } ` : ''} localRequire.dynamic = function (file, entryIndex) { return new Promise(function (resolve) { var relative_file = getRelativePath('${path.dirname(chunk.fileName)}', file); var cb = () => { // Each main overrides the dynamic callback so they all have different chunk references let chunk = chunks[file]; let id = chunk.entry; for (var key in chunk.modules) { modules[key] = chunk.modules[key]; } if (instances[number].dynamicDependencies.indexOf(id) === -1) { instances[number].dynamicDependencies.push(id); } resolve(_require(module, id)); }; // If the chunk already statically included this module, use that instead. if (instances[entryIndex]) { chunks[file] = { entry: entryIndex }; cb(); return; } if (chunks[file]) { cb(); } else { ${format === 'es'? (` ${this.context.liveBindings === 'with-scope'? ` return fetch(file).then(res => { return res.text(); }).then(res => { eval(res); cb(); }); ` : ` return import(relative_file).then(cb); `} `) : ''} ${format === 'cjs'? (` return Promise.resolve(require(relative_file)).then(cb); `) : ''} ${format === 'amd'? (` return new Promise(function (resolve) { require([relative_file], resolve)}).then(cb); `) : ''} } }); }; modules[number](function (dep) { if (!instances[dep] || instances[dep].invalidate) { create_module(dep); } if (instances[number].dependencies.indexOf(dep) === -1) { instances[number].dependencies.push(dep); } return true; }, function (dep) { return get_exports(module, dep); }, function(binder, impl) { module.__binder = binder; module.__impl = impl; }, function (arg1, arg2) { var bindings = {}; if (typeof arg1 === 'object') { bindings = arg1; } else { bindings[arg1] = arg2; } for (var prop in bindings) { ${this.context.liveBindings? ` if (!module.exports.hasOwnProperty(prop) || prop === 'default') { Object.defineProperty(module.exports, prop, { get: bindings[prop], enumerable: true, configurable: true }); ` : ` if (module.exports[prop] !== bindings[prop]()) { module.exports[prop] = bindings[prop](); `} Object.keys(instances).forEach(key => { if (instances[key].dependencies.indexOf(number) > -1) { instances[key].__binder(); } }) } } }, localRequire, module, module, __nollup__global__); // Initially this will bind nothing, unless // the module has been replaced by HMR module.__binder(); }; var get_exports = function (parent, number) { return instances[number].exports; }; var resolve_module = function (parent, number) { var module = instances[number]; if (module.__resolved) { return; } module.__resolving = true; var executeModuleImpl = function (module) { ${callNollupModuleWrap(/** @type {NollupPlugin[]} */ (plugins), ` module.__resolved = true; module.__impl(); `)} }; module.dependencies.forEach((dep) => { if (!instances[dep].__resolved && !instances[dep].__resolving) { resolve_module(module, dep); } }); // Make sure module wasn't resolved as a result of circular dep. if (!module.__resolved) { executeModuleImpl(module); } }; var _require = function (parent, number) { if (!instances[number] || instances[number].invalidate) { create_module(number); } resolve_module(parent, number); return instances[number].exports; }; if (!__nollup__global__.__nollup_dynamic_require_callback) { __nollup__global__.__nollup_dynamic_require_callback = function (file, chunk_entry_module, chunk_modules) { chunks[file] = { entry: chunk_entry_module, modules: chunk_modules }; }; } ${callNollupBundleInit(/** @type {NollupPlugin[]} */ (plugins))} ${format === 'cjs'? ` var result = _require(null, ${entryIndex}); var result_keys = Object.keys(result); if (result_keys.length === 1 && result_keys[0] === 'default') { module.exports = result.default; } else { module.exports = result; } `: ` return _require(null, ${entryIndex}); `} })({ `, files.join(','), ` }, typeof globalThis !== 'undefined'? globalThis : ( typeof self !== 'undefined' ? self : this )); ${format === 'amd'? (chunk.exports.length === 1 && chunk.exports[0] === 'default'? 'return __nollup_entry_exports.default;' : ( chunk.exports.map(declaration => { if (declaration === 'default') { return 'exports["default"] = __nollup_entry_exports.default;' } else { return `exports.${declaration} = __nollup_entry_exports.${declaration};` } }).join('\n') + '\nObject.defineProperty(exports, "__esModule", { value: true });' )) + '\n});' : ''} ${format === 'es'? chunk.exports.map(declaration => { if (declaration === 'default') { return 'export default __nollup_entry_exports.default;' } else { return `export var ${declaration} = __nollup_entry_exports.${declaration};` } }).join('\n') : ''} `, ].join('\n'); } }
@param {Object<string, NollupOutputModule>} modules @param {RollupOutputChunk} chunk @param {RollupOutputOptions} outputOptions @param {RollupConfigContainer} config @param {Array<NollupInternalModuleImport>} externalImports @return {string}
onGenerateChunk
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
function applyOutputFileNames (outputOptions, bundle, bundleOutputTypes) { let name_map = {}; bundle.forEach(curr => { if (!name_map[curr.name]) { name_map[curr.name] = []; } name_map[curr.name].push(curr); }); Object.keys(name_map).forEach(name => { let entries = name_map[name]; entries.forEach((entry, index) => { let name = entry.name + (index > 0? (index + 1) : ''); if (entry.isEntry && bundleOutputTypes[entry.facadeModuleId] === 'entry') { if (outputOptions.file) { entry.fileName = path.basename(outputOptions.file); } else { entry.fileName = formatFileName(outputOptions.format, name + '.js', outputOptions.entryFileNames); } } if (entry.isDynamicEntry || bundleOutputTypes[entry.facadeModuleId] === 'chunk') { entry.fileName = entry.fileName || formatFileName(outputOptions.format, name + '.js', outputOptions.chunkFileNames); } }); }); }
@param {RollupOutputOptions} outputOptions @param {RollupOutputFile[]} bundle @param {Object<string, string>} bundleOutputTypes
applyOutputFileNames
javascript
PepsRyuu/nollup
lib/impl/NollupCompiler.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCompiler.js
MIT
function resolveImportMetaProperty (plugins, moduleId, metaName, chunk, bundleReferenceIdMap) { if (metaName) { for (let i = 0; i < FILE_PROPS.length; i++) { if (metaName.startsWith(FILE_PROPS[i])) { let id = metaName.replace(FILE_PROPS[i], ''); let entry = bundleReferenceIdMap[id]; let replacement = plugins.hooks.resolveFileUrl( metaName, id, entry.fileName, chunk.fileName, moduleId ); return replacement || '"' + entry.fileName + '"'; } } } let replacement = plugins.hooks.resolveImportMeta(metaName, chunk.fileName, moduleId); if (replacement) { return replacement; } return 'import.meta.' + metaName; }
@param {PluginContainer} plugins @param {string} moduleId @param {string} metaName @param {RollupOutputChunk} chunk @param {Object<string, RollupOutputFile>} bundleReferenceIdMap @return {string}
resolveImportMetaProperty
javascript
PepsRyuu/nollup
lib/impl/NollupCompiler.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCompiler.js
MIT
async compile (context) { let generator = context.generator; context.plugins.start(); let bundle = /** @type {RollupOutputFile[]} */ ([]); let bundleError = /** @type {Error} */ (undefined); let bundleStartTime = Date.now(); let bundleEmittedChunks = /** @type {NollupInternalEmittedChunk[]} */ ([]); let bundleEmittedAssets = /** @type {NollupInternalEmittedAsset[]} */ ([]); let bundleModuleIds = new Set(); let bundleMetaProperties = {}; let bundleReferenceIdMap = /** @type {Object<string, RollupOutputChunk| RollupOutputAsset>} */ ({}); let bundleOutputTypes = /** @type {Object<String, string>} */ ({}); let bundleDynamicImports = /** @type {Object<string, string[]>} */ ({}); let bundleCirculars = []; let bundleExternalImports = /** @type {Object<string, NollupInternalModuleImport[]>} */ ({}); let invalidated = Object.keys(context.files).filter(filePath => context.files[filePath].invalidate); let addBundleEmittedChunks = function (dynamicImports, emittedChunks, modules) { dynamicImports.forEach(id => { // if the current chunk already includes the dynamic import content, then don't create a new chunk if (modules[id]) { return; } let found = bundleEmittedChunks.find(o => o.id === id); if (!found) { bundleEmittedChunks.push({ id: id, name: getNameFromFileName(id), isDynamicEntry: true, isEntry: false }); } }); Object.entries(emittedChunks).forEach(([referenceId, chunk]) => { let found = bundleEmittedChunks.find(o => o.id === chunk.id); let output = { id: chunk.id, name: chunk.name, isDynamicEntry: false, isEntry: true, fileName: chunk.fileName, referenceId: referenceId }; if (!found) { bundleEmittedChunks.push(output); } else { found.referenceId = referenceId; } }); }; context.currentBundle = bundle; context.currentBundleModuleIds = bundleModuleIds; context.currentBundleReferenceIdMap = bundleReferenceIdMap; context.currentEmittedAssets = bundleEmittedAssets; try { context.currentPhase = 'pre-build'; await context.plugins.hooks.buildStart(context.config); context.currentPhase = 'build'; let inputs = await context.input(); for (let i = 0; i < inputs.length; i++) { let { name, file } = inputs[i]; let emitted = await compileInputTarget(context, file, bundleModuleIds, generator, bundleEmittedAssets, true); bundle.push({ code: '', name: name, isEntry: true, isDynamicEntry: false, type: 'chunk', map: null, modules: emitted.modules, fileName: '', imports: emitted.externalImports.map(e => e.source), importedBindings: emitted.externalImports.reduce((acc, val) => { acc[val.source] = val.specifiers.map(s => s.imported); return acc; }, {}), dynamicImports: [], exports: context.files[file].exports.map(e => e.exported), facadeModuleId: file, implicitlyLoadedBefore: [], referencedFiles: [], isImplicitEntry: false }); addBundleEmittedChunks(emitted.dynamicImports, emitted.chunks, emitted.modules); bundleMetaProperties[file] = emitted.metaProperties; bundleOutputTypes[file] = 'entry'; bundleDynamicImports[file] = emitted.dynamicImports; bundleCirculars = bundleCirculars.concat(emitted.circulars); bundleExternalImports[file] = emitted.externalImports; } for (let i = 0; i < bundleEmittedChunks.length; i++) { let chunk = bundleEmittedChunks[i]; let emitted = await compileInputTarget(context, chunk.id, bundleModuleIds, generator, bundleEmittedAssets, chunk.isEntry); let bundleEntry = { code: '', name: chunk.name, isEntry: chunk.isEntry, isDynamicEntry: chunk.isDynamicEntry, type: /** @type {'chunk'} */ ('chunk'), map: null, modules: emitted.modules, fileName: chunk.fileName, facadeModuleId: chunk.id, imports: emitted.externalImports.map(e => e.source), importedBindings: emitted.externalImports.reduce((acc, val) => { acc[val.source] = val.specifiers; return acc; }, {}), dynamicImports: [], exports: context.files[chunk.id].exports.map(e => e.exported), implicitlyLoadedBefore: [], referencedFiles: [], isImplicitEntry: false }; addBundleEmittedChunks(emitted.dynamicImports, emitted.chunks, emitted.modules); bundleMetaProperties[chunk.id] = emitted.metaProperties; bundleOutputTypes[chunk.id] = 'chunk'; bundleDynamicImports[chunk.id] = emitted.dynamicImports; bundleReferenceIdMap[chunk.referenceId] = bundleEntry; bundleCirculars = bundleCirculars.concat(emitted.circulars); bundleExternalImports[chunk.id] = emitted.externalImports; bundle.push(bundleEntry); } } catch (e) { bundleError = e; throw e; } finally { context.currentPhase = 'post-build'; await context.plugins.hooks.buildEnd(bundleError); } if (bundleCirculars.length > 0) { let show = bundleCirculars.slice(0, 3); let hide = bundleCirculars.slice(3); show = show.map(t => t.map(t => t.replace(process.cwd(), '')).join(' -> ')); console.warn([ yellow('(!) Circular dependencies'), ...show, hide.length > 0? `...and ${hide.length} more` : '', yellow('Code may not run correctly. See https://github.com/PepsRyuu/nollup/blob/master/docs/circular.md') ].join('\n')); } applyOutputFileNames(context.config.output, bundle, bundleOutputTypes); context.currentPhase = 'generate'; bundleEmittedAssets.forEach(asset => { emitAssetToBundle(context.config.output, bundle, asset, bundleReferenceIdMap); }); let modules = /** @type {Object<String, NollupOutputModule>} */(null); try { await context.plugins.hooks.renderStart(context.config.output, context.config); // clone files and their code modules = Object.entries(context.files).reduce((acc, val) => { let [ id, file ] = val; acc[id] = { index: file.index, code: generator.onGenerateModulePreChunk(file, bundle, context.files), }; return acc; }, {}); // Rendering hooks let [ banner, intro, outro, footer ] = await Promise.all([ context.plugins.hooks.banner(), context.plugins.hooks.intro(), context.plugins.hooks.outro(), context.plugins.hooks.footer() ]); for (let i = 0; i < bundle.length; i++) { let bundleEntry = /** @type {RollupOutputChunk} */ (bundle[i]); if (bundleEntry.type === 'chunk') { Object.entries(bundleMetaProperties[bundleEntry.facadeModuleId]).forEach(([moduleId, metaNames]) => { metaNames.forEach(metaName => { let resolved = resolveImportMetaProperty(context.plugins, moduleId, metaName, bundleEntry, bundleReferenceIdMap); modules[moduleId].code = modules[moduleId].code.replace( metaName === null? new RegExp('import\\.meta') : new RegExp('import\\.meta\\.' + metaName, 'g'), resolved ); }); }); bundleEntry.code = banner + '\n' + intro + '\n' + generator.onGenerateChunk(modules, bundleEntry, context.config.output, context.config, bundleExternalImports[bundleEntry.facadeModuleId]) + '\n' + outro + '\n' + footer; await context.plugins.hooks.renderChunk(bundleEntry.code, bundleEntry, context.config.output); } } } catch (e) { await context.plugins.hooks.renderError(e); throw e; } await context.plugins.hooks.generateBundle(context.config.output, bundle); let removedIds = [...context.previousBundleModuleIds].filter(i => !bundleModuleIds.has(i)); let addedIds = [...bundleModuleIds].filter(i => !context.previousBundleModuleIds.has(i)); let changedIds = new Set(addedIds.concat(invalidated)); context.previousBundleModuleIds = bundleModuleIds; let changes = removedIds.map(f => ({ id: context.files[f].index, code: '', removed: true })).concat([...changedIds].map(f => ({ id: context.files[f].index, code: generator.onGenerateModuleChange(modules[f]), removed: false }))); return { stats: { time: Date.now() - bundleStartTime }, changes: changes, output: bundle } }
@param {NollupContext} context @return {Promise<NollupCompileOutput>}
compile
javascript
PepsRyuu/nollup
lib/impl/NollupCompiler.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCompiler.js
MIT
async function resolveInputId (context, id) { let resolved = await context.plugins.hooks.resolveId(id, undefined, { isEntry: true }); if ((typeof resolved === 'object' && resolved.external)) { throw new Error('Input cannot be external'); } return typeof resolved === 'object' && resolved.id; }
@param {NollupContext} context @param {string} id @return {Promise<string>}
resolveInputId
javascript
PepsRyuu/nollup
lib/impl/NollupContext.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupContext.js
MIT
async function getInputEntries (context, input) { if (typeof input === 'string') { input = await resolveInputId(context, input); return [{ name: getNameFromFileName(input), file: input }]; } if (Array.isArray(input)) { return await Promise.all(input.map(async file => { file = await resolveInputId(context, file); return { name: getNameFromFileName(file), file: file }; })); } if (typeof input === 'object') { return await Promise.all(Object.keys(input).map(async key => { let file = await resolveInputId(context, input[key]); return { name: key, file: file }; })); } }
@param {NollupContext} context @param {string|string[]|Object<string, string>} input @return {Promise<{name: string, file: string}[]>}
getInputEntries
javascript
PepsRyuu/nollup
lib/impl/NollupContext.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupContext.js
MIT
async initialize (options) { this.config = new RollupConfigContainer(options); if (this.config.acornInjectPlugins) { AcornParser.inject(this.config.acornInjectPlugins); } this.files = /** @type {Object<string, NollupInternalModule>} */ ({}); this.rawWatchFiles = /** @type {Object<string, string[]>} */ ({}); this.watchFiles = /** @type {Object<string, string>} */ ({}); this.currentBundle = /** @type {RollupOutputFile[]} */ (null); this.currentBundleModuleIds = /** @type {Set<string>}*/ (null); this.currentPhase = /** @type {string} */ (null); this.currentModuleEmittedAssetsCache = /** @type {Object<string, RollupEmittedAsset>} */ (null); this.currentModuleEmittedChunksCache = /** @type {Object<string, RollupEmittedChunk>} */ (null); this.currentEmittedAssets = /** @type {NollupInternalEmittedAsset[]} */ (null); this.currentBundleReferenceIdMap = /** @type {Object<String, RollupOutputFile>} */ (null); this.plugins = new PluginContainer(this.config, AcornParser); this.plugins.start(); this.plugins.onAddWatchFile((source, parent) => { if (!this.rawWatchFiles[parent]) { this.rawWatchFiles[parent] = []; } this.rawWatchFiles[parent].push(source); this.watchFiles[resolvePath(source, process.cwd() + '/__entry__')] = parent; }); this.plugins.onGetWatchFiles(() => { let result = Object.keys(this.files); Object.entries(this.rawWatchFiles).forEach(([parent, watchFiles]) => { let parentIndex = result.indexOf(parent); let start = result.slice(0, parentIndex + 1); let end = result.slice(parentIndex + 1); result = start.concat(watchFiles).concat(end); }); return result; }); this.plugins.onEmitFile((referenceId, emitted) => { if (this.currentPhase === 'build') { if (emitted.type === 'asset') { this.currentModuleEmittedAssetsCache[referenceId] = emitted; } if (emitted.type === 'chunk') { this.currentModuleEmittedChunksCache[referenceId] = emitted; } } else if (this.currentPhase === 'generate') { if (emitted.type === 'asset') { let asset = { ...emitted, referenceId: referenceId }; emitAssetToBundle(this.config.output, /** @type {RollupOutputAsset[]} */ (this.currentBundle), asset, this.currentBundleReferenceIdMap); } if (emitted.type === 'chunk') { throw new Error('Cannot emit chunks after module loading has finished.'); } } }); this.plugins.onGetFileName(referenceId => { if (this.currentPhase === 'generate') { return this.currentBundleReferenceIdMap[referenceId].fileName; } throw new Error('File name not available yet.'); }); this.plugins.onSetAssetSource((referenceId, source) => { let found = this.currentBundleReferenceIdMap[referenceId] || this.currentEmittedAssets.find(a => a.referenceId === referenceId) || this.currentModuleEmittedAssetsCache[referenceId]; if (found) { found.source = source; } }); this.plugins.onGetModuleIds(() => { return this.currentBundleModuleIds.values(); }); this.plugins.onGetModuleInfo(id => { let file = this.files[id]; if (file) { return { id: id, code: file.transformedCode || null, isEntry: file.isEntry, isExternal: false, importedIds: file.externalImports.map(i => i.source).concat(file.imports.map(i => i.source)), importedIdResolutions: file.externalImports.map(i => ({ id: i.source, external: true, meta: this.plugins.__meta[i.source] || {}, syntheticNamedExports: false, moduleSideEffects: true })).concat(file.imports.map(i => ({ id: i.source, external: false, meta: this.plugins.__meta[i.source] || {}, syntheticNamedExports: Boolean(file[i.source] && file[i.source].syntheticNamedExports), moduleSideEffects: true }))), dynamicallyImportedIds: file.externalDynamicImports.concat(file.dynamicImports), dynamicallyImportedIdResolutions: file.externalDynamicImports.map(i => ({ id: i, external: true, meta: this.plugins.__meta[i] || {}, syntheticNamedExports: false, moduleSideEffects: true })).concat(file.dynamicImports.map(i => ({ id: i, external: false, meta: this.plugins.__meta[i] || {}, syntheticNamedExports: Boolean(file[i] && file[i].syntheticNamedExports), moduleSideEffects: true }))), syntheticNamedExports: file.syntheticNamedExports, hasDefaultExport: !file.rawAst? null : Boolean(file.rawAst.exports.find(e => e.type === 'default')) }; } else { // Probably external return { id: id, code: null, isEntry: false, isExternal: true, }; } }); this.plugins.onLoad(async ({ id, syntheticNamedExports, resolveDependencies, meta}) => { if (meta) { this.plugins.__meta[id] = meta; } await this.load(id, null, false, syntheticNamedExports, resolveDependencies); }); this.liveBindings = /** @type {Boolean|String} */(false); this.generator = new NollupCodeGenerator(this); this.indexGenerator = 0; this.previousBundleModuleIds = new Set(); this.resolvedInputs = undefined; if (!this.config.input) { throw new Error('Input option not defined'); } this.input = async () => { if (!this.resolvedInputs) { this.resolvedInputs = await getInputEntries(this, this.config.input); } return this.resolvedInputs; } }
@param {RollupOptions} options @return {Promise<void>}
initialize
javascript
PepsRyuu/nollup
lib/impl/NollupContext.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupContext.js
MIT
function resolveDefaultExport (container, input, output, node, currentpath, generator) { generator.onESMNodeFound(currentpath, node, undefined); output.exports.push({ local: '', exported: 'default' }); }
@param {PluginContainer} container @param {string} input @param {Object} output @param {ESTree} node @param {CodeGenerator} generator
resolveDefaultExport
javascript
PepsRyuu/nollup
lib/impl/NollupImportExportResolver.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupImportExportResolver.js
MIT
async function resolveNamedExport (container, input, output, node, currentpath, generator, liveBindings) { let exports = []; // export function / class / let... if (node.declaration) { let dec = node.declaration; // Singular export declaration if (dec.id) { exports.push({ local: dec.id.name, exported: dec.id.name }); } // Multiple export declaration if (dec.declarations) { dec.declarations.forEach(node => { if (node.id.type === 'ObjectPattern') { node.id.properties.forEach(prop => { exports.push({ local: prop.value.name, exported: prop.value.name }); }); } else { if (!liveBindings &&!node.init) { output.exportLiveBindings.push(node.id.name); return ``; } exports.push({ local: node.id.name, exported: node.id.name }); } }); } } // export { specifier, specifier } if (node.specifiers.length > 0) { let dep; // export { imported } from './file.js'; if (node.source) { dep = await resolveImport(container, input, output, node, currentpath, generator); dep.export = true; } node.specifiers.forEach(spec => { /** @type {{local: string, exported: string}} */ let _export; if (spec.type === 'ExportSpecifier') { if (node.source) { _export = { local: spec.exported.name, exported: spec.exported.name }; } else { _export = { local: spec.local.name, exported: spec.exported.name } } exports.push(_export); } }); } if (!node.source) { generator.onESMNodeFound(currentpath, node, exports); } exports.forEach(e => output.exports.push(e)); }
@param {PluginContainer} container @param {string} input @param {Object} output @param {ESTree} node @param {string} currentpath @param {CodeGenerator} generator @param {Boolean|String} liveBindings
resolveNamedExport
javascript
PepsRyuu/nollup
lib/impl/NollupImportExportResolver.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupImportExportResolver.js
MIT
async function resolveAllExport (container, input, output, node, currentpath, generator) { // export * from './file'; let dep = await resolveImport(container, input, output, node, currentpath, generator); if (!dep) { return; } dep.export = true; dep.specifiers.push({ imported: '*' }); }
@param {PluginContainer} container @param {string} input @param {Object} output @param {ESTree} node @param {string} currentpath @param {CodeGenerator} generator
resolveAllExport
javascript
PepsRyuu/nollup
lib/impl/NollupImportExportResolver.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupImportExportResolver.js
MIT
function resolveMetaProperty (container, input, output, node, currentpath, generator) { let name = node.type === 'MetaProperty'? null : node.property && node.property.name; output.metaProperties.push(name); generator.onESMNodeFound(currentpath, node, name); }
@param {PluginContainer} container @param {string} input @param {Object} output @param {ESTree} node @param {string} currentpath @param {CodeGenerator} generator
resolveMetaProperty
javascript
PepsRyuu/nollup
lib/impl/NollupImportExportResolver.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupImportExportResolver.js
MIT
async function resolveDynamicImport (container, input, output, node, currentpath, generator) { let arg = node.source; let value; if (arg.type === 'Literal') { value = arg.value; } if (arg.type === 'TemplateLiteral') { if (arg.expressions.length === 0 && arg.quasis[0] && arg.quasis[0].value.raw) { value = arg.quasis[0].value.raw; } } let resolved = await container.hooks.resolveDynamicImport(value || arg, currentpath); let external = false; if ((typeof resolved === 'object' && resolved.external)) { output.externalDynamicImports.push(resolved.id || value); external = true; } if (typeof resolved.id === 'string' && !external) { output.dynamicImports.push(resolved.id); } generator.onESMNodeFound(currentpath, node, { resolved, external }); }
@param {PluginContainer} container @param {string} input @param {Object} output @param {ESTree} node @param {string} currentpath @param {CodeGenerator} generator
resolveDynamicImport
javascript
PepsRyuu/nollup
lib/impl/NollupImportExportResolver.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupImportExportResolver.js
MIT
async function resolveImport (container, input, output, node, currentpath, generator) { let resolved = await container.hooks.resolveId(node.source.value, currentpath); let dependency = { source: undefined, specifiers: [] }; if (resolved.external) { dependency.external = true; } if (resolved.syntheticNamedExports) { dependency.syntheticNamedExports = resolved.syntheticNamedExports; } if (dependency.external) { dependency.source = (resolved && resolved.external && resolved.id) || node.source.value; output.externalImports.push(dependency); } else { dependency.source = resolved.id; output.imports.push(dependency); } if (node.specifiers && node.specifiers.length > 0) { node.specifiers.forEach(specifier => { if (specifier.type === 'ImportDefaultSpecifier') { dependency.specifiers.push({ local: specifier.local.name, imported: 'default' }); } if (specifier.type === 'ImportSpecifier') { dependency.specifiers.push({ local: specifier.local.name, imported: specifier.imported.name }); } if (specifier.type === 'ImportNamespaceSpecifier') { dependency.specifiers.push({ local: specifier.local.name, imported: '*' }); } if (specifier.type === 'ExportSpecifier') { dependency.specifiers.push({ local: specifier.exported.name, imported: specifier.local.name }); } }); } generator.onESMNodeFound(currentpath, node, dependency); return dependency; }
@param {PluginContainer} container @param {string} input @param {Object} output @param {ESTree} node @param {string} currentpath @param {CodeGenerator} generator
resolveImport
javascript
PepsRyuu/nollup
lib/impl/NollupImportExportResolver.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupImportExportResolver.js
MIT
function walkSimpleLiveBindings (container, input, output, nodes, found, level, generator, currentpath) { for (let i = 0; i < nodes.length; i++) { let node = nodes[i]; let locals = []; if (!node) { continue; } if ( node.type === 'AssignmentExpression' && node.left.type === 'Identifier' && output.exportLiveBindings.indexOf(node.left.name) > -1 ) { if (found.indexOf(node.left.name) === -1) { found.push(node.left.name); } } walkSimpleLiveBindings(container, input, output, findChildNodes(node), found, level + 1, generator, currentpath); if (level === 0 && found.length > 0) { generator.onESMLateInitFound(currentpath, node, found); found = []; } } }
@param {PluginContainer} container @param {string} input @param {Object} output @param {Array<ESTree>} nodes @param {Array<string>} found @param {number} level @param {CodeGenerator} generator
walkSimpleLiveBindings
javascript
PepsRyuu/nollup
lib/impl/NollupImportExportResolver.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupImportExportResolver.js
MIT
async function findESMNodes (nodes, output) { for (let i = 0; i < nodes.length; i++) { let node = nodes[i]; if (!node) { // There's a possibility of null nodes continue; } if (node.type === 'ImportDeclaration') { output.imports.push({ node }); continue; } else if (node.type === 'ExportDefaultDeclaration') { output.exports.push({ type: 'default', node }); } else if (node.type === 'ExportNamedDeclaration') { output.exports.push({ type: 'named', node }); } else if (node.type === 'ExportAllDeclaration') { output.exports.push({ type: 'all', node }); continue; } else if (node.type === 'ImportExpression') { output.dynamicImports.push({ node }); } else if (node.type === 'MetaProperty' || (node.object && node.object.type === 'MetaProperty')) { output.metaProperties.push({ node }); continue; } findESMNodes(findChildNodes(node), output); } }
@param {PluginContainer} container @param {string} input @param {Object} output @param {Array<ESTree>} nodes @param {Array<string>} found @param {number} level @param {CodeGenerator} generator
findESMNodes
javascript
PepsRyuu/nollup
lib/impl/NollupImportExportResolver.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupImportExportResolver.js
MIT
getBindings(code) { // TODO: Store the ast for later parsing? let ast = AcornParser.parse(code); let output = { imports: [], exports: [], dynamicImports: [], metaProperties: [] }; findESMNodes(ast.body, output); return { ast, ...output } }
@param {PluginContainer} container @param {string} input @param {Object} output @param {Array<ESTree>} nodes @param {Array<string>} found @param {number} level @param {CodeGenerator} generator
getBindings
javascript
PepsRyuu/nollup
lib/impl/NollupImportExportResolver.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupImportExportResolver.js
MIT
async transformBindings(container, input, raw, currentpath, generator, liveBindings) { let output = { imports: [], externalImports: [], exports: [], dynamicImports: [], externalDynamicImports: [], metaProperties: [], dynamicMappings: {}, exportLiveBindings: [] }; generator.onESMEnter(input, currentpath, raw.ast); for (let i = 0; i < raw.imports.length; i++) { await resolveImport(container, input, output, raw.imports[i].node, currentpath, generator); } for (let i = 0; i < raw.exports.length; i++) { let { type, node } = raw.exports[i]; if (type === 'default') { resolveDefaultExport(container, input, output, node, currentpath, generator); continue; } if (type === 'named') { await resolveNamedExport(container, input, output, node, currentpath, generator, liveBindings); continue; } if (type === 'all') { await resolveAllExport(container, input, output, node, currentpath, generator); continue; } } for (let i = 0; i < raw.dynamicImports.length; i++) { await resolveDynamicImport(container, input, output, raw.dynamicImports[i].node, currentpath, generator); } for (let i = 0; i < raw.metaProperties.length; i++) { resolveMetaProperty(container, input, output, raw.metaProperties[i].node, currentpath, generator); } if (!liveBindings && output.exportLiveBindings.length > 0) { walkSimpleLiveBindings(container, input, output, raw.ast.body, [], 0, generator, currentpath); } if (liveBindings === 'reference') { LiveBindingResolver(output.imports, raw.ast.body, generator, currentpath) } let { code, map } = generator.onESMLeave(input, currentpath, raw.ast); output.code = code; output.map = map; return output; }
@param {PluginContainer} container @param {string} input @param {string} currentpath @param {CodeGenerator} generator @param {Boolean|String} liveBindings @return {Promise<Object>}
transformBindings
javascript
PepsRyuu/nollup
lib/impl/NollupImportExportResolver.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupImportExportResolver.js
MIT
function NollupLiveBindingsResolver (imports, ast, generator, currentpath) { let specifiers = imports.flatMap(i => i.specifiers.map(s => s.local)); transformImportReferences(specifiers, ast, generator, currentpath); }
@param {NollupInternalModuleImport[]} imports @param {ESTree} ast @param {NollupCodeGenerator} generator
NollupLiveBindingsResolver
javascript
PepsRyuu/nollup
lib/impl/NollupLiveBindingsResolver.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupLiveBindingsResolver.js
MIT
constructor (config, parser) { this.__config = config; this.__meta = {}; this.__currentModuleId = null; this.__currentMapChain = null; this.__currentOriginalCode = null; this.__currentLoadQueue = []; this.__parser = parser; this.__errorState = true; this.__onAddWatchFile = (source, parent) => {}; this.__onGetWatchFiles = () => ([]); this.__onEmitFile = (referenceId, emittedFile) => {}; this.__onGetFileName = (referenceId) => ''; this.__onGetModuleIds = () => new Set().values(); this.__onGetModuleInfo = (id) => ({}); this.__onSetAssetSource = (id, source) => {}; this.__onLoad = (resolvedId) => Promise.resolve(); this.__errorHandler = new PluginErrorHandler(); this.__errorHandler.onThrow(() => { this.__errorState = true; }); this.__plugins = (config.plugins || []).map(plugin => ({ execute: plugin, context: PluginContext.create(this, plugin), error: this.__errorHandler })); this.hooks = /** @type {PluginLifecycleHooks} */ (Object.entries(PluginLifecycle.create(this)).reduce((acc, val) => { if (val[0] === 'buildEnd' || val[0] === 'renderError' || val[0] === 'watchChange') { acc[val[0]] = val[1]; return acc; } acc[val[0]] = (...args) => { if (this.__errorState) { throw new Error('PluginContainer "start()" method must be called before going further.'); } // @ts-ignore return val[1](...args); } return acc; }, {})); }
@param {RollupConfigContainer} config @param {{parse: function(string, object): ESTree}} parser
constructor
javascript
PepsRyuu/nollup
lib/impl/PluginContainer.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginContainer.js
MIT
onAddWatchFile (callback) { // Local copy of watch files for the getWatchFiles method, but also triggers this event this.__onAddWatchFile = callback; }
Receives source and parent file if any. @param {function(string, string): void} callback
onAddWatchFile
javascript
PepsRyuu/nollup
lib/impl/PluginContainer.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginContainer.js
MIT
onGetWatchFiles (callback) { this.__onGetWatchFiles = callback; }
Must return a list of files that are being watched. @param {function(): string[]} callback
onGetWatchFiles
javascript
PepsRyuu/nollup
lib/impl/PluginContainer.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginContainer.js
MIT
onGetModuleInfo (callback) { this.__onGetModuleInfo = callback; }
Receives the requested module. Must return module info. @param {function(string): object} callback
onGetModuleInfo
javascript
PepsRyuu/nollup
lib/impl/PluginContainer.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginContainer.js
MIT
onSetAssetSource (callback) { this.__onSetAssetSource = callback; }
Receives asset reference id, and source. @param {function(string, string|Uint8Array): void} callback
onSetAssetSource
javascript
PepsRyuu/nollup
lib/impl/PluginContainer.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginContainer.js
MIT
onGetModuleIds (callback) { this.__onGetModuleIds = callback; }
Must return iterable of all modules in the current bundle. @param {function(): IterableIterator<string>} callback
onGetModuleIds
javascript
PepsRyuu/nollup
lib/impl/PluginContainer.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginContainer.js
MIT
onLoad (callback) { this.__onLoad = callback; }
Must load the module. @param {function(): Promise<void>} callback
onLoad
javascript
PepsRyuu/nollup
lib/impl/PluginContainer.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginContainer.js
MIT
create (container, plugin) { let context = { meta: PluginMeta, /** * @return {IterableIterator<string>} */ get moduleIds () { return context.getModuleIds(); }, /** * @param {string} filePath */ addWatchFile (filePath) { container.__onAddWatchFile(filePath, container.__currentModuleId); }, /** * @param {RollupEmittedFile} file * @return {string} */ emitFile (file) { if (!file.type) { // @ts-ignore file.type = file.source? 'asset' : 'chunk'; } if (!file.name) { file.name = file.type; } let referenceId = getReferenceId(); if (file.type === 'asset') { let asset = { type: file.type, name: file.name, source: file.source, fileName: file.fileName }; container.__onEmitFile(referenceId, asset); } if (file.type === 'chunk') { let chunk = { type: file.type, name: file.name, fileName: file.fileName, id: resolvePath(file.id, process.cwd() + '/__entry') }; container.__onEmitFile(referenceId, chunk); } return referenceId; }, /** * @return {RollupSourceMap} */ getCombinedSourcemap () { if (!container.__currentMapChain) { throw new Error('getCombinedSourcemap can only be called in transform hook'); } return combineSourceMapChain(container.__currentMapChain, container.__currentOriginalCode, container.__currentModuleId); }, /** * @param {string} id * @return {string} */ getFileName (id) { return container.__onGetFileName(id); }, /** * @return {IterableIterator<string>} */ getModuleIds () { return container.__onGetModuleIds(); }, /** * @param {string} id * @return {RollupModuleInfo} */ getModuleInfo (id) { return getModuleInfo(container, id); }, /** * @param {string} importee * @param {string} importer * @param {{ isEntry?: boolean, custom?: import('rollup').CustomPluginOptions, skipSelf?: boolean }} options * @return {Promise<RollupResolveId>} */ async resolve (importee, importer, options = {}) { if (options.skipSelf) { PluginLifecycle.resolveIdSkips.add(plugin, importer, importee); } try { return await PluginLifecycle.resolveIdImpl(container, importee, importer, { isEntry: options.isEntry, custom: options.custom }); } finally { if (options.skipSelf) { PluginLifecycle.resolveIdSkips.remove(plugin, importer, importee); } } }, /** * @param {import('rollup').ResolvedId} resolvedId * @return {Promise<RollupModuleInfo>} */ async load(resolvedId) { await container.__onLoad(resolvedId); return context.getModuleInfo(resolvedId.id); }, /** * @param {string} code * @param {Object} options * @return {ESTree} */ parse (code, options) { return container.__parser.parse(code, options); }, /** * @param {string} e */ warn (e) { container.__errorHandler.warn(e); }, /** * @param {string|Error} e */ error (e) { container.__errorHandler.throw(e); }, /** * @param {string} name * @param {string|Uint8Array} source * @return {string} */ emitAsset (name, source) { return context.emitFile({ type: 'asset', name: name, source: source }); }, /** * @param {string} id * @param {Object} options * @return {string} */ emitChunk (id, options = {}) { return context.emitFile({ type: 'chunk', id: id, name: options.name }); }, /** * @param {string} id * @return {string} */ getAssetFileName (id) { return context.getFileName(id); }, /** * @param {string} id * @return {string} */ getChunkFileName (id) { return context.getFileName(id); }, /** * @param {string} id * @param {string|Uint8Array} source */ setAssetSource (id, source) { container.__onSetAssetSource(id, source); }, isExternal () { throw new Error('isExternal: deprecated in Rollup, not implemented'); }, /** * @param {string} importee * @param {string} importer * @return {Promise<RollupResolveId>} */ async resolveId (importee, importer) { let result = await container.hooks.resolveId(importee, importer); if (typeof result === 'object') { if (result.external) { return null; } return result.id; } return result; }, /** * @return {string[]} */ getWatchFiles () { return container.__onGetWatchFiles(); }, cache: null }; // @ts-ignore return context; }
@param {PluginContainer} container @param {RollupPlugin} plugin @return {RollupPluginContext}
create
javascript
PepsRyuu/nollup
lib/impl/PluginContext.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginContext.js
MIT
async resolve (importee, importer, options = {}) { if (options.skipSelf) { PluginLifecycle.resolveIdSkips.add(plugin, importer, importee); } try { return await PluginLifecycle.resolveIdImpl(container, importee, importer, { isEntry: options.isEntry, custom: options.custom }); } finally { if (options.skipSelf) { PluginLifecycle.resolveIdSkips.remove(plugin, importer, importee); } } }
@param {string} importee @param {string} importer @param {{ isEntry?: boolean, custom?: import('rollup').CustomPluginOptions, skipSelf?: boolean }} options @return {Promise<RollupResolveId>}
resolve
javascript
PepsRyuu/nollup
lib/impl/PluginContext.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginContext.js
MIT
async load(resolvedId) { await container.__onLoad(resolvedId); return context.getModuleInfo(resolvedId.id); }
@param {import('rollup').ResolvedId} resolvedId @return {Promise<RollupModuleInfo>}
load
javascript
PepsRyuu/nollup
lib/impl/PluginContext.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginContext.js
MIT
parse (code, options) { return container.__parser.parse(code, options); }
@param {string} code @param {Object} options @return {ESTree}
parse
javascript
PepsRyuu/nollup
lib/impl/PluginContext.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginContext.js
MIT
emitAsset (name, source) { return context.emitFile({ type: 'asset', name: name, source: source }); }
@param {string} name @param {string|Uint8Array} source @return {string}
emitAsset
javascript
PepsRyuu/nollup
lib/impl/PluginContext.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginContext.js
MIT
emitChunk (id, options = {}) { return context.emitFile({ type: 'chunk', id: id, name: options.name }); }
@param {string} id @param {Object} options @return {string}
emitChunk
javascript
PepsRyuu/nollup
lib/impl/PluginContext.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginContext.js
MIT
setAssetSource (id, source) { container.__onSetAssetSource(id, source); }
@param {string} id @param {string|Uint8Array} source
setAssetSource
javascript
PepsRyuu/nollup
lib/impl/PluginContext.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginContext.js
MIT
isExternal () { throw new Error('isExternal: deprecated in Rollup, not implemented'); }
@param {string} id @param {string|Uint8Array} source
isExternal
javascript
PepsRyuu/nollup
lib/impl/PluginContext.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginContext.js
MIT
async resolveId (importee, importer) { let result = await container.hooks.resolveId(importee, importer); if (typeof result === 'object') { if (result.external) { return null; } return result.id; } return result; }
@param {string} importee @param {string} importer @return {Promise<RollupResolveId>}
resolveId
javascript
PepsRyuu/nollup
lib/impl/PluginContext.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginContext.js
MIT
throw (e) { e = format(e); if (!this.__errorThrown) { this.__errorThrown = true; this.__onThrow(); if (this.__asyncErrorListener) { this.__asyncErrorListener(e); } else { throw e; } } }
@param {object|string} e @return {void|never}
throw
javascript
PepsRyuu/nollup
lib/impl/PluginErrorHandler.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginErrorHandler.js
MIT
async function _callAsyncHook (plugin, hook, args) { let handler = plugin.execute[hook]; if (typeof handler === 'string') { return handler; } if (typeof handler === 'object') { handler = handler.handler; } if (handler) { let hr = handler.apply(plugin.context, args); if (hr instanceof Promise) { return (await plugin.error.wrapAsync(hr)); } return hr; } }
@param {NollupInternalPluginWrapper} plugin @param {string} hook @param {any[]} args @return {Promise<any>}
_callAsyncHook
javascript
PepsRyuu/nollup
lib/impl/PluginLifecycle.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginLifecycle.js
MIT
function _callSyncHook (plugin, hook, args) { let handler = plugin.execute[hook]; if (typeof handler === 'object') { handler = handler.handler; } if (handler) { return handler.apply(plugin.context, args); } }
@param {NollupInternalPluginWrapper} plugin @param {string} hook @param {any[]} args @return {any}
_callSyncHook
javascript
PepsRyuu/nollup
lib/impl/PluginLifecycle.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginLifecycle.js
MIT
function _getSortedPlugins(plugins, hook) { plugins = plugins.slice(0); return plugins.filter(p => { return typeof p.execute[hook] === 'object' && p.execute[hook].order === 'pre'; }).concat(plugins.filter(p => { return typeof p.execute[hook] === 'function' || typeof p.execute[hook] === 'string' || (typeof p.execute[hook] === 'object' && !p.execute[hook].order); })).concat(plugins.filter(p => { return typeof p.execute[hook] === 'object' && p.execute[hook].order === 'post'; })); }
@param {NollupInternalPluginWrapper} plugin @param {string} hook @param {any[]} args @return {any}
_getSortedPlugins
javascript
PepsRyuu/nollup
lib/impl/PluginLifecycle.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginLifecycle.js
MIT
async function callAsyncFirstHook (container, hook, args) { // hook may return a promise. // waits for hook to return value other than null or undefined. let plugins = _getSortedPlugins(container.__plugins, hook); for (let i = 0; i < plugins.length; i++) { let hr = await _callAsyncHook(plugins[i], hook, args); if (hr !== null && hr !== undefined) { return hr; } } }
@param {PluginContainer} container @param {string} hook @param {any[]} args @return {Promise<any>}
callAsyncFirstHook
javascript
PepsRyuu/nollup
lib/impl/PluginLifecycle.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginLifecycle.js
MIT
async function callAsyncSequentialHook (container, hook, toArgs, fromResult, start) { // hook may return a promise. // all plugins that implement this hook will run, passing data onwards let plugins = _getSortedPlugins(container.__plugins, hook); let output = start; for (let i = 0; i < plugins.length; i++) { let args = toArgs(output); let hr = await _callAsyncHook(plugins[i], hook, args); if (hr !== null && hr !== undefined) { output = fromResult(hr, output); } } return output; }
@param {PluginContainer} container @param {string} hook @param {function} toArgs @param {function} fromResult @param {any} start @return {Promise}
callAsyncSequentialHook
javascript
PepsRyuu/nollup
lib/impl/PluginLifecycle.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginLifecycle.js
MIT
async function callAsyncParallelHook (container, hook, args) { // hooks may return promises. // all hooks are executed at the same time without waiting // will wait for all hooks to complete before returning let hookResults = []; let plugins = _getSortedPlugins(container.__plugins, hook); let previous = []; for (let i = 0; i < plugins.length; i++) { if (typeof plugins[i].execute[hook] === 'object' && plugins[i].execute[hook].sequential) { let values = await Promise.all(previous); hookResults.push(...values); previous = []; let v = await _callAsyncHook(plugins[i], hook, args); hookResults.push(v); continue; } previous.push(_callAsyncHook(plugins[i], hook, args)); } let values = await Promise.all(previous); hookResults.push(...values); return hookResults; }
@param {PluginContainer} container @param {string} hook @param {any[]} args @return {Promise}
callAsyncParallelHook
javascript
PepsRyuu/nollup
lib/impl/PluginLifecycle.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginLifecycle.js
MIT
function callSyncFirstHook (container, hook, args) { let plugins = _getSortedPlugins(container.__plugins, hook); // waits for hook to return value other than null of undefined for (let i = 0; i < plugins.length; i++) { let hr = _callSyncHook(plugins[i], hook, args); if (hr !== null && hr !== undefined) { return hr; } } }
@param {PluginContainer} container @param {string} hook @param {any[]} args @return {any}
callSyncFirstHook
javascript
PepsRyuu/nollup
lib/impl/PluginLifecycle.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginLifecycle.js
MIT
function callSyncSequentialHook (container, hook, args) { // all plugins that implement this hook will run, passing data onwards let plugins = _getSortedPlugins(container.__plugins, hook); let output = args[0]; for (let i = 0; i < plugins.length; i++) { let hr = _callSyncHook(plugins[i], hook, [output]); if (hr !== null && hr !== undefined) { output = hr; } } return output; }
@param {PluginContainer} container @param {string} hook @param {any[]} args @return {any}
callSyncSequentialHook
javascript
PepsRyuu/nollup
lib/impl/PluginLifecycle.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginLifecycle.js
MIT
function handleMetaProperty (container, filePath, meta) { if (meta) { let fileMeta = container.__meta[filePath]; if (!fileMeta) { fileMeta = {}; container.__meta[filePath] = fileMeta; } for (let prop in meta) { fileMeta[prop] = meta[prop]; } } }
@param {PluginContainer} container @param {string} filePath @param {Object} meta
handleMetaProperty
javascript
PepsRyuu/nollup
lib/impl/PluginLifecycle.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginLifecycle.js
MIT
function triggerNotImplemented(name, args) { let error = `"${name}" not implemented`; console.error(error, args); throw new Error(error); }
@param {string} name @param {any[]} args
triggerNotImplemented
javascript
PepsRyuu/nollup
lib/impl/PluginLifecycle.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginLifecycle.js
MIT
function isExternal (config, name) { if (config && config.external) { let external = config.external; if (Array.isArray(external)) { return external.indexOf(name) > -1; } if (typeof external === 'function') { return external(name, undefined, undefined); } } return false; }
@param {RollupConfigContainer} config @param {string} name @return {boolean | void}
isExternal
javascript
PepsRyuu/nollup
lib/impl/PluginLifecycle.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginLifecycle.js
MIT
async resolveIdImpl (container, id, parentFilePath, options = {}) { options.isEntry = options.isEntry || false; options.custom = options.hasOwnProperty('custom')? options.custom : {}; let __plugins = container.__plugins.filter(p => !this.resolveIdSkips.contains(p.execute, parentFilePath, id)); let hr = await callAsyncFirstHook(/** @type {PluginContainer} */ ({ __plugins, __config: container.__config }), 'resolveId', [id, parentFilePath, options]); if (hr === false || isExternal(container.__config, id)) { return { id, external: true }; } if (typeof hr === 'string') { hr = { id: path.isAbsolute(hr)? path.normalize(hr) : hr, external: false }; } if (!hr) { let parent = parentFilePath || path.resolve(process.cwd(), '__entry'); hr = { id: path.normalize(resolvePath(id, parent)), external: false }; if (!fs.existsSync(hr.id)) { hr.external = true; hr.id = id; } } handleMetaProperty(container, hr.id, hr.meta); return hr; }
@param {PluginContainer} container @param {string} id @param {string} parentFilePath @return {Promise<RollupResolveIdResult>}
resolveIdImpl
javascript
PepsRyuu/nollup
lib/impl/PluginLifecycle.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginLifecycle.js
MIT
function prepareSourceMapChain (mapChain, original_code, filepath) { mapChain = mapChain.filter(o => o.map && o.map.mappings).reverse(); if (mapChain.length > 1) { mapChain.forEach((obj, index) => { obj.map.version = 3; obj.map.file = filepath + '_' + index; // Check is in place because some transforms return sources, in particular multi-file sources. obj.map.sources = obj.map.sources.length === 1? [filepath + '_' + (index + 1)] : obj.map.sources; if(obj.map.sourcesContent && obj.map.sourcesContent.length === 1) { obj.map.sourcesContent = [mapChain[index + 1] ? mapChain[index + 1].code : original_code] } }); } return mapChain; }
@param {NollupTransformMapEntry[]} mapChain @param {string} original_code @param {string} filepath @return {NollupTransformMapEntry[]}
prepareSourceMapChain
javascript
PepsRyuu/nollup
lib/impl/PluginUtils.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginUtils.js
MIT
function generateSourceMap (mapChain, mapGenerator, original_code, filepath) { let map; if (mapChain.length > 1) { // @ts-ignore map = mapGenerator.toJSON(); } else { map = mapChain.length > 0? mapChain[0].map : undefined; } if (map) { map.file = filepath; map.sources = [filepath]; map.sourcesContent = [original_code]; } // @ts-ignore return map; }
@param {NollupTransformMapEntry[]} mapChain @param {SourceMapGenerator} mapGenerator @param {string} original_code @param {string} filepath @return {RollupSourceMap}
generateSourceMap
javascript
PepsRyuu/nollup
lib/impl/PluginUtils.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginUtils.js
MIT
function combineSourceMapChain (inputMapChain, original_code, filepath) { let mapGenerator, mapChain = prepareSourceMapChain(inputMapChain, original_code, filepath); if (mapChain.length > 1) { // @ts-ignore mapGenerator = SourceMap.SourceMapGenerator.fromSourceMap(new SourceMap.SourceMapConsumer(mapChain[0].map)); for (let i = 1; i < mapChain.length; i++) { // @ts-ignore mapGenerator.applySourceMap(new SourceMap.SourceMapConsumer(mapChain[i].map), undefined, undefined); } } return generateSourceMap(mapChain, mapGenerator, original_code, filepath); }
@param {NollupTransformMapEntry[]} inputMapChain @param {string} original_code @param {string} filepath @return {RollupSourceMap}
combineSourceMapChain
javascript
PepsRyuu/nollup
lib/impl/PluginUtils.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginUtils.js
MIT
async function combineSourceMapChainFast (inputMapChain, original_code, filepath) { let mapGenerator, mapChain = prepareSourceMapChain(inputMapChain, original_code, filepath); if (mapChain.length > 1) { mapGenerator = SourceMapFast.SourceMapGenerator.fromSourceMap(await new SourceMapFast.SourceMapConsumer(mapChain[0].map)); for (let i = 1; i < mapChain.length; i++) { mapGenerator.applySourceMap(await new SourceMapFast.SourceMapConsumer(mapChain[i].map)) } } return generateSourceMap(mapChain, mapGenerator, original_code, filepath); }
@param {NollupTransformMapEntry[]} inputMapChain @param {string} original_code @param {string} filepath @return {Promise<RollupSourceMap>}
combineSourceMapChainFast
javascript
PepsRyuu/nollup
lib/impl/PluginUtils.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginUtils.js
MIT
function getModuleInfo (container, id) { let response = container.__onGetModuleInfo(id); return { id: id, code: response.code || null, isEntry: response.isEntry || false, isExternal: response.isExternal || false, importers: response.importers || [], importedIds: response.importedIds || [], importedIdResolutions: response.importedIdResolutions || [], meta: container.__meta[id] || {}, dynamicImporters: response.dynamicImporters || [], dynamicallyImportedIds: response.dynamicallyImportedIds || [], dynamicallyImportedIdResolutions: response.dynamicallyImportedIdResolutions || [], ast: response.ast || null, hasModuleSideEffects: response.hasModuleSideEffects || false, syntheticNamedExports: response.syntheticNamedExports || false, implicitlyLoadedAfterOneOf: response.implicitlyLoadedAfterOneOf || [], implicitlyLoadedBefore: response.implicitlyLoadedBefore || [], hasDefaultExport: response.hasDefaultExport, isIncluded: response.isIncluded || false, moduleSideEffects: response.moduleSideEffects || true } }
@param {PluginContainer} container @param {string} id @return {RollupModuleInfo}
getModuleInfo
javascript
PepsRyuu/nollup
lib/impl/PluginUtils.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/PluginUtils.js
MIT
function callOutputOptionsHook (plugins, outputOptions) { if (plugins) { plugins.forEach(plugin => { if (plugin.outputOptions) { outputOptions = plugin.outputOptions.call({ meta: PluginMeta }, outputOptions) || outputOptions; } }); } return outputOptions; }
@param {RollupPlugin[]} plugins @param {RollupOutputOptions} outputOptions
callOutputOptionsHook
javascript
PepsRyuu/nollup
lib/impl/RollupConfigContainer.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/RollupConfigContainer.js
MIT
function normalizeInput (input) { if (typeof input === 'string') { return [input]; } if (Array.isArray(input)) { return input; } return input; }
@param {RollupInputOption} input @return {string[]|Object<string, string>}
normalizeInput
javascript
PepsRyuu/nollup
lib/impl/RollupConfigContainer.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/RollupConfigContainer.js
MIT
function findChildNodes (node) { let children = []; for (let prop in node) { if (Array.isArray(node[prop]) && node[prop][0] && node[prop][0].constructor && node[prop][0].constructor.name === 'Node') { children.push(...node[prop]); } if (node[prop] && node[prop].constructor && node[prop].constructor.name === 'Node') { children.push(node[prop]); } } return children; }
@param {ESTree} node @return {Array<ESTree>}
findChildNodes
javascript
PepsRyuu/nollup
lib/impl/utils.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/utils.js
MIT
function resolvePath (target, current) { if (path.isAbsolute(target)) { return path.normalize(target); } else { // Plugins like CommonJS have namespaced imports. let parts = target.split(':'); let namespace = parts.length === 2? parts[0] + ':' : ''; let file = parts.length === 2? parts[1] : parts[0]; let ext = path.extname(file); return namespace + path.normalize(path.resolve(path.dirname(current), ext? file : file + '.js')); } }
@param {string} target @param {string} current @return {string}
resolvePath
javascript
PepsRyuu/nollup
lib/impl/utils.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/utils.js
MIT
function formatFileName (format, fileName, pattern) { let name = path.basename(fileName).replace(path.extname(fileName), ''); if (typeof pattern === 'string') { return pattern.replace('[name]', name) .replace('[extname]', path.extname(fileName)) .replace('[ext]', path.extname(fileName).substring(1)) .replace('[format]', format === 'es'? 'esm' : format); } // TODO: Function pattern implementation return ''; }
@param {string} format @param {string} fileName @param {string|function(RollupPreRenderedFile): string} pattern @return {string}
formatFileName
javascript
PepsRyuu/nollup
lib/impl/utils.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/utils.js
MIT
async function logs (count = 1, timeout = 5000) { let start = Date.now(); // Wait until we acquire the requested number of logs while (logbuffer.length < count) { await wait(100); if (Date.now() - start > timeout) { break; } } // return the logs and clear it afterwards return logbuffer.splice(0, logbuffer.length); }
Returns a list of logs. Waits until the number of requested logs have accumulated. There's a timeout to force it to stop checking. @param {Number} count @param {Number} timeout @returns {Promise<String[]>}
logs
javascript
PepsRyuu/nollup
test/utils/evaluator.js
https://github.com/PepsRyuu/nollup/blob/master/test/utils/evaluator.js
MIT
async function call (fn, arg) { // TODO: Find deterministic way of handling this await wait(100); global._evaluatorInstance.send({ call: [fn, arg] }); await wait(100); }
Call the global function in the VM. @param {String} fn @param {*} arg
call
javascript
PepsRyuu/nollup
test/utils/evaluator.js
https://github.com/PepsRyuu/nollup/blob/master/test/utils/evaluator.js
MIT
function invalidate (chunks) { global._evaluatorInstance.send({ invalidate: true, chunks }); }
Sends updated bundle chunks to VM. @param {Object[]} chunks
invalidate
javascript
PepsRyuu/nollup
test/utils/evaluator.js
https://github.com/PepsRyuu/nollup/blob/master/test/utils/evaluator.js
MIT
function init (format, entry, chunks, globals = {}, async = false) { logbuffer = []; return new Promise((resolve, reject) => { let impl = (resolve, reject) => { global._evaluatorResultListener = msg => { if (msg.log) { logbuffer.push(msg.log); return; } if (msg.error) { return reject(msg.error); } resolve({ globals: msg.globals, exports: msg.result }); }; global._evaluatorInstance.send({ format, entry, chunks, globals, async }); }; // The forked node may not be ready yet when the test starts. // This will push the test into a backlog. if (!global._evaluatorReady) { global._evaluatorReadyListeners.push(() => impl(resolve, reject)); } else { impl(resolve, reject); } }); }
Evaluates the VM with the provided code. @param {String} format @param {String} entry @param {Object[]} chunks @param {Object} globals @param {Boolean} async @returns {Object}
init
javascript
PepsRyuu/nollup
test/utils/evaluator.js
https://github.com/PepsRyuu/nollup/blob/master/test/utils/evaluator.js
MIT
impl = (resolve, reject) => { global._evaluatorResultListener = msg => { if (msg.log) { logbuffer.push(msg.log); return; } if (msg.error) { return reject(msg.error); } resolve({ globals: msg.globals, exports: msg.result }); }; global._evaluatorInstance.send({ format, entry, chunks, globals, async }); }
Evaluates the VM with the provided code. @param {String} format @param {String} entry @param {Object[]} chunks @param {Object} globals @param {Boolean} async @returns {Object}
impl
javascript
PepsRyuu/nollup
test/utils/evaluator.js
https://github.com/PepsRyuu/nollup/blob/master/test/utils/evaluator.js
MIT
impl = (resolve, reject) => { global._evaluatorResultListener = msg => { if (msg.log) { logbuffer.push(msg.log); return; } if (msg.error) { return reject(msg.error); } resolve({ globals: msg.globals, exports: msg.result }); }; global._evaluatorInstance.send({ format, entry, chunks, globals, async }); }
Evaluates the VM with the provided code. @param {String} format @param {String} entry @param {Object[]} chunks @param {Object} globals @param {Boolean} async @returns {Object}
impl
javascript
PepsRyuu/nollup
test/utils/evaluator.js
https://github.com/PepsRyuu/nollup/blob/master/test/utils/evaluator.js
MIT
constructor(capacity) { this.capacity = capacity; this.regExpMap = new Map(); // Since our capacity tends to be fairly small, `.shift()` will be fairly quick despite being O(n). We just use a // normal array to keep it simple. this.regExpQueue = []; }
This is a reusable regular expression cache class. Given a certain maximum number of regular expressions we're allowed to store in the cache, it provides a way to avoid recreating regular expression objects over and over. When it needs to evict something, it evicts the oldest one.
constructor
javascript
i18next/i18next
src/utils.js
https://github.com/i18next/i18next/blob/master/src/utils.js
MIT
getRegExp(pattern) { const regExpFromCache = this.regExpMap.get(pattern); if (regExpFromCache !== undefined) { return regExpFromCache; } const regExpNew = new RegExp(pattern); if (this.regExpQueue.length === this.capacity) { this.regExpMap.delete(this.regExpQueue.shift()); } this.regExpMap.set(pattern, regExpNew); this.regExpQueue.push(pattern); return regExpNew; }
This is a reusable regular expression cache class. Given a certain maximum number of regular expressions we're allowed to store in the cache, it provides a way to avoid recreating regular expression objects over and over. When it needs to evict something, it evicts the oldest one.
getRegExp
javascript
i18next/i18next
src/utils.js
https://github.com/i18next/i18next/blob/master/src/utils.js
MIT
looksLikeObjectPath = (key, nsSeparator, keySeparator) => { nsSeparator = nsSeparator || ''; keySeparator = keySeparator || ''; const possibleChars = chars.filter( (c) => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0, ); if (possibleChars.length === 0) return true; const r = looksLikeObjectPathRegExpCache.getRegExp( `(${possibleChars.map((c) => (c === '?' ? '\\?' : c)).join('|')})`, ); let matched = !r.test(key); if (!matched) { const ki = key.indexOf(keySeparator); if (ki > 0 && !r.test(key.substring(0, ki))) { matched = true; } } return matched; }
This is a reusable regular expression cache class. Given a certain maximum number of regular expressions we're allowed to store in the cache, it provides a way to avoid recreating regular expression objects over and over. When it needs to evict something, it evicts the oldest one.
looksLikeObjectPath
javascript
i18next/i18next
src/utils.js
https://github.com/i18next/i18next/blob/master/src/utils.js
MIT
looksLikeObjectPath = (key, nsSeparator, keySeparator) => { nsSeparator = nsSeparator || ''; keySeparator = keySeparator || ''; const possibleChars = chars.filter( (c) => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0, ); if (possibleChars.length === 0) return true; const r = looksLikeObjectPathRegExpCache.getRegExp( `(${possibleChars.map((c) => (c === '?' ? '\\?' : c)).join('|')})`, ); let matched = !r.test(key); if (!matched) { const ki = key.indexOf(keySeparator); if (ki > 0 && !r.test(key.substring(0, ki))) { matched = true; } } return matched; }
This is a reusable regular expression cache class. Given a certain maximum number of regular expressions we're allowed to store in the cache, it provides a way to avoid recreating regular expression objects over and over. When it needs to evict something, it evicts the oldest one.
looksLikeObjectPath
javascript
i18next/i18next
src/utils.js
https://github.com/i18next/i18next/blob/master/src/utils.js
MIT
deepFind = (obj, path, keySeparator = '.') => { if (!obj) return undefined; if (obj[path]) { if (!Object.prototype.hasOwnProperty.call(obj, path)) return undefined; return obj[path]; } const tokens = path.split(keySeparator); let current = obj; for (let i = 0; i < tokens.length; ) { if (!current || typeof current !== 'object') { return undefined; } let next; let nextPath = ''; for (let j = i; j < tokens.length; ++j) { if (j !== i) { nextPath += keySeparator; } nextPath += tokens[j]; next = current[nextPath]; if (next !== undefined) { if (['string', 'number', 'boolean'].indexOf(typeof next) > -1 && j < tokens.length - 1) { continue; } i += j - i + 1; break; } } current = next; } return current; }
Given 1. a top level object obj, and 2. a path to a deeply nested string or object within it Find and return that deeply nested string or object. The caveat is that the keys of objects within the nesting chain may contain period characters. Therefore, we need to DFS and explore all possible keys at each step until we find the deeply nested string or object.
deepFind
javascript
i18next/i18next
src/utils.js
https://github.com/i18next/i18next/blob/master/src/utils.js
MIT
deepFind = (obj, path, keySeparator = '.') => { if (!obj) return undefined; if (obj[path]) { if (!Object.prototype.hasOwnProperty.call(obj, path)) return undefined; return obj[path]; } const tokens = path.split(keySeparator); let current = obj; for (let i = 0; i < tokens.length; ) { if (!current || typeof current !== 'object') { return undefined; } let next; let nextPath = ''; for (let j = i; j < tokens.length; ++j) { if (j !== i) { nextPath += keySeparator; } nextPath += tokens[j]; next = current[nextPath]; if (next !== undefined) { if (['string', 'number', 'boolean'].indexOf(typeof next) > -1 && j < tokens.length - 1) { continue; } i += j - i + 1; break; } } current = next; } return current; }
Given 1. a top level object obj, and 2. a path to a deeply nested string or object within it Find and return that deeply nested string or object. The caveat is that the keys of objects within the nesting chain may contain period characters. Therefore, we need to DFS and explore all possible keys at each step until we find the deeply nested string or object.
deepFind
javascript
i18next/i18next
src/utils.js
https://github.com/i18next/i18next/blob/master/src/utils.js
MIT
httpApiReadMockImplementation = (language, namespace, callback) => { const namespacePath = `${__dirname}/locales/${language}/${namespace}.json`; // console.info('httpApiReadMockImplementation', namespacePath); if (fs.existsSync(namespacePath)) { const data = JSON.parse(fs.readFileSync(namespacePath, 'utf-8')); callback(null, data); } else { callback('File is not available in `locales` folder', null); } }
@param {string} language @param {string} namespace @param {import('i18next').ReadCallback} callback @returns {void}
httpApiReadMockImplementation
javascript
i18next/i18next
test/compatibility/v1/v1.i18nInstance.js
https://github.com/i18next/i18next/blob/master/test/compatibility/v1/v1.i18nInstance.js
MIT
httpApiReadMockImplementation = (language, namespace, callback) => { const namespacePath = `${__dirname}/locales/${language}/${namespace}.json`; // console.info('httpApiReadMockImplementation', namespacePath); if (fs.existsSync(namespacePath)) { const data = JSON.parse(fs.readFileSync(namespacePath, 'utf-8')); callback(null, data); } else { callback('File is not available in `locales` folder', null); } }
@param {string} language @param {string} namespace @param {import('i18next').ReadCallback} callback @returns {void}
httpApiReadMockImplementation
javascript
i18next/i18next
test/compatibility/v1/v1.i18nInstance.js
https://github.com/i18next/i18next/blob/master/test/compatibility/v1/v1.i18nInstance.js
MIT
getI18nCompatibilityV1InitOptions = () => ({ compatibilityAPI: 'v1', compatibilityJSON: 'v1', lng: 'en-US', load: 'all', fallbackLng: 'dev', fallbackNS: [], fallbackOnNull: true, fallbackOnEmpty: false, preload: [], lowerCaseLng: false, ns: 'translation', fallbackToDefaultNS: false, resGetPath: 'http://localhost:9877/locales/__lng__/__ns__.json', dynamicLoad: false, useLocalStorage: false, sendMissing: false, resStore: false, getAsync: true, returnObjectTrees: false, debug: false, selectorAttr: 'data-i18n', postProcess: '', parseMissingKey: '', interpolationPrefix: '__', interpolationSuffix: '__', defaultVariables: false, shortcutFunction: 'sprintf', objectTreeKeyHandler: null, lngWhitelist: null, resources: null, })
using a function to have always a new object
getI18nCompatibilityV1InitOptions
javascript
i18next/i18next
test/compatibility/v1/v1.i18nInstance.js
https://github.com/i18next/i18next/blob/master/test/compatibility/v1/v1.i18nInstance.js
MIT
getI18nCompatibilityV1InitOptions = () => ({ compatibilityAPI: 'v1', compatibilityJSON: 'v1', lng: 'en-US', load: 'all', fallbackLng: 'dev', fallbackNS: [], fallbackOnNull: true, fallbackOnEmpty: false, preload: [], lowerCaseLng: false, ns: 'translation', fallbackToDefaultNS: false, resGetPath: 'http://localhost:9877/locales/__lng__/__ns__.json', dynamicLoad: false, useLocalStorage: false, sendMissing: false, resStore: false, getAsync: true, returnObjectTrees: false, debug: false, selectorAttr: 'data-i18n', postProcess: '', parseMissingKey: '', interpolationPrefix: '__', interpolationSuffix: '__', defaultVariables: false, shortcutFunction: 'sprintf', objectTreeKeyHandler: null, lngWhitelist: null, resources: null, })
using a function to have always a new object
getI18nCompatibilityV1InitOptions
javascript
i18next/i18next
test/compatibility/v1/v1.i18nInstance.js
https://github.com/i18next/i18next/blob/master/test/compatibility/v1/v1.i18nInstance.js
MIT
function distance(p1, p2) { return Math.hypot(p1.x - p2.x, p1.y - p2.y); }
Calculates distance between two points. Each point must have `x` and `y` property @param {*} p1 point 1 @param {*} p2 point 2 @returns distance between two points
distance
javascript
puffinsoft/jscanify
src/jscanify-node.js
https://github.com/puffinsoft/jscanify/blob/master/src/jscanify-node.js
MIT
loadOpenCV(callback) { cv = require("./opencv"); cv["onRuntimeInitialized"] = () => { callback(cv); }; }
Calculates distance between two points. Each point must have `x` and `y` property @param {*} p1 point 1 @param {*} p2 point 2 @returns distance between two points
loadOpenCV
javascript
puffinsoft/jscanify
src/jscanify-node.js
https://github.com/puffinsoft/jscanify/blob/master/src/jscanify-node.js
MIT
findPaperContour(img) { const imgGray = new cv.Mat(); cv.Canny(img, imgGray, 50, 200); const imgBlur = new cv.Mat(); cv.GaussianBlur( imgGray, imgBlur, new cv.Size(3, 3), 0, 0, cv.BORDER_DEFAULT ); const imgThresh = new cv.Mat(); cv.threshold(imgBlur, imgThresh, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU); let contours = new cv.MatVector(); let hierarchy = new cv.Mat(); cv.findContours( imgThresh, contours, hierarchy, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE ); let maxArea = 0; let maxContourIndex = -1; for (let i = 0; i < contours.size(); ++i) { let contourArea = cv.contourArea(contours.get(i)); if (contourArea > maxArea) { maxArea = contourArea; maxContourIndex = i; } } const maxContour = maxContourIndex >= 0 ? contours.get(maxContourIndex) : null; imgGray.delete(); imgBlur.delete(); imgThresh.delete(); contours.delete(); hierarchy.delete(); return maxContour; }
Finds the contour of the paper within the image @param {*} img image to process (cv.Mat) @returns the biggest contour inside the image
findPaperContour
javascript
puffinsoft/jscanify
src/jscanify-node.js
https://github.com/puffinsoft/jscanify/blob/master/src/jscanify-node.js
MIT
highlightPaper(image, options) { options = options || {}; options.color = options.color || "orange"; options.thickness = options.thickness || 10; const canvas = createCanvas(); const ctx = canvas.getContext("2d"); const img = cv.imread(image); const maxContour = this.findPaperContour(img); cv.imshow(canvas, img); if (maxContour) { const { topLeftCorner, topRightCorner, bottomLeftCorner, bottomRightCorner, } = this.getCornerPoints(maxContour, img); if ( topLeftCorner && topRightCorner && bottomLeftCorner && bottomRightCorner ) { ctx.strokeStyle = options.color; ctx.lineWidth = options.thickness; ctx.beginPath(); ctx.moveTo(...Object.values(topLeftCorner)); ctx.lineTo(...Object.values(topRightCorner)); ctx.lineTo(...Object.values(bottomRightCorner)); ctx.lineTo(...Object.values(bottomLeftCorner)); ctx.lineTo(...Object.values(topLeftCorner)); ctx.stroke(); } } img.delete(); return canvas; }
Highlights the paper detected inside the image. @param {*} image image to process @param {*} options options for highlighting. Accepts `color` and `thickness` parameter @returns `HTMLCanvasElement` with original image and paper highlighted
highlightPaper
javascript
puffinsoft/jscanify
src/jscanify-node.js
https://github.com/puffinsoft/jscanify/blob/master/src/jscanify-node.js
MIT
extractPaper(image, resultWidth, resultHeight, cornerPoints) { const canvas = createCanvas(); const img = cv.imread(image); const maxContour = cornerPoints ? null : this.findPaperContour(img); if(maxContour == null && cornerPoints === undefined){ return null; } const { topLeftCorner, topRightCorner, bottomLeftCorner, bottomRightCorner, } = cornerPoints || this.getCornerPoints(maxContour, img); let warpedDst = new cv.Mat(); let dsize = new cv.Size(resultWidth, resultHeight); let srcTri = cv.matFromArray(4, 1, cv.CV_32FC2, [ topLeftCorner.x, topLeftCorner.y, topRightCorner.x, topRightCorner.y, bottomLeftCorner.x, bottomLeftCorner.y, bottomRightCorner.x, bottomRightCorner.y, ]); let dstTri = cv.matFromArray(4, 1, cv.CV_32FC2, [ 0, 0, resultWidth, 0, 0, resultHeight, resultWidth, resultHeight, ]); let M = cv.getPerspectiveTransform(srcTri, dstTri); cv.warpPerspective( img, warpedDst, M, dsize, cv.INTER_LINEAR, cv.BORDER_CONSTANT, new cv.Scalar() ); cv.imshow(canvas, warpedDst); img.delete(); warpedDst.delete(); return canvas; }
Extracts and undistorts the image detected within the frame. Returns `null` if no paper is detected. @param {*} image image to process @param {*} resultWidth desired result paper width @param {*} resultHeight desired result paper height @param {*} cornerPoints optional custom corner points, in case automatic corner points are incorrect @returns `HTMLCanvasElement` containing undistorted image
extractPaper
javascript
puffinsoft/jscanify
src/jscanify-node.js
https://github.com/puffinsoft/jscanify/blob/master/src/jscanify-node.js
MIT
getCornerPoints(contour) { let rect = cv.minAreaRect(contour); const center = rect.center; let topLeftCorner; let topLeftCornerDist = 0; let topRightCorner; let topRightCornerDist = 0; let bottomLeftCorner; let bottomLeftCornerDist = 0; let bottomRightCorner; let bottomRightCornerDist = 0; for (let i = 0; i < contour.data32S.length; i += 2) { const point = { x: contour.data32S[i], y: contour.data32S[i + 1] }; const dist = distance(point, center); if (point.x < center.x && point.y < center.y) { // top left if (dist > topLeftCornerDist) { topLeftCorner = point; topLeftCornerDist = dist; } } else if (point.x > center.x && point.y < center.y) { // top right if (dist > topRightCornerDist) { topRightCorner = point; topRightCornerDist = dist; } } else if (point.x < center.x && point.y > center.y) { // bottom left if (dist > bottomLeftCornerDist) { bottomLeftCorner = point; bottomLeftCornerDist = dist; } } else if (point.x > center.x && point.y > center.y) { // bottom right if (dist > bottomRightCornerDist) { bottomRightCorner = point; bottomRightCornerDist = dist; } } } return { topLeftCorner, topRightCorner, bottomLeftCorner, bottomRightCorner, }; }
Calculates the corner points of a contour. @param {*} contour contour from {@link findPaperContour} @returns object with properties `topLeftCorner`, `topRightCorner`, `bottomLeftCorner`, `bottomRightCorner`, each with `x` and `y` property
getCornerPoints
javascript
puffinsoft/jscanify
src/jscanify-node.js
https://github.com/puffinsoft/jscanify/blob/master/src/jscanify-node.js
MIT
function distance(p1, p2) { return Math.hypot(p1.x - p2.x, p1.y - p2.y); }
Calculates distance between two points. Each point must have `x` and `y` property @param {*} p1 point 1 @param {*} p2 point 2 @returns distance between two points
distance
javascript
puffinsoft/jscanify
src/jscanify.js
https://github.com/puffinsoft/jscanify/blob/master/src/jscanify.js
MIT
findPaperContour(img) { const imgGray = new cv.Mat(); cv.Canny(img, imgGray, 50, 200); const imgBlur = new cv.Mat(); cv.GaussianBlur( imgGray, imgBlur, new cv.Size(3, 3), 0, 0, cv.BORDER_DEFAULT ); const imgThresh = new cv.Mat(); cv.threshold( imgBlur, imgThresh, 0, 255, cv.THRESH_OTSU ); let contours = new cv.MatVector(); let hierarchy = new cv.Mat(); cv.findContours( imgThresh, contours, hierarchy, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE ); let maxArea = 0; let maxContourIndex = -1; for (let i = 0; i < contours.size(); ++i) { let contourArea = cv.contourArea(contours.get(i)); if (contourArea > maxArea) { maxArea = contourArea; maxContourIndex = i; } } const maxContour = maxContourIndex >= 0 ? contours.get(maxContourIndex) : null; imgGray.delete(); imgBlur.delete(); imgThresh.delete(); contours.delete(); hierarchy.delete(); return maxContour; }
Finds the contour of the paper within the image @param {*} img image to process (cv.Mat) @returns the biggest contour inside the image
findPaperContour
javascript
puffinsoft/jscanify
src/jscanify.js
https://github.com/puffinsoft/jscanify/blob/master/src/jscanify.js
MIT
highlightPaper(image, options) { options = options || {}; options.color = options.color || "orange"; options.thickness = options.thickness || 10; const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); const img = cv.imread(image); const maxContour = this.findPaperContour(img); cv.imshow(canvas, img); if (maxContour) { const { topLeftCorner, topRightCorner, bottomLeftCorner, bottomRightCorner, } = this.getCornerPoints(maxContour, img); if ( topLeftCorner && topRightCorner && bottomLeftCorner && bottomRightCorner ) { ctx.strokeStyle = options.color; ctx.lineWidth = options.thickness; ctx.beginPath(); ctx.moveTo(...Object.values(topLeftCorner)); ctx.lineTo(...Object.values(topRightCorner)); ctx.lineTo(...Object.values(bottomRightCorner)); ctx.lineTo(...Object.values(bottomLeftCorner)); ctx.lineTo(...Object.values(topLeftCorner)); ctx.stroke(); } } img.delete(); return canvas; }
Highlights the paper detected inside the image. @param {*} image image to process @param {*} options options for highlighting. Accepts `color` and `thickness` parameter @returns `HTMLCanvasElement` with original image and paper highlighted
highlightPaper
javascript
puffinsoft/jscanify
src/jscanify.js
https://github.com/puffinsoft/jscanify/blob/master/src/jscanify.js
MIT
extractPaper(image, resultWidth, resultHeight, cornerPoints) { const canvas = document.createElement("canvas"); const img = cv.imread(image); const maxContour = cornerPoints ? null : this.findPaperContour(img); if(maxContour == null && cornerPoints === undefined){ return null; } const { topLeftCorner, topRightCorner, bottomLeftCorner, bottomRightCorner, } = cornerPoints || this.getCornerPoints(maxContour, img); let warpedDst = new cv.Mat(); let dsize = new cv.Size(resultWidth, resultHeight); let srcTri = cv.matFromArray(4, 1, cv.CV_32FC2, [ topLeftCorner.x, topLeftCorner.y, topRightCorner.x, topRightCorner.y, bottomLeftCorner.x, bottomLeftCorner.y, bottomRightCorner.x, bottomRightCorner.y, ]); let dstTri = cv.matFromArray(4, 1, cv.CV_32FC2, [ 0, 0, resultWidth, 0, 0, resultHeight, resultWidth, resultHeight, ]); let M = cv.getPerspectiveTransform(srcTri, dstTri); cv.warpPerspective( img, warpedDst, M, dsize, cv.INTER_LINEAR, cv.BORDER_CONSTANT, new cv.Scalar() ); cv.imshow(canvas, warpedDst); img.delete() warpedDst.delete() return canvas; }
Extracts and undistorts the image detected within the frame. Returns `null` if no paper is detected. @param {*} image image to process @param {*} resultWidth desired result paper width @param {*} resultHeight desired result paper height @param {*} cornerPoints optional custom corner points, in case automatic corner points are incorrect @returns `HTMLCanvasElement` containing undistorted image
extractPaper
javascript
puffinsoft/jscanify
src/jscanify.js
https://github.com/puffinsoft/jscanify/blob/master/src/jscanify.js
MIT
getCornerPoints(contour) { let rect = cv.minAreaRect(contour); const center = rect.center; let topLeftCorner; let topLeftCornerDist = 0; let topRightCorner; let topRightCornerDist = 0; let bottomLeftCorner; let bottomLeftCornerDist = 0; let bottomRightCorner; let bottomRightCornerDist = 0; for (let i = 0; i < contour.data32S.length; i += 2) { const point = { x: contour.data32S[i], y: contour.data32S[i + 1] }; const dist = distance(point, center); if (point.x < center.x && point.y < center.y) { // top left if (dist > topLeftCornerDist) { topLeftCorner = point; topLeftCornerDist = dist; } } else if (point.x > center.x && point.y < center.y) { // top right if (dist > topRightCornerDist) { topRightCorner = point; topRightCornerDist = dist; } } else if (point.x < center.x && point.y > center.y) { // bottom left if (dist > bottomLeftCornerDist) { bottomLeftCorner = point; bottomLeftCornerDist = dist; } } else if (point.x > center.x && point.y > center.y) { // bottom right if (dist > bottomRightCornerDist) { bottomRightCorner = point; bottomRightCornerDist = dist; } } } return { topLeftCorner, topRightCorner, bottomLeftCorner, bottomRightCorner, }; }
Calculates the corner points of a contour. @param {*} contour contour from {@link findPaperContour} @returns object with properties `topLeftCorner`, `topRightCorner`, `bottomLeftCorner`, `bottomRightCorner`, each with `x` and `y` property
getCornerPoints
javascript
puffinsoft/jscanify
src/jscanify.js
https://github.com/puffinsoft/jscanify/blob/master/src/jscanify.js
MIT
function processSegmentation(canvas, segmentation) { var ctx = canvas.getContext('2d'); console.log(segmentation) // Get data from our overlay canvas which is attempting to estimate background. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); var data = imageData.data; // Get data from the live webcam view which has all data. var liveData = videoRenderCanvasCtx.getImageData(0, 0, canvas.width, canvas.height); var dataL = liveData.data; var minX = 100000; var minY = 100000; var maxX = 0; var maxY = 0; var foundBody = false; // Go through pixels and figure out bounding box of body pixels. for (let x = 0; x < canvas.width; x++) { for (let y = 0; y < canvas.height; y++) { let n = y * canvas.width + x; // Human pixel found. Update bounds. if (segmentation.data[n] !== 0) { if(x < minX) { minX = x; } if(y < minY) { minY = y; } if(x > maxX) { maxX = x; } if(y > maxY) { maxY = y; } foundBody = true; } } } // Calculate dimensions of bounding box. var width = maxX - minX; var height = maxY - minY; // Define scale factor to use to allow for false negatives around this region. var scale = 1.3; // Define scaled dimensions. var newWidth = width * scale; var newHeight = height * scale; // Caculate the offset to place new bounding box so scaled from center of current bounding box. var offsetX = (newWidth - width) / 2; var offsetY = (newHeight - height) / 2; var newXMin = minX - offsetX; var newYMin = minY - offsetY; // Now loop through update backgound understanding with new data // if not inside a bounding box. for (let x = 0; x < canvas.width; x++) { for (let y = 0; y < canvas.height; y++) { // If outside bounding box and we found a body, update background. if (foundBody && (x < newXMin || x > newXMin + newWidth) || ( y < newYMin || y > newYMin + newHeight)) { // Convert xy co-ords to array offset. let n = y * canvas.width + x; data[n * 4] = dataL[n * 4]; data[n * 4 + 1] = dataL[n * 4 + 1]; data[n * 4 + 2] = dataL[n * 4 + 2]; data[n * 4 + 3] = 255; } else if (!foundBody) { // No body found at all, update all pixels. let n = y * canvas.width + x; data[n * 4] = dataL[n * 4]; data[n * 4 + 1] = dataL[n * 4 + 1]; data[n * 4 + 2] = dataL[n * 4 + 2]; data[n * 4 + 3] = 255; } } } ctx.putImageData(imageData, 0, 0); if (DEBUG) { ctx.strokeStyle = "#00FF00" ctx.beginPath(); ctx.rect(newXMin, newYMin, newWidth, newHeight); ctx.stroke(); } }
***************************************************************** Real-Time-Person-Removal Created by Jason Mayes 2020. Get latest code on my Github: https://github.com/jasonmayes/Real-Time-Person-Removal Got questions? Reach out to me on social: Twitter: @jason_mayes LinkedIn: https://www.linkedin.com/in/creativetech ******************************************************************
processSegmentation
javascript
jasonmayes/Real-Time-Person-Removal
script.js
https://github.com/jasonmayes/Real-Time-Person-Removal/blob/master/script.js
Apache-2.0
function hasGetUserMedia() { return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia); }
***************************************************************** // Continuously grab image from webcam stream and classify it. ******************************************************************
hasGetUserMedia
javascript
jasonmayes/Real-Time-Person-Removal
script.js
https://github.com/jasonmayes/Real-Time-Person-Removal/blob/master/script.js
Apache-2.0
function predictWebcam() { if (previousSegmentationComplete) { // Copy the video frame from webcam to a tempory canvas in memory only (not in the DOM). videoRenderCanvasCtx.drawImage(video, 0, 0); previousSegmentationComplete = false; // Now classify the canvas image we have available. model.segmentPerson(videoRenderCanvas, segmentationProperties).then(function(segmentation) { processSegmentation(webcamCanvas, segmentation); previousSegmentationComplete = true; }); } // Call this function again to keep predicting when the browser is ready. window.requestAnimationFrame(predictWebcam); }
***************************************************************** // Continuously grab image from webcam stream and classify it. ******************************************************************
predictWebcam
javascript
jasonmayes/Real-Time-Person-Removal
script.js
https://github.com/jasonmayes/Real-Time-Person-Removal/blob/master/script.js
Apache-2.0
function enableCam(event) { if (!modelHasLoaded) { return; } // Hide the button. event.target.classList.add('removed'); // getUsermedia parameters. const constraints = { video: true }; // Activate the webcam stream. navigator.mediaDevices.getUserMedia(constraints).then(function(stream) { video.addEventListener('loadedmetadata', function() { // Update widths and heights once video is successfully played otherwise // it will have width and height of zero initially causing classification // to fail. webcamCanvas.width = video.videoWidth; webcamCanvas.height = video.videoHeight; videoRenderCanvas.width = video.videoWidth; videoRenderCanvas.height = video.videoHeight; bodyPixCanvas.width = video.videoWidth; bodyPixCanvas.height = video.videoHeight; let webcamCanvasCtx = webcamCanvas.getContext('2d'); webcamCanvasCtx.drawImage(video, 0, 0); }); video.srcObject = stream; video.addEventListener('loadeddata', predictWebcam); }); }
***************************************************************** // Continuously grab image from webcam stream and classify it. ******************************************************************
enableCam
javascript
jasonmayes/Real-Time-Person-Removal
script.js
https://github.com/jasonmayes/Real-Time-Person-Removal/blob/master/script.js
Apache-2.0
function processSegmentation(canvas, segmentation) { var ctx = canvas.getContext('2d'); // Get data from our overlay canvas which is attempting to estimate background. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); var data = imageData.data; // Get data from the live webcam view which has all data. var liveData = videoRenderCanvasCtx.getImageData(0, 0, canvas.width, canvas.height); var dataL = liveData.data; // Now loop through and see if pixels contain human parts. If not, update // backgound understanding with new data. for (let x = RESOLUTION_MIN; x < canvas.width; x += RESOLUTION_MIN) { for (let y = RESOLUTION_MIN; y < canvas.height; y += RESOLUTION_MIN) { // Convert xy co-ords to array offset. let n = y * canvas.width + x; let foundBodyPartNearby = false; // Let's check around a given pixel if any other pixels were body like. let yMin = y - SEARCH_OFFSET; yMin = yMin < 0 ? 0: yMin; let yMax = y + SEARCH_OFFSET; yMax = yMax > canvas.height ? canvas.height : yMax; let xMin = x - SEARCH_OFFSET; xMin = xMin < 0 ? 0: xMin; let xMax = x + SEARCH_OFFSET; xMax = xMax > canvas.width ? canvas.width : xMax; for (let i = xMin; i < xMax; i++) { for (let j = yMin; j < yMax; j++) { let offset = j * canvas.width + i; // If any of the pixels in the square we are analysing has a body // part, mark as contaminated. if (segmentation.data[offset] !== 0) { foundBodyPartNearby = true; break; } } } // Update patch if patch was clean. if (!foundBodyPartNearby) { for (let i = xMin; i < xMax; i++) { for (let j = yMin; j < yMax; j++) { // Convert xy co-ords to array offset. let offset = j * canvas.width + i; data[offset * 4] = dataL[offset * 4]; data[offset * 4 + 1] = dataL[offset * 4 + 1]; data[offset * 4 + 2] = dataL[offset * 4 + 2]; data[offset * 4 + 3] = 255; } } } else { if (DEBUG) { for (let i = xMin; i < xMax; i++) { for (let j = yMin; j < yMax; j++) { // Convert xy co-ords to array offset. let offset = j * canvas.width + i; data[offset * 4] = 255; data[offset * 4 + 1] = 0; data[offset * 4 + 2] = 0; data[offset * 4 + 3] = 255; } } } } } } ctx.putImageData(imageData, 0, 0); }
***************************************************************** Real-Time-Person-Removal Created by Jason Mayes 2020. Get latest code on my Github: https://github.com/jasonmayes/Real-Time-Person-Removal Got questions? Reach out to me on social: Twitter: @jason_mayes LinkedIn: https://www.linkedin.com/in/creativetech ******************************************************************
processSegmentation
javascript
jasonmayes/Real-Time-Person-Removal
script_original.js
https://github.com/jasonmayes/Real-Time-Person-Removal/blob/master/script_original.js
Apache-2.0
function hasGetUserMedia() { return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia); }
***************************************************************** // Continuously grab image from webcam stream and classify it. ******************************************************************
hasGetUserMedia
javascript
jasonmayes/Real-Time-Person-Removal
script_original.js
https://github.com/jasonmayes/Real-Time-Person-Removal/blob/master/script_original.js
Apache-2.0
function predictWebcam() { if (previousSegmentationComplete) { // Copy the video frame from webcam to a tempory canvas in memory only (not in the DOM). videoRenderCanvasCtx.drawImage(video, 0, 0); previousSegmentationComplete = false; // Now classify the canvas image we have available. model.segmentPerson(videoRenderCanvas, segmentationProperties).then(function(segmentation) { processSegmentation(webcamCanvas, segmentation); previousSegmentationComplete = true; }); } // Call this function again to keep predicting when the browser is ready. window.requestAnimationFrame(predictWebcam); }
***************************************************************** // Continuously grab image from webcam stream and classify it. ******************************************************************
predictWebcam
javascript
jasonmayes/Real-Time-Person-Removal
script_original.js
https://github.com/jasonmayes/Real-Time-Person-Removal/blob/master/script_original.js
Apache-2.0
function enableCam(event) { if (!modelHasLoaded) { return; } // Hide the button. event.target.classList.add('removed'); // getUsermedia parameters. const constraints = { video: true }; // Activate the webcam stream. navigator.mediaDevices.getUserMedia(constraints).then(function(stream) { video.addEventListener('loadedmetadata', function() { // Update widths and heights once video is successfully played otherwise // it will have width and height of zero initially causing classification // to fail. webcamCanvas.width = video.videoWidth; webcamCanvas.height = video.videoHeight; videoRenderCanvas.width = video.videoWidth; videoRenderCanvas.height = video.videoHeight; let webcamCanvasCtx = webcamCanvas.getContext('2d'); webcamCanvasCtx.drawImage(video, 0, 0); }); video.srcObject = stream; video.addEventListener('loadeddata', predictWebcam); }); }
***************************************************************** // Continuously grab image from webcam stream and classify it. ******************************************************************
enableCam
javascript
jasonmayes/Real-Time-Person-Removal
script_original.js
https://github.com/jasonmayes/Real-Time-Person-Removal/blob/master/script_original.js
Apache-2.0
function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; }
Based on JSON2 (http://www.JSON.org/js.html).
f
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function date(d, key) { return isFinite(d.valueOf()) ? d.getUTCFullYear() + '-' + f(d.getUTCMonth() + 1) + '-' + f(d.getUTCDate()) + 'T' + f(d.getUTCHours()) + ':' + f(d.getUTCMinutes()) + ':' + f(d.getUTCSeconds()) + 'Z' : null; }
Based on JSON2 (http://www.JSON.org/js.html).
date
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT