code
stringlengths
28
313k
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
74
language
stringclasses
1 value
repo
stringlengths
5
60
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function runModuleExecutionHooks(module, executeModule) { if (typeof globalThis.$RefreshInterceptModuleExecution$ === 'function') { const cleanupReactRefreshIntercept = globalThis.$RefreshInterceptModuleExecution$(module.id); try { executeModule({ register: globalThis.$RefreshReg$, signature: globalThis.$RefreshSig$, registerExports: registerExportsAndSetupBoundaryForReactRefresh }); } finally{ // Always cleanup the intercept, even if module execution failed. cleanupReactRefreshIntercept(); } } else { // If the react refresh hooks are not installed we need to bind dummy functions. // This is expected when running in a Web Worker. It is also common in some of // our test environments. executeModule({ register: (type, id)=>{}, signature: ()=>(type)=>{}, registerExports: (module, helpers)=>{} }); } }
NOTE(alexkirsz) Webpack has a "module execution" interception hook that Next.js' React Refresh runtime hooks into to add module context to the refresh registry.
runModuleExecutionHooks
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function registerExportsAndSetupBoundaryForReactRefresh(module, helpers) { const currentExports = module.exports; const prevExports = module.hot.data.prevExports ?? null; helpers.registerExportsForReactRefresh(currentExports, module.id); // A module can be accepted automatically based on its exports, e.g. when // it is a Refresh Boundary. if (helpers.isReactRefreshBoundary(currentExports)) { // Save the previous exports on update, so we can compare the boundary // signatures. module.hot.dispose((data)=>{ data.prevExports = currentExports; }); // Unconditionally accept an update to this module, we'll check if it's // still a Refresh Boundary later. module.hot.accept(); // This field is set when the previous version of this module was a // Refresh Boundary, letting us know we need to check for invalidation or // enqueue an update. if (prevExports !== null) { // A boundary can become ineligible if its exports are incompatible // with the previous exports. // // For example, if you add/remove/change exports, we'll want to // re-execute the importing modules, and force those components to // re-render. Similarly, if you convert a class component to a // function, we want to invalidate the boundary. if (helpers.shouldInvalidateReactRefreshBoundary(helpers.getRefreshBoundarySignature(prevExports), helpers.getRefreshBoundarySignature(currentExports))) { module.hot.invalidate(); } else { helpers.scheduleUpdate(); } } } else { // Since we just executed the code for the module, it's possible that the // new exports made it ineligible for being a boundary. // We only care about the case when we were _previously_ a boundary, // because we already accepted this update (accidental side effect). const isNoLongerABoundary = prevExports !== null; if (isNoLongerABoundary) { module.hot.invalidate(); } } }
This is adapted from https://github.com/vercel/next.js/blob/3466862d9dc9c8bb3131712134d38757b918d1c0/packages/react-refresh-utils/internal/ReactRefreshModule.runtime.ts
registerExportsAndSetupBoundaryForReactRefresh
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function updateChunksPhase(chunksAddedModules, chunksDeletedModules) { for (const [chunkPath, addedModuleIds] of chunksAddedModules){ for (const moduleId of addedModuleIds){ addModuleToChunk(moduleId, chunkPath); } } const disposedModules = new Set(); for (const [chunkPath, addedModuleIds] of chunksDeletedModules){ for (const moduleId of addedModuleIds){ if (removeModuleFromChunk(moduleId, chunkPath)) { disposedModules.add(moduleId); } } } return { disposedModules }; }
Adds, deletes, and moves modules between chunks. This must happen before the dispose phase as it needs to know which modules were removed from all chunks, which we can only compute *after* taking care of added and moved modules.
updateChunksPhase
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function disposeModule(moduleId, mode) { const module = devModuleCache[moduleId]; if (!module) { return; } const hotState = moduleHotState.get(module); const data = {}; // Run the `hot.dispose` handler, if any, passing in the persistent // `hot.data` object. for (const disposeHandler of hotState.disposeHandlers){ disposeHandler(data); } // This used to warn in `getOrInstantiateModuleFromParent` when a disposed // module is still importing other modules. module.hot.active = false; moduleHotState.delete(module); // TODO(alexkirsz) Dependencies: delete the module from outdated deps. // Remove the disposed module from its children's parent list. // It will be added back once the module re-instantiates and imports its // children again. for (const childId of module.children){ const child = devModuleCache[childId]; if (!child) { continue; } const idx = child.parents.indexOf(module.id); if (idx >= 0) { child.parents.splice(idx, 1); } } switch(mode){ case 'clear': delete devModuleCache[module.id]; moduleHotData.delete(module.id); break; case 'replace': moduleHotData.set(module.id, data); break; default: invariant(mode, (mode)=>`invalid mode: ${mode}`); } }
Disposes of an instance of a module. Returns the persistent hot data that should be kept for the next module instance. NOTE: mode = "replace" will not remove modules from the devModuleCache This must be done in a separate step afterwards. This is important because all modules need to be disposed to update the parent/child relationships before they are actually removed from the devModuleCache. If this was done in this method, the following disposeModule calls won't find the module from the module id in the cache.
disposeModule
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function removeModuleFromChunk(moduleId, chunkPath) { const moduleChunks = moduleChunksMap.get(moduleId); moduleChunks.delete(chunkPath); const chunkModules = chunkModulesMap.get(chunkPath); chunkModules.delete(moduleId); const noRemainingModules = chunkModules.size === 0; if (noRemainingModules) { chunkModulesMap.delete(chunkPath); } const noRemainingChunks = moduleChunks.size === 0; if (noRemainingChunks) { moduleChunksMap.delete(moduleId); } return noRemainingChunks; }
Removes a module from a chunk. Returns `true` if there are no remaining chunks including this module.
removeModuleFromChunk
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function disposeChunkList(chunkListPath) { const chunkPaths = chunkListChunksMap.get(chunkListPath); if (chunkPaths == null) { return false; } chunkListChunksMap.delete(chunkListPath); for (const chunkPath of chunkPaths){ const chunkChunkLists = chunkChunkListsMap.get(chunkPath); chunkChunkLists.delete(chunkListPath); if (chunkChunkLists.size === 0) { chunkChunkListsMap.delete(chunkPath); disposeChunk(chunkPath); } } // We must also dispose of the chunk list's chunk itself to ensure it may // be reloaded properly in the future. const chunkListUrl = getChunkRelativeUrl(chunkListPath); DEV_BACKEND.unloadChunk?.(chunkListUrl); return true; }
Disposes of a chunk list and its corresponding exclusive chunks.
disposeChunkList
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function disposeChunk(chunkPath) { const chunkUrl = getChunkRelativeUrl(chunkPath); // This should happen whether the chunk has any modules in it or not. // For instance, CSS chunks have no modules in them, but they still need to be unloaded. DEV_BACKEND.unloadChunk?.(chunkUrl); const chunkModules = chunkModulesMap.get(chunkPath); if (chunkModules == null) { return false; } chunkModules.delete(chunkPath); for (const moduleId of chunkModules){ const moduleChunks = moduleChunksMap.get(moduleId); moduleChunks.delete(chunkPath); const noRemainingChunks = moduleChunks.size === 0; if (noRemainingChunks) { moduleChunksMap.delete(moduleId); disposeModule(moduleId, 'clear'); availableModules.delete(moduleId); } } return true; }
Disposes of a chunk and its corresponding exclusive modules. @returns Whether the chunk was disposed of.
disposeChunk
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function registerChunkList(chunkList) { const chunkListScript = chunkList.script; const chunkListPath = getPathFromScript(chunkListScript); // The "chunk" is also registered to finish the loading in the backend BACKEND.registerChunk(chunkListPath); globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS.push([ chunkListPath, handleApply.bind(null, chunkListPath) ]); // Adding chunks to chunk lists and vice versa. const chunkPaths = new Set(chunkList.chunks.map(getChunkPath)); chunkListChunksMap.set(chunkListPath, chunkPaths); for (const chunkPath of chunkPaths){ let chunkChunkLists = chunkChunkListsMap.get(chunkPath); if (!chunkChunkLists) { chunkChunkLists = new Set([ chunkListPath ]); chunkChunkListsMap.set(chunkPath, chunkChunkLists); } else { chunkChunkLists.add(chunkListPath); } } if (chunkList.source === 'entry') { markChunkListAsRuntime(chunkListPath); } }
Subscribes to chunk list updates from the update server and applies them.
registerChunkList
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function augmentContext(context) { return context; }
This file contains the runtime code specific to the Turbopack development ECMAScript DOM runtime. It will be appended to the base development runtime code.
augmentContext
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
async registerChunk (chunkPath, params) { const chunkUrl = getChunkRelativeUrl(chunkPath); const resolver = getOrCreateResolver(chunkUrl); resolver.resolve(); if (params == null) { return; } for (const otherChunkData of params.otherChunks){ const otherChunkPath = getChunkPath(otherChunkData); const otherChunkUrl = getChunkRelativeUrl(otherChunkPath); // Chunk might have started loading, so we want to avoid triggering another load. getOrCreateResolver(otherChunkUrl); } // This waits for chunks to be loaded, but also marks included items as available. await Promise.all(params.otherChunks.map((otherChunkData)=>loadChunk({ type: SourceType.Runtime, chunkPath }, otherChunkData))); if (params.runtimeModuleIds.length > 0) { for (const moduleId of params.runtimeModuleIds){ getOrInstantiateRuntimeModule(moduleId, chunkPath); } } }
Maps chunk paths to the corresponding resolver.
registerChunk
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
loadChunk (chunkUrl, source) { return doLoadChunk(chunkUrl, source); }
Loads the given chunk, and returns a promise that resolves once the chunk has been loaded.
loadChunk
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function done(err) { if (!cbCalled) { cb(err); cbCalled = true; } }
This is the exposed module. This method facilitates copying a file. @param {String} fileSrc @param {String} fileDest @param {Function} cb @access public
done
javascript
aws/aws-iot-device-sdk-js
examples/lib/copy-file.js
https://github.com/aws/aws-iot-device-sdk-js/blob/master/examples/lib/copy-file.js
Apache-2.0
Unirest = function (method, uri, headers, body, callback) { var unirest = function (uri, headers, body, callback) { var $this = { /** * Stream Multipart form-data request * * @type {Boolean} */ _stream: false, /** * Container to hold multipart form data for processing upon request. * * @type {Array} * @private */ _multipart: [], /** * Container to hold form data for processing upon request. * * @type {Array} * @private */ _form: [], /** * Request option container for details about the request. * * @type {Object} */ options: { /** * Url obtained from request method arguments. * * @type {String} */ url: uri, /** * Method obtained from request method arguments. * * @type {String} */ method: method, /** * List of headers with case-sensitive fields. * * @type {Object} */ headers: {} }, hasHeader: function (name) { var headers var lowercaseHeaders name = name.toLowerCase() headers = Object.keys($this.options.headers) lowercaseHeaders = headers.map(function (header) { return header.toLowerCase() }) for (var i = 0; i < lowercaseHeaders.length; i++) { if (lowercaseHeaders[i] === name) { return headers[i] } } return false }, /** * Turn on multipart-form streaming * * @return {Object} */ stream: function () { $this._stream = true return this }, /** * Attaches a field to the multipart-form request, with pre-processing. * * @param {String} name * @param {String} value * @return {Object} */ field: function (name, value, options) { return handleField(name, value, options) }, /** * Attaches a file to the multipart-form request. * * @param {String} name * @param {String|Object} path * @return {Object} */ attach: function (name, path, options) { options = options || {} options.attachment = true return handleField(name, path, options) }, /** * Attaches field to the multipart-form request, with no pre-processing. * * @param {String} name * @param {String|Object} path * @param {Object} options * @return {Object} */ rawField: function (name, value, options) { $this._multipart.push({ name: name, value: value, options: options, attachment: options.attachment || false }) }, /** * Basic Header Authentication Method * * Supports user being an Object to reflect Request * Supports user, password to reflect SuperAgent * * @param {String|Object} user * @param {String} password * @param {Boolean} sendImmediately * @return {Object} */ auth: function (user, password, sendImmediately) { $this.options.auth = (is(user).a(Object)) ? user : { user: user, password: password, sendImmediately: sendImmediately } return $this }, /** * Sets header field to value * * @param {String} field Header field * @param {String} value Header field value * @return {Object} */ header: function (field, value) { if (is(field).a(Object)) { for (var key in field) { if (Object.prototype.hasOwnProperty.call(field, key)) { $this.header(key, field[key]) } } return $this } var existingHeaderName = $this.hasHeader(field) $this.options.headers[existingHeaderName || field] = value return $this }, /** * Serialize value as querystring representation, and append or set on `Request.options.url` * * @param {String|Object} value * @return {Object} */ query: function (value) { if (is(value).a(Object)) value = Unirest.serializers.form(value) if (!value.length) return $this $this.options.url += (does($this.options.url).contain('?') ? '&' : '?') + value return $this }, /** * Set _content-type_ header with type passed through `mime.getType()` when necessary. * * @param {String} type * @return {Object} */ type: function (type) { $this.header('Content-Type', does(type).contain('/') ? type : mime.getType(type)) return $this }, /** * Data marshalling for HTTP request body data * * Determines whether type is `form` or `json`. * For irregular mime-types the `.type()` method is used to infer the `content-type` header. * * When mime-type is `application/x-www-form-urlencoded` data is appended rather than overwritten. * * @param {Mixed} data * @return {Object} */ send: function (data) { var type = $this.options.headers[$this.hasHeader('content-type')] if ((is(data).a(Object) || is(data).a(Array)) && !Buffer.isBuffer(data)) { if (!type) { $this.type('form') type = $this.options.headers[$this.hasHeader('content-type')] $this.options.body = Unirest.serializers.form(data) } else if (~type.indexOf('json')) { $this.options.json = true if ($this.options.body && is($this.options.body).a(Object)) { for (var key in data) { if (Object.prototype.hasOwnProperty.call(data, key)) { $this.options.body[key] = data[key] } } } else { $this.options.body = data } } else { $this.options.body = Unirest.Request.serialize(data, type) } } else if (is(data).a(String)) { if (!type) { $this.type('form') type = $this.options.headers[$this.hasHeader('content-type')] } if (type === 'application/x-www-form-urlencoded') { $this.options.body = $this.options.body ? $this.options.body + '&' + data : data } else { $this.options.body = ($this.options.body || '') + data } } else { $this.options.body = data } return $this }, /** * Takes multipart options and places them on `options.multipart` array. * Transforms body when an `Object` or _content-type_ is present. * * Example: * * Unirest.get('http://google.com').part({ * 'content-type': 'application/json', * body: { * phrase: 'Hello' * } * }).part({ * 'content-type': 'application/json', * body: { * phrase: 'World' * } * }).end(function (response) {}) * * @param {Object|String} options When an Object, headers should be placed directly on the object, * not under a child property. * @return {Object} */ part: function (options) { if (!$this._multipart) { $this.options.multipart = [] } if (is(options).a(Object)) { if (options['content-type']) { var type = Unirest.type(options['content-type'], true) if (type) options.body = Unirest.Response.parse(options.body) } else { if (is(options.body).a(Object)) { options.body = Unirest.serializers.json(options.body) } } $this.options.multipart.push(options) } else { $this.options.multipart.push({ body: options }) } return $this }, /** * Instructs the Request to be retried if specified error status codes (4xx, 5xx, ETIMEDOUT) are returned. * Retries are delayed with an exponential backoff. * * @param {(err: Error) => boolean} [callback] - Invoked on response error. Return false to stop next request. * @param {Object} [options] - Optional retry configuration to override defaults. * @param {number} [options.attempts=3] - The number of retry attempts. * @param {number} [options.delayInMs=250] - The delay in milliseconds (delayInMs *= delayMulti) * @param {number} [options.delayMulti=2] - The multiplier of delayInMs after each attempt. * @param {Array<string|number>} [options.statusCodes=["ETIMEDOUT", "5xx"]] - The status codes to retry on. * @return {Object} */ retry: function (callback, options) { $this.options.retry = { callback: typeof callback === "function" ? callback : null, attempts: options && +options.attempts || 3, delayInMs: options && +options.delayInMs || 250, delayMulti: options && +options.delayMulti || 2, statusCodes: (options && options.statusCodes || ["ETIMEDOUT", "5xx"]).slice(0) }; return $this }, /** * Proxies the call to end. This adds support for using promises as well as async/await. * * @param {Function} callback * @return {Promise} **/ then: function (callback) { return new Promise((resolve, reject) => { this.end(result => { try { resolve(callback(result)) } catch (err) { reject(err) } }) }) }, /** * Sends HTTP Request and awaits Response finalization. Request compression and Response decompression occurs here. * Upon HTTP Response post-processing occurs and invokes `callback` with a single argument, the `[Response](#response)` object. * * @param {Function} callback * @return {Object} */ end: function (callback) { var self = this var Request var header var parts var form function handleRetriableRequestResponse (result) { // If retries is not defined or all attempts tried, return true to invoke end's callback. if ($this.options.retry === undefined || $this.options.retry.attempts === 0) { return true } // If status code is not listed, abort with return true to invoke end's callback. var isStatusCodeDefined = (function (code, codes) { if (codes.indexOf(code) !== -1) { return true } return codes.reduce(function (p, c) { return p || String(code).split("").every(function (ch, i) { return ch === "x" || ch === c[i] }) }, false) }(result.code || result.error && result.error.code, $this.options.retry.statusCodes)) if (!isStatusCodeDefined) { return true } if ($this.options.retry.callback) { var isContinue = $this.options.retry.callback(result) // If retry callback returns false, stop retries and invoke end's callback. if (isContinue === false) { return true; } } setTimeout(function () { self.end(callback) }, $this.options.retry.delayInMs) $this.options.retry.attempts-- $this.options.retry.delayInMs *= $this.options.retry.delayMulti // Return false to not invoke end's callback. return false } function handleRequestResponse (error, response, body) { var result = {} var status var data var type // Handle pure error if (error && !response) { result.error = error if (handleRetriableRequestResponse(result) && callback) { callback(result) } return } // Handle No Response... // This is weird. if (!response) { console.log('This is odd, report this action / request to: http://github.com/mashape/unirest-nodejs') result.error = { message: 'No response found.' } if (handleRetriableRequestResponse(result) && callback) { callback(result) } return } // Create response reference result = response // Create response status reference status = response.statusCode // Normalize MSIE response to HTTP 204 status = (status === 1223 ? 204 : status) // Obtain status range typecode (1, 2, 3, 4, 5, etc.) type = status / 100 | 0 // Generate sugar helper properties for status information result.code = status result.status = status result.statusType = type result.info = type === 1 result.ok = type === 2 result.clientError = type === 4 result.serverError = type === 5 result.error = (type === 4 || type === 5) ? (function generateErrorMessage () { var msg = 'got ' + result.status + ' response' var err = new Error(msg) err.status = result.status return err })() : false // Iterate over Response Status Codes and generate more sugar for (var name in Unirest.Response.statusCodes) { result[name] = Unirest.Response.statusCodes[name] === status } // Cookie Holder result.cookies = {} // Cookie Sugar Method result.cookie = function (name) { return result.cookies[name] } function setCookie (cookie) { var crumbs = Unirest.trim(cookie).split('=') var key = Unirest.trim(crumbs[0]) var value = Unirest.trim(crumbs.slice(1).join('=')) if (crumbs[0] && crumbs[0] !== '') { result.cookies[key] = value === '' ? true : value } } if (response.cookies && is(response.cookies).a(Object) && Object.keys(response.cookies).length > 0) { result.cookies = response.cookies } else { // Handle cookies to be set var cookies = response.headers['set-cookie'] if (cookies && is(cookies).a(Array)) { for (var index = 0; index < cookies.length; index++) { var entry = cookies[index] if (is(entry).a(String) && does(entry).contain(';')) { entry.split(';').forEach(setCookie) } } } // Handle cookies that have been set cookies = response.headers.cookie if (cookies && is(cookies).a(String)) { cookies.split(';').forEach(setCookie) } } // Obtain response body body = body || response.body result.raw_body = body result.headers = response.headers // Handle Response Body if (body) { type = Unirest.type(result.headers['content-type'], true) if (type) data = Unirest.Response.parse(body, type) else data = body } result.body = data ;(handleRetriableRequestResponse(result)) && (callback) && callback(result) } function handleGZIPResponse (response) { if (/^(deflate|gzip)$/.test(response.headers['content-encoding'])) { var unzip = zlib.createUnzip() var stream = new Stream() var _on = response.on var decoder // Keeping node happy stream.req = response.req // Make sure we emit prior to processing unzip.on('error', function (error) { // Catch the parser error when there is no content if (error.errno === zlib.Z_BUF_ERROR || error.errno === zlib.Z_DATA_ERROR) { stream.emit('end') return } stream.emit('error', error) }) // Start the processing response.pipe(unzip) // Ensure encoding is captured response.setEncoding = function (type) { decoder = new StringDecoder(type) } // Capture decompression and decode with captured encoding unzip.on('data', function (buffer) { if (!decoder) return stream.emit('data', buffer) var string = decoder.write(buffer) if (string.length) stream.emit('data', string) }) // Emit yoself unzip.on('end', function () { stream.emit('end') }) response.on = function (type, next) { if (type === 'data' || type === 'end') { stream.on(type, next) } else if (type === 'error') { _on.call(response, type, next) } else { _on.call(response, type, next) } } } } function handleFormData (form) { for (var i = 0; i < $this._multipart.length; i++) { var item = $this._multipart[i] if (item.attachment && is(item.value).a(String)) { if (does(item.value).contain('http://') || does(item.value).contain('https://')) { item.value = Unirest.request(item.value) } else { item.value = fs.createReadStream(path.resolve(item.value)) } } form.append(item.name, item.value, item.options) } return form } if ($this._multipart.length && !$this._stream) { header = $this.options.headers[$this.hasHeader('content-type')] parts = URL.parse($this.options.url) form = new FormData() if (header) { $this.options.headers['content-type'] = header.split(';')[0] + '; boundary=' + form.getBoundary() } else { $this.options.headers['content-type'] = 'multipart/form-data; boundary=' + form.getBoundary() } function authn(auth) { if (!auth) return null; if (typeof auth === 'string') return auth; if (auth.user && auth.pass) return auth.user + ':' + auth.pass; return auth; } return handleFormData(form).submit({ protocol: parts.protocol, port: parts.port, // Formdata doesn't expect port to be included with host // so we use hostname rather than host host: parts.hostname, path: parts.path, method: $this.options.method, headers: $this.options.headers, auth: authn($this.options.auth || parts.auth) }, function (error, response) { var decoder = new StringDecoder('utf8') if (error) { return handleRequestResponse(error, response) } if (!response.body) { response.body = '' } // Node 10+ response.resume() // GZIP, Feel me? handleGZIPResponse(response) // Fallback response.on('data', function (chunk) { if (typeof chunk === 'string') response.body += chunk else response.body += decoder.write(chunk) }) // After all, we end up here response.on('end', function () { return handleRequestResponse(error, response) }) }) } Request = Unirest.request($this.options, handleRequestResponse) Request.on('response', handleGZIPResponse) if ($this._multipart.length && $this._stream) { handleFormData(Request.form()) } return Request } } /** * Alias for _.header_ * @type {Function} */ $this.headers = $this.header /** * Alias for _.header_ * * @type {Function} */ $this.set = $this.header /** * Alias for _.end_ * * @type {Function} */ $this.complete = $this.end /** * Aliases for _.end_ * * @type {Object} */ $this.as = { json: $this.end, binary: $this.end, string: $this.end } /** * Handles Multipart Field Processing * * @param {String} name * @param {Mixed} value * @param {Object} options */ function handleField (name, value, options) { var serialized var length var key var i options = options || { attachment: false } if (is(name).a(Object)) { for (key in name) { if (Object.prototype.hasOwnProperty.call(name, key)) { handleField(key, name[key], options) } } } else { if (is(value).a(Array)) { for (i = 0, length = value.length; i < length; i++) { serialized = handleFieldValue(value[i]) if (serialized) { $this.rawField(name, serialized, options) } } } else if (value != null) { $this.rawField(name, handleFieldValue(value), options) } } return $this } /** * Handles Multipart Value Processing * * @param {Mixed} value */ function handleFieldValue (value) { if (!(value instanceof Buffer || typeof value === 'string')) { if (is(value).a(Object)) { if (value instanceof fs.FileReadStream) { return value } else { return Unirest.serializers.json(value) } } else { return value.toString() } } else return value } function setupOption (name, ref) { $this[name] = function (arg) { $this.options[ref || name] = arg return $this } } // Iterates over a list of option methods to generate the chaining // style of use you see in Superagent and jQuery. for (var x in Unirest.enum.options) { if (Object.prototype.hasOwnProperty.call(Unirest.enum.options, x)) { var option = Unirest.enum.options[x] var reference = null if (option.indexOf(':') > -1) { option = option.split(':') reference = option[1] option = option[0] } setupOption(option, reference) } } if (headers && typeof headers === 'function') { callback = headers headers = null } else if (body && typeof body === 'function') { callback = body body = null } if (headers) $this.set(headers) if (body) $this.send(body) return callback ? $this.end(callback) : $this } return uri ? unirest(uri, headers, body, callback) : unirest }
Initialize our Rest Container @type {Object}
Unirest
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function handleRetriableRequestResponse (result) { // If retries is not defined or all attempts tried, return true to invoke end's callback. if ($this.options.retry === undefined || $this.options.retry.attempts === 0) { return true } // If status code is not listed, abort with return true to invoke end's callback. var isStatusCodeDefined = (function (code, codes) { if (codes.indexOf(code) !== -1) { return true } return codes.reduce(function (p, c) { return p || String(code).split("").every(function (ch, i) { return ch === "x" || ch === c[i] }) }, false) }(result.code || result.error && result.error.code, $this.options.retry.statusCodes)) if (!isStatusCodeDefined) { return true } if ($this.options.retry.callback) { var isContinue = $this.options.retry.callback(result) // If retry callback returns false, stop retries and invoke end's callback. if (isContinue === false) { return true; } } setTimeout(function () { self.end(callback) }, $this.options.retry.delayInMs) $this.options.retry.attempts-- $this.options.retry.delayInMs *= $this.options.retry.delayMulti // Return false to not invoke end's callback. return false }
Sends HTTP Request and awaits Response finalization. Request compression and Response decompression occurs here. Upon HTTP Response post-processing occurs and invokes `callback` with a single argument, the `[Response](#response)` object. @param {Function} callback @return {Object}
handleRetriableRequestResponse
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function handleField (name, value, options) { var serialized var length var key var i options = options || { attachment: false } if (is(name).a(Object)) { for (key in name) { if (Object.prototype.hasOwnProperty.call(name, key)) { handleField(key, name[key], options) } } } else { if (is(value).a(Array)) { for (i = 0, length = value.length; i < length; i++) { serialized = handleFieldValue(value[i]) if (serialized) { $this.rawField(name, serialized, options) } } } else if (value != null) { $this.rawField(name, handleFieldValue(value), options) } } return $this }
Handles Multipart Field Processing @param {String} name @param {Mixed} value @param {Object} options
handleField
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function handleFieldValue (value) { if (!(value instanceof Buffer || typeof value === 'string')) { if (is(value).a(Object)) { if (value instanceof fs.FileReadStream) { return value } else { return Unirest.serializers.json(value) } } else { return value.toString() } } else return value }
Handles Multipart Value Processing @param {Mixed} value
handleFieldValue
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function setupMethod (method) { Unirest[method] = Unirest(method) }
Generate sugar for request library. This allows us to mock super-agent chaining style while using request library under the hood.
setupMethod
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function is (value) { return { a: function (check) { if (check.prototype) check = check.prototype.constructor.name var type = Object.prototype.toString.call(value).slice(8, -1).toLowerCase() return value != null && type === check.toLowerCase() } } }
Simple Utility Methods for checking information about a value. @param {Mixed} value Could be anything. @return {Object}
is
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function broadcast(data, channel) { for (var client of server.clients) { if (channel ? client.channel === channel : client.channel) { send(data, client) } } }
Sends data to all clients channel: if not null, restricts broadcast to clients in the channel
broadcast
javascript
AndrewBelt/hack.chat
server.js
https://github.com/AndrewBelt/hack.chat/blob/master/server.js
MIT
function Options(data) { this.style = data.style; this.color = data.color; this.size = data.size; this.phantom = data.phantom; this.font = data.font; if (data.parentStyle === undefined) { this.parentStyle = data.style; } else { this.parentStyle = data.parentStyle; } if (data.parentSize === undefined) { this.parentSize = data.size; } else { this.parentSize = data.parentSize; } }
This is the main options class. It contains the style, size, color, and font of the current parse level. It also contains the style and size of the parent parse level, so size changes can be handled efficiently. Each of the `.with*` and `.reset` functions passes its current style and size as the parentStyle and parentSize of the new options class, so parent handling is taken care of automatically.
Options
javascript
AndrewBelt/hack.chat
client/katex/katex.js
https://github.com/AndrewBelt/hack.chat/blob/master/client/katex/katex.js
MIT
function get(option, defaultValue) { return option === undefined ? defaultValue : option; }
Helper function for getting a default value if the value is undefined
get
javascript
AndrewBelt/hack.chat
client/katex/katex.js
https://github.com/AndrewBelt/hack.chat/blob/master/client/katex/katex.js
MIT
mathDefault = function(value, mode, color, classes, type) { if (type === "mathord") { return mathit(value, mode, color, classes); } else if (type === "textord") { return makeSymbol( value, "Main-Regular", mode, color, classes.concat(["mathrm"])); } else { throw new Error("unexpected type: " + type + " in mathDefault"); } }
Makes a symbol in the default font for mathords and textords.
mathDefault
javascript
AndrewBelt/hack.chat
client/katex/katex.js
https://github.com/AndrewBelt/hack.chat/blob/master/client/katex/katex.js
MIT
buildHTML = function(tree, settings) { // buildExpression is destructive, so we need to make a clone // of the incoming tree so that it isn't accidentally changed tree = JSON.parse(JSON.stringify(tree)); var startStyle = Style.TEXT; if (settings.displayMode) { startStyle = Style.DISPLAY; } // Setup the default options var options = new Options({ style: startStyle, size: "size5" }); // Build the expression contained in the tree var expression = buildExpression(tree, options); var body = makeSpan(["base", options.style.cls()], expression); // Add struts, which ensure that the top of the HTML element falls at the // height of the expression, and the bottom of the HTML element falls at the // depth of the expression. var topStrut = makeSpan(["strut"]); var bottomStrut = makeSpan(["strut", "bottom"]); topStrut.style.height = body.height + "em"; bottomStrut.style.height = (body.height + body.depth) + "em"; // We'd like to use `vertical-align: top` but in IE 9 this lowers the // baseline of the box to the bottom of this strut (instead staying in the // normal place) so we use an absolute value for vertical-align instead bottomStrut.style.verticalAlign = -body.depth + "em"; // Wrap the struts and body together var htmlNode = makeSpan(["katex-html"], [topStrut, bottomStrut, body]); htmlNode.setAttribute("aria-hidden", "true"); return htmlNode; }
Take an entire parse tree, and build it into an appropriate set of HTML nodes.
buildHTML
javascript
AndrewBelt/hack.chat
client/katex/katex.js
https://github.com/AndrewBelt/hack.chat/blob/master/client/katex/katex.js
MIT
getVariant = function(group, options) { var font = options.font; if (!font) { return null; } var mode = group.mode; if (font === "mathit") { return "italic"; } var value = group.value; if (utils.contains(["\\imath", "\\jmath"], value)) { return null; } if (symbols[mode][value] && symbols[mode][value].replace) { value = symbols[mode][value].replace; } var fontName = fontMap[font].fontName; if (fontMetrics.getCharacterMetrics(value, fontName)) { return fontMap[options.font].variant; } return null; }
Returns the math variant as a string or null if none is required.
getVariant
javascript
AndrewBelt/hack.chat
client/katex/katex.js
https://github.com/AndrewBelt/hack.chat/blob/master/client/katex/katex.js
MIT
buildExpression = function(expression, options) { var groups = []; for (var i = 0; i < expression.length; i++) { var group = expression[i]; groups.push(buildGroup(group, options)); } return groups; }
Takes a list of nodes, builds them, and returns a list of the generated MathML nodes. A little simpler than the HTML version because we don't do any previous-node handling.
buildExpression
javascript
AndrewBelt/hack.chat
client/katex/katex.js
https://github.com/AndrewBelt/hack.chat/blob/master/client/katex/katex.js
MIT
buildGroup = function(group, options) { if (!group) { return new mathMLTree.MathNode("mrow"); } if (groupTypes[group.type]) { // Call the groupTypes function return groupTypes[group.type](group, options); } else { throw new ParseError( "Got group of unknown type: '" + group.type + "'"); } }
Takes a group from the parser and calls the appropriate groupTypes function on it to produce a MathML node.
buildGroup
javascript
AndrewBelt/hack.chat
client/katex/katex.js
https://github.com/AndrewBelt/hack.chat/blob/master/client/katex/katex.js
MIT
buildMathML = function(tree, texExpression, settings) { settings = settings || new Settings({}); var startStyle = Style.TEXT; if (settings.displayMode) { startStyle = Style.DISPLAY; } // Setup the default options var options = new Options({ style: startStyle, size: "size5" }); var expression = buildExpression(tree, options); // Wrap up the expression in an mrow so it is presented in the semantics // tag correctly. var wrapper = new mathMLTree.MathNode("mrow", expression); // Build a TeX annotation of the source var annotation = new mathMLTree.MathNode( "annotation", [new mathMLTree.TextNode(texExpression)]); annotation.setAttribute("encoding", "application/x-tex"); var semantics = new mathMLTree.MathNode( "semantics", [wrapper, annotation]); var math = new mathMLTree.MathNode("math", [semantics]); // You can't style <math> nodes, so we wrap the node in a span. return makeSpan(["katex-mathml"], [math]); }
Takes a full parse tree and settings and builds a MathML representation of it. In particular, we put the elements from building the parse tree into a <semantics> tag so we can also include that TeX source as an annotation. Note that we actually return a domTree element with a `<math>` inside it so we can do appropriate styling.
buildMathML
javascript
AndrewBelt/hack.chat
client/katex/katex.js
https://github.com/AndrewBelt/hack.chat/blob/master/client/katex/katex.js
MIT
function MathNode(type, children) { this.type = type; this.attributes = {}; this.children = children || []; }
This node represents a general purpose MathML node of any type. The constructor requires the type of node to create (for example, `"mo"` or `"mspace"`, corresponding to `<mo>` and `<mspace>` tags).
MathNode
javascript
AndrewBelt/hack.chat
client/katex/katex.js
https://github.com/AndrewBelt/hack.chat/blob/master/client/katex/katex.js
MIT
deflt = function(setting, defaultIfUndefined) { return setting === undefined ? defaultIfUndefined : setting; }
Provide a default value if a setting is undefined
deflt
javascript
AndrewBelt/hack.chat
client/katex/katex.js
https://github.com/AndrewBelt/hack.chat/blob/master/client/katex/katex.js
MIT
optionsToArray(obj, optionsPrefix, hasEquals) { optionsPrefix = optionsPrefix || '--' var ret = [] Object.keys(obj).forEach((key) => { ret.push(optionsPrefix + key + (hasEquals ? '=' : '')) if (obj[key]) { ret.push(obj[key]) } }) return ret }
Convert an options object into a valid arguments array for the child_process.spawn method from: var options = { foo: 'hello', baz: 'world' } to: ['--foo=', 'hello', '--baz=','world'] @param { Object } obj - object we need to convert @param { Array } optionsPrefix - use a prefix for the new array created @param { Boolean } hasEquals - set the options commands using the equal @returns { Array } - options array
optionsToArray
javascript
GianlucaGuarini/es6-project-starter-kit
tasks/_utils.js
https://github.com/GianlucaGuarini/es6-project-starter-kit/blob/master/tasks/_utils.js
MIT
extend(obj1, obj2) { for (var i in obj2) { if (obj2.hasOwnProperty(i)) { obj1[i] = obj2[i] } } return obj1 }
Simple object extend function @param { Object } obj1 - destination @param { Object } obj2 - source @returns { Object } - destination object
extend
javascript
GianlucaGuarini/es6-project-starter-kit
tasks/_utils.js
https://github.com/GianlucaGuarini/es6-project-starter-kit/blob/master/tasks/_utils.js
MIT
exec(command, args, envVariables) { var path = require('path'), os = require('os') return new Promise(function(resolve, reject) { if (os.platform() == 'win32' || os.platform() == 'win64') command += '.cmd' // extend the env variables with some other custom options utils.extend(process.env, envVariables) utils.print(`Executing: ${command} ${args.join(' ')} \n`, 'confirm') var cmd = spawn(path.normalize(command), args, { stdio: 'inherit', cwd: process.cwd() }) cmd.on('exit', function(code) { if (code === 1) reject() else resolve() }) }) }
Run any system command @param { String } command - command to execute @param { Array } args - command arguments @param { Object } envVariables - command environment variables @returns { Promise } chainable promise object
exec
javascript
GianlucaGuarini/es6-project-starter-kit
tasks/_utils.js
https://github.com/GianlucaGuarini/es6-project-starter-kit/blob/master/tasks/_utils.js
MIT
listFiles(path, mustDelete) { utils.print(`Listing all the files in the folder: ${path}`, 'confirm') var files = [] if (fs.existsSync(path)) { var tmpFiles = fs.readdirSync(path) tmpFiles.forEach((file) => { var curPath = path + '/' + file files.push(curPath) if (fs.lstatSync(curPath).isDirectory()) { // recurse utils.listFiles(curPath, mustDelete) } else if (mustDelete) { // delete file fs.unlinkSync(curPath) } }) if (mustDelete) { fs.rmdirSync(path) } } return files }
Read all the files crawling starting from a certain folder path @param { String } path directory path @param { bool } mustDelete delete the files found @returns { Array } files path list
listFiles
javascript
GianlucaGuarini/es6-project-starter-kit
tasks/_utils.js
https://github.com/GianlucaGuarini/es6-project-starter-kit/blob/master/tasks/_utils.js
MIT
clean(path) { var files = utils.listFiles(path, true) utils.print(`Deleting the following files: \n ${files.join('\n')}`, 'cool') }
Delete synchronously any folder or file @param { String } path - path to clean
clean
javascript
GianlucaGuarini/es6-project-starter-kit
tasks/_utils.js
https://github.com/GianlucaGuarini/es6-project-starter-kit/blob/master/tasks/_utils.js
MIT
print(msg, type) { var color switch (type) { case 'error': color = '\x1B[31m' break case 'warning': color = '\x1B[33m' break case 'confirm': color = '\x1B[32m' break case 'cool': color = '\x1B[36m' break default: color = '' } console.log(`${color} ${msg} \x1B[39m`) }
Log messages in the terminal using custom colors @param { String } msg - message to output @param { String } type - message type to handle the right color
print
javascript
GianlucaGuarini/es6-project-starter-kit
tasks/_utils.js
https://github.com/GianlucaGuarini/es6-project-starter-kit/blob/master/tasks/_utils.js
MIT
function SmoothieChart(options) { this.options = Util.extend({}, SmoothieChart.defaultChartOptions, options); this.seriesSet = []; this.currentValueRange = 1; this.currentVisMinValue = 0; this.lastRenderTimeMillis = 0; }
Initialises a new <code>SmoothieChart</code>. Options are optional, and should be of the form below. Just specify the values you need and the rest will be given sensible defaults as shown: <pre> { minValue: undefined, // specify to clamp the lower y-axis to a given value maxValue: undefined, // specify to clamp the upper y-axis to a given value maxValueScale: 1, // allows proportional padding to be added above the chart. for 10% padding, specify 1.1. minValueScale: 1, // allows proportional padding to be added below the chart. for 10% padding, specify 1.1. yRangeFunction: undefined, // function({min: , max: }) { return {min: , max: }; } scaleSmoothing: 0.125, // controls the rate at which y-value zoom animation occurs millisPerPixel: 20, // sets the speed at which the chart pans by enableDpiScaling: true, // support rendering at different DPI depending on the device yMinFormatter: function(min, precision) { // callback function that formats the min y value label return parseFloat(min).toFixed(precision); }, yMaxFormatter: function(max, precision) { // callback function that formats the max y value label return parseFloat(max).toFixed(precision); }, maxDataSetLength: 2, interpolation: 'bezier' // one of 'bezier', 'linear', or 'step' timestampFormatter: null, // optional function to format time stamps for bottom of chart // you may use SmoothieChart.timeFormatter, or your own: function(date) { return ''; } scrollBackwards: false, // reverse the scroll direction of the chart horizontalLines: [], // [ { value: 0, color: '#ffffff', lineWidth: 1 } ] grid: { fillStyle: '#000000', // the background colour of the chart lineWidth: 1, // the pixel width of grid lines strokeStyle: '#777777', // colour of grid lines millisPerLine: 1000, // distance between vertical grid lines sharpLines: false, // controls whether grid lines are 1px sharp, or softened verticalSections: 2, // number of vertical sections marked out by horizontal grid lines borderVisible: true // whether the grid lines trace the border of the chart or not }, labels { disabled: false, // enables/disables labels showing the min/max values fillStyle: '#ffffff', // colour for text of labels, fontSize: 15, fontFamily: 'sans-serif', precision: 2 } } </pre> @constructor
SmoothieChart
javascript
01alchemist/TurboScript
benchmark/web-dsp/demo/smoothie.js
https://github.com/01alchemist/TurboScript/blob/master/benchmark/web-dsp/demo/smoothie.js
Apache-2.0
function deriveConcreteClass(context, type, parameters, scope) { var templateNode = type.resolvedType.pointerTo ? type.resolvedType.pointerTo.symbol.node : type.resolvedType.symbol.node; var templateName = templateNode.stringValue; var typeName = templateNode.stringValue + ("<" + parameters[0].stringValue + ">"); var rename = templateNode.stringValue + ("_" + parameters[0].stringValue); var symbol = scope.parent.findNested(typeName, scope_1.ScopeHint.NORMAL, scope_1.FindNested.NORMAL); if (symbol) { // resolve(context, type.firstChild.firstChild, scope.parent); var genericSymbol = scope.parent.findNested(type.firstChild.firstChild.stringValue, scope_1.ScopeHint.NORMAL, scope_1.FindNested.NORMAL); type.firstChild.firstChild.symbol = genericSymbol; if (genericSymbol.resolvedType.pointerTo) { type.firstChild.firstChild.resolvedType = genericSymbol.resolvedType.pointerType(); } else { type.firstChild.firstChild.resolvedType = genericSymbol.resolvedType; } type.symbol = symbol; if (type.resolvedType.pointerTo) { type.resolvedType = symbol.resolvedType.pointerType(); } else { type.resolvedType = symbol.resolvedType; } return; } var node = templateNode.clone(); // node.parent = templateNode.parent; node.stringValue = typeName; cloneChildren(templateNode.firstChild.nextSibling, node, parameters, templateName, typeName); node.offset = null; //FIXME: we cannot take offset from class template node initialize(context, node, scope.parent, CheckMode.NORMAL); resolve(context, node, scope.parent); node.symbol.flags |= symbol_1.SYMBOL_FLAG_USED; node.constructorFunctionNode.symbol.flags |= symbol_1.SYMBOL_FLAG_USED; type.symbol = node.symbol; node.symbol.rename = rename; if (type.resolvedType.pointerTo) { type.resolvedType = node.symbol.resolvedType.pointerType(); } else { type.resolvedType = node.symbol.resolvedType; } if (templateNode.parent) { templateNode.replaceWith(node); } else { var prevNode = templateNode.derivedNodes[templateNode.derivedNodes.length - 1]; prevNode.parent.insertChildAfter(prevNode, node); } if (templateNode.derivedNodes === undefined) { templateNode.derivedNodes = []; } templateNode.derivedNodes.push(node); //Leave the parameter for the emitter to identify the type type.firstChild.firstChild.kind = node_1.NodeKind.NAME; resolve(context, type.firstChild.firstChild, scope.parent); type.stringValue = node.symbol.name; return; }
Derive a concrete class from class template type @param context @param type @param parameters @param scope @returns {Symbol}
deriveConcreteClass
javascript
01alchemist/TurboScript
lib/turboscript.js
https://github.com/01alchemist/TurboScript/blob/master/lib/turboscript.js
Apache-2.0
function TouchScroll(/*HTMLElement*/scrollElement, /*Object*/options){ options = options || {}; this.elastic = !!options.elastic, this.snapToGrid = !!options.snapToGrid; this.containerSize = null; this.maxSegments = {e: 1, f: 1}; this.currentSegment = {e: 0, f: 0}; // references to scroll div elements this.scrollers = { container: scrollElement, outer: /*HTMLElement*/null, inner: /*HTMLElement*/null, e: /*HTMLElement*/null, f: /*HTMLElement*/null }; // Whether the scroller scrolls this._scrolls = {e: false, f: false}; // The minimal scroll values (fully scrolled to the bottom/right) // Object with attributes "e" and "f" this._scrollMin = {e: false, f: false}; // References DOM nodes for scrollbar tracks and handles. // Gets set up by "_initDom" // { // container: HTMLElement, // handles:{e: HTMLElement, f: HTMLElement}, // maxOffsets: {e: Number, f: Number}, -> maximum offsets for the handles // offsetRatios: {e: Number, f: Number}, -> Ratio of scroller offset to handle offset // sizes: {e: Number, f: Number}, -> handle sizes // tracks: {e: HTMLElement, f: HTMLElement}, // } this._scrollbars = null, /* ---- SCROLLER STATE ---- */ this._isScrolling = false; this._startEvent = null; // the current scroller offset this._currentOffset = new WebKitCSSMatrix(); // Events tracked during a move action // [ {timeStamp: Number, matrix: WebKitCSSMatrix} ] // The last two events get tracked. this._trackedEvents = /*Array*/null; // Keeps track whether flicking is active this._flicking = {e: false, f: false}; // Queued bounces this._bounces = {e: null, f: null}; // Animation timeouts // This implementation uses timeouts for combined animations, // because the webkitTransitionEnd event fires late on iPhone 3G this._animationTimeouts = {e: [], f: []}; this._initDom(); this.setupScroller(); }
Constructor for scrollers. @constructor @param {HTMLElement} scrollElement The node to make scrollable @param {Object} [options] Options for the scroller- Known options are elastic {Boolean} whether the scroller bounces
TouchScroll
javascript
davidaurelio/TouchScroll
src/touchscroll.js
https://github.com/davidaurelio/TouchScroll/blob/master/src/touchscroll.js
BSD-2-Clause
async viteFinal(config) { // Merge custom configuration into the default config return mergeConfig(config, { assetsInclude: ['**/*.glb', '**/*.hdr', '**/*.glsl'], build: { assetsInlineLimit: 1024, }, }); }
@type { import('@storybook/react-vite').StorybookConfig }
viteFinal
javascript
HamishMW/portfolio
.storybook/main.js
https://github.com/HamishMW/portfolio/blob/master/.storybook/main.js
MIT
async function loadImageFromSrcSet({ src, srcSet, sizes }) { return new Promise((resolve, reject) => { try { if (!src && !srcSet) { throw new Error('No image src or srcSet provided'); } let tempImage = new Image(); if (src) { tempImage.src = src; } if (srcSet) { tempImage.srcset = srcSet; } if (sizes) { tempImage.sizes = sizes; } const onLoad = () => { tempImage.removeEventListener('load', onLoad); const source = tempImage.currentSrc; tempImage = null; resolve(source); }; tempImage.addEventListener('load', onLoad); } catch (error) { reject(`Error loading ${srcSet}: ${error}`); } }); }
Use the browser's image loading to load an image and grab the `src` it chooses from a `srcSet`
loadImageFromSrcSet
javascript
HamishMW/portfolio
app/utils/image.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/image.js
MIT
async function generateImage(width = 1, height = 1) { return new Promise(resolve => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); canvas.width = width; canvas.height = height; ctx.fillStyle = 'rgba(0, 0, 0, 0)'; ctx.fillRect(0, 0, width, height); canvas.toBlob(async blob => { if (!blob) throw new Error('Video thumbnail failed to load'); const image = URL.createObjectURL(blob); canvas.remove(); resolve(image); }); }); }
Generates a transparent png of a given width and height
generateImage
javascript
HamishMW/portfolio
app/utils/image.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/image.js
MIT
async function resolveSrcFromSrcSet({ srcSet, sizes }) { const sources = await Promise.all( srcSet.split(', ').map(async srcString => { const [src, width] = srcString.split(' '); const size = Number(width.replace('w', '')); const image = await generateImage(size); return { src, image, width }; }) ); const fakeSrcSet = sources.map(({ image, width }) => `${image} ${width}`).join(', '); const fakeSrc = await loadImageFromSrcSet({ srcSet: fakeSrcSet, sizes }); const output = sources.find(src => src.image === fakeSrc); return output.src; }
Use native html image `srcSet` resolution for non-html images
resolveSrcFromSrcSet
javascript
HamishMW/portfolio
app/utils/image.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/image.js
MIT
rgbToThreeColor = rgb => rgb?.split(' ').map(value => Number(value) / 255) || []
Convert an rgb theme property (e.g. rgbBlack: '0 0 0') to values that can be spread into a ThreeJS Color class
rgbToThreeColor
javascript
HamishMW/portfolio
app/utils/style.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/style.js
MIT
function cssProps(props, style = {}) { let result = {}; const keys = Object.keys(props); for (const key of keys) { let value = props[key]; if (typeof value === 'number' && key === 'delay') { value = numToMs(value); } if (typeof value === 'number' && key !== 'opacity') { value = numToPx(value); } if (typeof value === 'number' && key === 'opacity') { value = `${value * 100}%`; } result[`--${key}`] = value; } return { ...result, ...style }; }
Convert a JS object into `--` prefixed css custom properties. Optionally pass a second param for normal styles
cssProps
javascript
HamishMW/portfolio
app/utils/style.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/style.js
MIT
cleanScene = scene => { scene?.traverse(object => { if (!object.isMesh) return; object.geometry.dispose(); if (object.material.isMaterial) { cleanMaterial(object.material); } else { for (const material of object.material) { cleanMaterial(material); } } }); }
Clean up a scene's materials and geometry
cleanScene
javascript
HamishMW/portfolio
app/utils/three.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/three.js
MIT
cleanMaterial = material => { material.dispose(); for (const key of Object.keys(material)) { const value = material[key]; if (value && typeof value === 'object' && 'minFilter' in value) { value.dispose(); // Close GLTF bitmap textures value.source?.data?.close?.(); } } }
Clean up and dispose of a material
cleanMaterial
javascript
HamishMW/portfolio
app/utils/three.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/three.js
MIT
cleanRenderer = renderer => { renderer.dispose(); renderer = null; }
Clean up and dispose of a renderer
cleanRenderer
javascript
HamishMW/portfolio
app/utils/three.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/three.js
MIT
removeLights = lights => { for (const light of lights) { light.parent.remove(light); } }
Clean up lights by removing them from their parent
removeLights
javascript
HamishMW/portfolio
app/utils/three.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/three.js
MIT
function formatTimecode(time) { const hours = time / 1000 / 60 / 60; const h = Math.floor(hours); const m = Math.floor((hours - h) * 60); const s = Math.floor(((hours - h) * 60 - m) * 60); const c = Math.floor(((((hours - h) * 60 - m) * 60 - s) * 1000) / 10); return `${zeroPrefix(h)}:${zeroPrefix(m)}:${zeroPrefix(s)}:${zeroPrefix(c)}`; }
Format a timecode intro a hours:minutes:seconds:centiseconds string
formatTimecode
javascript
HamishMW/portfolio
app/utils/timecode.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/timecode.js
MIT
function zeroPrefix(value) { return value < 10 ? `0${value}` : `${value}`; }
Prefix a number with zero as a string if less than 10
zeroPrefix
javascript
HamishMW/portfolio
app/utils/timecode.js
https://github.com/HamishMW/portfolio/blob/master/app/utils/timecode.js
MIT
function parse (input, options = {}) { try { options = Object.assign({}, defaultAcornOptions, options) return parser.parse(input, options); } catch (e) { e.message = [ e.message, ' ' + input.split('\n')[e.loc.line - 1], ' ' + '^'.padStart(e.loc.column + 1) ].join('\n'); throw e; } }
@param {string} input @param {object} options @return {any}
parse
javascript
PepsRyuu/nollup
lib/impl/AcornParser.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/AcornParser.js
MIT
static async loadCJS(filepath, code) { // Once transpiled, we temporarily modify the require function // so that when it loads the config file, it will load the transpiled // version instead, and all of the require calls inside that will still work. let defaultLoader = require.extensions['.js']; require.extensions['.js'] = (module, filename) => { if (filename === filepath) { // @ts-ignore module._compile(code, filename); } else { defaultLoader(module, filename); } }; delete require.cache[filepath]; // Load the config file. If it uses ESM export, it will // be exported with a default key, so get that. Otherwise // if it was written in CJS, use the root instead. let config = require(filepath); config = config.default || config; require.extensions['.js'] = defaultLoader; return config; }
Uses compiler to compile rollup.config.js file. This allows config file to use ESM, but compiles to CJS so that import statements change to require statements. @param {string} filepath @param {string} code @return {Promise<object>}
loadCJS
javascript
PepsRyuu/nollup
lib/impl/ConfigLoader.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/ConfigLoader.js
MIT
static async loadESM(filepath, code) { let uri = `data:text/javascript;charset=utf-8,${encodeURIComponent(code)}`; return (await import(uri)).default; }
Directly imports rollup.config.mjs @param {string} filepath @param {string} code @return {Promise<object>}
loadESM
javascript
PepsRyuu/nollup
lib/impl/ConfigLoader.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/ConfigLoader.js
MIT
function blanker (input, start, end) { return input.substring(start, end).replace(/[^\n\r]/g, ' '); }
Setting imports to empty can cause source maps to break. This is because some imports could span across multiple lines when importing named exports. To bypass this problem, this function will replace all text except line breaks with spaces. This will preserve the lines so source maps function correctly. Source maps are ideally the better way to solve this, but trying to maintain performance. @param {string} input @param {number} start @param {number} end @return {string}
blanker
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
function getSyntheticExports (synthetic) { if (synthetic === true) { synthetic = 'default'; } return `if (__m__.exports.${synthetic}) { for (let prop in __m__.exports.${synthetic}) { prop !== '${synthetic}' && !__m__.exports.hasOwnProperty(prop) && __e__(prop, function () { return __m__.exports.${synthetic}[prop] }); } }` }
@param {boolean|string} synthetic @return {string}
getSyntheticExports
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
function createExternalImports (chunk, outputOptions, externalImports) { let output = ''; let { format, globals } = outputOptions; output += externalImports.map(ei => { let name = ei.source.replace(/[\W]/g, '_'); let { source, specifiers } = ei; // Bare external import if (specifiers.length === 0) { if (format === 'es') return `import '${source}';` if (format === 'cjs' || format === 'amd') return `require('${source}');` } let iifeName = format === 'iife'? (globals[source] || getIIFEName(ei)) : ''; return specifiers.map(s => { if (s.imported === '*') { if (format === 'es') return `import * as __nollup__external__${name}__ from '${source}';`; if (format === 'cjs' || format === 'amd') return `var __nollup__external__${name}__ = require('${source}');`; if (format === 'iife') return `var __nollup__external__${name}__ = self.${iifeName};` } if (s.imported === 'default') { if (format === 'es') return `import __nollup__external__${name}__default__ from '${source}';`; if (format === 'cjs' || format === 'amd') return `var __nollup__external__${name}__default__ = require('${source}').hasOwnProperty('default')? require('${source}').default : require('${source}');` if (format === 'iife') return `var __nollup__external__${name}__default__ = self.${iifeName} && self.${iifeName}.hasOwnProperty('default')? self.${iifeName}.default : self.${iifeName};` } if (format === 'es') return `import { ${s.imported} as __nollup__external__${name}__${s.imported}__ } from '${source}';`; if (format === 'cjs' || format === 'amd') return `var __nollup__external__${name}__${s.imported}__ = require('${source}').${s.imported};` if (format === 'iife') return `var __nollup__external__${name}__${s.imported}__ = self.${iifeName}.${s.imported};` }).join('\n'); }).join('\n'); return output; }
@param {RollupRenderedChunk} chunk @param {RollupOutputOptions} outputOptions @param {Array<NollupInternalModuleImport>} externalImports @return {string}
createExternalImports
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
function callNollupModuleWrap (plugins, code) { return plugins.filter(p => { return p.nollupModuleWrap }).reduce((code, p) => { return p.nollupModuleWrap(code) }, code); }
@param {NollupPlugin[]} plugins @param {string} code @return {string}
callNollupModuleWrap
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
onESMEnter (code, filePath, ast) { activeModules[filePath] = { output: new MagicString(code), code: code }; }
@param {string} code @param {string} filePath @param {ESTree} ast
onESMEnter
javascript
PepsRyuu/nollup
lib/impl/NollupCodeGenerator.js
https://github.com/PepsRyuu/nollup/blob/master/lib/impl/NollupCodeGenerator.js
MIT
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
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 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 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
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
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