code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
function getNode (input) { if (input.tagName) { return input; } else if (toString(input) === '[object String]') { return document.querySelector(input); } else if (input.length) { return input[0]; } return null; }
return a DOM Node matching variable input input might be a DOMElement, a DOMCollection or a string @param input @returns DOMElement
getNode ( input )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
function cssObjectToString (obj) { var res = []; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { res.push(prop + ': ' + obj[prop] + ';'); } } return res.join(''); }
serialize an object into a string of CSS to use for style.cssText @param {Object} obj @returns {String}
cssObjectToString ( obj )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
function attachSelfAsPlugin ($) { if (!$.fn || $.fn.seeThru) { return; } $.fn.seeThru = function () { var args = slice(arguments); var head = args.shift(); return this.each(function () { var self = this; var $this = $(this); if (args.length === 0) { if ($this.data('seeThru')) { return; } $this.data('seeThru', new SeeThru(this, head)._init()); } else if (toString(head) === '[object String]') { if (!$this.data('seeThru')) { return; } // all methods other then init will be deferred until `.ready()` $this.data('seeThru').ready(function () { $this.data('seeThru')[head].apply(self, args); if (head === 'revert') { $this.data('seeThru', null); } }); } }); }; }
make the script available as a plugin on the passed jQuery instance @param {jQuery} $
attachSelfAsPlugin ( $ )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
function Store () { var elements = []; this.push = function (el) { if (el) { elements.push(el); return el; } else { return null; } }; this.has = function (el) { return elements.some(function (video) { return video === el; }); }; this.remove = function (el) { elements = elements.filter(function (video) { return video !== el; }); }; }
@constructor Store simple wrapper around [] to keep track of video elements that are currently handled by the script
Store ( )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
this.startRendering = function () { drawFrame(true); return this; };
@method startRendering kick off the animation loop @returns self @API public
this.startRendering ( )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
this.stopRendering = function () { cancelAnimationFrame(interval); return this; };
@method stopRendering ends the animation loop @returns self @API public
this.stopRendering ( )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
this.teardown = function () { cancelAnimationFrame(interval); video.parentNode.removeChild(video.nextSibling); video.parentNode.removeChild(video.nextSibling); for (var key in initialStyles) { if (Object.prototype.hasOwnProperty.call(initialStyles, key)) { video.style[key] = initialStyles[key]; } } return this; };
@method stopRendering ends the animation loop, removes the canvas elements and unhides the video @returns self @API public
this.teardown ( )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
this.updateMask = function (node) { drawStaticMask(node); return this; };
@method updateMask draws a new image onto the alpha portion of the buffer @param {DOMElement} node @returns self @API public
this.updateMask ( node )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
this.getCanvas = function () { return displayCanvas; };
@method getCanvas gets the visible canvas element that is used for display @returns {DOMElement} @API public
this.getCanvas ( )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
this.getPoster = function () { return posterframe; };
@method getPoster gets the posterframe element @returns {DOMElement} @API public
this.getPoster ( )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
self._init = function () { function runInit () { function playSelfAndUnbind () { self._video.play(); if (self._options.poster) { self._seeThru.getPoster().removeEventListener('click', playSelfAndUnbind); } else { self._seeThru.getCanvas().removeEventListener('click', playSelfAndUnbind); } } if (elementStore.has(self._video)) { throw new Error('seeThru already initialized on passed video element!'); } self._seeThru = new TransparentVideo(self._video, self._options); // attach behavior for start options if (self._options.start === 'clicktoplay') { if (self._options.poster) { self._seeThru.getPoster().addEventListener('click', playSelfAndUnbind); } else { self._seeThru.getCanvas().addEventListener('click', playSelfAndUnbind); } } // attach behavior for end options if (self._options.end === 'rewind') { self._video.addEventListener('ended', function () { self._video.currentTime = 0; self._seeThru.getCanvas().addEventListener('click', playSelfAndUnbind); }); } else if (self._options.end !== 'stop') { self._video.addEventListener('ended', function () { self._video.currentTime = 0; self._video.play(); }); } // attach behavior for posterframe option if (self._options.poster && self._video.poster) { self._video.addEventListener('play', function () { self._seeThru.getPoster().style.display = 'none'; }); self._video.addEventListener('pause', function () { self._seeThru.getPoster().style.display = 'block'; }); } // some events that are registered on the canvas representation // will be echoed on the original video element so that pre-existing // event handlers bound to the video element will keep working // it is recommended to use `.getCanvas()` to bind new behavior though eventsToEcho.forEach(function (eventName) { self._seeThru.getCanvas().addEventListener(eventName, function () { var evt; if (canConstructEvents) { evt = new Event(eventName); } else { evt = document.createEvent('Event'); evt.initEvent(eventName, true, true); } self._video.dispatchEvent(evt); }); }); self._seeThru.startRendering(); ready = true; elementStore.push(self._video); callbacks.forEach(function (cb) { cb(self, self._video, self.getCanvas()); }); } if (self._video.readyState > 0) { runInit(); } else { self._video.addEventListener('loadedmetadata', runInit); } return self; };
@method init sets up transparent video once the video has metadata @returns self @API private
self._init ( )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
self.getCanvas = function () { return self._seeThru.getCanvas(); };
@method getCanvas returns the canvas element that is used for on-screen displaylay @returns {DOMElement} @API public
self.getCanvas ( )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
self.play = function () { self._video.play(); return self; };
@method play starts playback of the associated video element @returns self @API public
self.play ( )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
self.pause = function () { self._video.pause(); return self; };
@method pause halts playback of the associated video element @returns self @API public
self.pause ( )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
self.revert = function () { self._seeThru.teardown(); elementStore.remove(self._video); };
@method revert reverts the transparent video back to its original state @API public
self.revert ( )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
self.updateMask = function (mask) { self._seeThru.updateMask(getNode(mask)); return self; };
@method updateMask @param {String|DOMElement|DOMCollection} mask swaps the static mask currently used for sourcing alpha @returns self @API public
self.updateMask ( mask )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
self.ready = function (cb) { if (ready) { setTimeout(function () { cb(self, self._video, self.getCanvas()); }, 0); } else { callbacks.push(cb); } return self; };
@method ready @param {Function} cb defers the passed callback until the associated video element has metadata passes itself as the 1st argument of the callback @returns self @API public
self.ready ( cb )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
function SeeThru (DOMNode, options) { var self = this; var ready = false; var callbacks = []; var defaultOptions = { start: 'external', // 'clicktoplay' or 'external' defaults to external end: 'stop', // 'loop', 'rewind', 'stop' any other input will default to 'stop' mask: false, // this lets you define a <img> (selected by #id or .class - class will use the first occurence)used as a black and white mask instead of adding the alpha to the video alphaMask: false, // defines if the used `mask` uses black and white or alpha information - defaults to false, i.e. black and white width: null, // lets you specify a pixel value used as width -- overrides all other calculations height: null, // lets you specify a pixel value used as height -- overrides all other calculations poster: false, // the plugin will display the image set in the video's poster-attribute when not playing if set to true unmult: false, // set this to true if your video material is premultiplied on black - might cause performance issues videoStyles: { display: 'none' }, // this is the CSS that is used to hide the original video - can be updated in order to work around autoplay restrictions namespace: 'seeThru' // this will be used for prefixing the CSS classnames applied to the created elements }; options = options || {}; self._video = getNode(DOMNode); if (!self._video || self._video.tagName !== 'VIDEO') throw new Error('Could not use specified source'); self._options = (function (options) { for (var key in defaultOptions) { if (defaultOptions.hasOwnProperty(key)) { if (!(key in options)) { options[key] = defaultOptions[key]; } } } return options; })(options); /** * @method init * sets up transparent video once the video has metadata * @returns self * @API private */ self._init = function () { function runInit () { function playSelfAndUnbind () { self._video.play(); if (self._options.poster) { self._seeThru.getPoster().removeEventListener('click', playSelfAndUnbind); } else { self._seeThru.getCanvas().removeEventListener('click', playSelfAndUnbind); } } if (elementStore.has(self._video)) { throw new Error('seeThru already initialized on passed video element!'); } self._seeThru = new TransparentVideo(self._video, self._options); // attach behavior for start options if (self._options.start === 'clicktoplay') { if (self._options.poster) { self._seeThru.getPoster().addEventListener('click', playSelfAndUnbind); } else { self._seeThru.getCanvas().addEventListener('click', playSelfAndUnbind); } } // attach behavior for end options if (self._options.end === 'rewind') { self._video.addEventListener('ended', function () { self._video.currentTime = 0; self._seeThru.getCanvas().addEventListener('click', playSelfAndUnbind); }); } else if (self._options.end !== 'stop') { self._video.addEventListener('ended', function () { self._video.currentTime = 0; self._video.play(); }); } // attach behavior for posterframe option if (self._options.poster && self._video.poster) { self._video.addEventListener('play', function () { self._seeThru.getPoster().style.display = 'none'; }); self._video.addEventListener('pause', function () { self._seeThru.getPoster().style.display = 'block'; }); } // some events that are registered on the canvas representation // will be echoed on the original video element so that pre-existing // event handlers bound to the video element will keep working // it is recommended to use `.getCanvas()` to bind new behavior though eventsToEcho.forEach(function (eventName) { self._seeThru.getCanvas().addEventListener(eventName, function () { var evt; if (canConstructEvents) { evt = new Event(eventName); } else { evt = document.createEvent('Event'); evt.initEvent(eventName, true, true); } self._video.dispatchEvent(evt); }); }); self._seeThru.startRendering(); ready = true; elementStore.push(self._video); callbacks.forEach(function (cb) { cb(self, self._video, self.getCanvas()); }); } if (self._video.readyState > 0) { runInit(); } else { self._video.addEventListener('loadedmetadata', runInit); } return self; }; /** * @method getCanvas * returns the canvas element that is used for on-screen displaylay * @returns {DOMElement} * @API public */ self.getCanvas = function () { return self._seeThru.getCanvas(); }; /** * @method play * starts playback of the associated video element * @returns self * @API public */ self.play = function () { self._video.play(); return self; }; /** * @method pause * halts playback of the associated video element * @returns self * @API public */ self.pause = function () { self._video.pause(); return self; }; /** * @method revert * reverts the transparent video back to its original state * @API public */ self.revert = function () { self._seeThru.teardown(); elementStore.remove(self._video); }; /** * @method updateMask * @param {String|DOMElement|DOMCollection} mask * swaps the static mask currently used for sourcing alpha * @returns self * @API public */ self.updateMask = function (mask) { self._seeThru.updateMask(getNode(mask)); return self; }; /** * @method ready * @param {Function} cb * defers the passed callback until the associated video element has metadata * passes itself as the 1st argument of the callback * @returns self * @API public */ self.ready = function (cb) { if (ready) { setTimeout(function () { cb(self, self._video, self.getCanvas()); }, 0); } else { callbacks.push(cb); } return self; }; }
@constructor SeeThru handles a video element turned into a transparent mock version of itself @param {String|DOMElement|DOMNode} DOMNode @param {Object} [options]
SeeThru ( DOMNode , options )
javascript
m90/seeThru
src/seeThru.js
https://github.com/m90/seeThru/blob/master/src/seeThru.js
MIT
async function vad(buffer) { const input = new Tensor("float32", buffer, [1, buffer.length]); const { stateN, output } = await (inferenceChain = inferenceChain.then((_) => silero_vad({ input, sr, state }), )); state = stateN; // Update state const isSpeech = output.data[0]; // Use heuristics to determine if the buffer is speech or not return ( // Case 1: We are above the threshold (definitely speech) isSpeech > SPEECH_THRESHOLD || // Case 2: We are in the process of recording, and the probability is above the negative (exit) threshold (isRecording && isSpeech >= EXIT_THRESHOLD) ); }
Perform Voice Activity Detection (VAD) @param {Float32Array} buffer The new audio buffer @returns {Promise<boolean>} `true` if the buffer is speech, `false` otherwise.
vad ( buffer )
javascript
huggingface/transformers.js-examples
moonshine-web/src/worker.js
https://github.com/huggingface/transformers.js-examples/blob/master/moonshine-web/src/worker.js
Apache-2.0
const transcribe = async (buffer, data) => { const { text } = await (inferenceChain = inferenceChain.then((_) => transcriber(buffer), )); self.postMessage({ type: "output", buffer, message: text, ...data }); };
Transcribe the audio buffer @param {Float32Array} buffer The audio buffer @param {Object} data Additional data
transcribe
javascript
huggingface/transformers.js-examples
moonshine-web/src/worker.js
https://github.com/huggingface/transformers.js-examples/blob/master/moonshine-web/src/worker.js
Apache-2.0
constructor(model, processor, tokenizer) { this.model = model; this.processor = processor; this.tokenizer = tokenizer; // Prepare text inputs this.task = "<CAPTION>"; const prompts = processor.construct_prompts(this.task); this.text_inputs = tokenizer(prompts); }
Create a new Caption model. @param {import('@huggingface/transformers').PreTrainedModel} model The model to use for captioning @param {import('@huggingface/transformers').Processor} processor The processor to use for captioning @param {import('@huggingface/transformers').PreTrainedTokenizer} tokenizer The tokenizer to use for captioning
constructor ( model , processor , tokenizer )
javascript
huggingface/transformers.js-examples
omniparser-node/captioning.js
https://github.com/huggingface/transformers.js-examples/blob/master/omniparser-node/captioning.js
Apache-2.0
async describe(image) { const vision_inputs = await this.processor(image); // Generate text const generated_ids = await this.model.generate({ ...this.text_inputs, ...vision_inputs, max_new_tokens: 256, }); // Decode generated text const generated_text = this.tokenizer.batch_decode(generated_ids, { skip_special_tokens: false, })[0]; // Post-process the generated text const result = this.processor.post_process_generation( generated_text, this.task, image.size, ); return result[this.task]; }
Generate a caption for an image. @param {import('@huggingface/transformers').RawImage} image The input image. @returns {Promise<string>} The caption for the image
describe ( image )
javascript
huggingface/transformers.js-examples
omniparser-node/captioning.js
https://github.com/huggingface/transformers.js-examples/blob/master/omniparser-node/captioning.js
Apache-2.0
function iou(a, b) { const x1 = Math.max(a.x1, b.x1); const y1 = Math.max(a.y1, b.y1); const x2 = Math.min(a.x2, b.x2); const y2 = Math.min(a.y2, b.y2); const intersection = Math.max(0, x2 - x1) * Math.max(0, y2 - y1); const area1 = (a.x2 - a.x1) * (a.y2 - a.y1); const area2 = (b.x2 - b.x1) * (b.y2 - b.y1); const union = area1 + area2 - intersection; return intersection / union; }
Compute Intersection over Union (IoU) between two detections. @param {Detection} a The first detection. @param {Detection} b The second detection.
iou ( a , b )
javascript
huggingface/transformers.js-examples
omniparser-node/detector.js
https://github.com/huggingface/transformers.js-examples/blob/master/omniparser-node/detector.js
Apache-2.0
constructor(model, processor) { this.model = model; this.processor = processor; }
Create a new YOLOv8 detector. @param {import('@huggingface/transformers').PreTrainedModel} model The model to use for detection @param {import('@huggingface/transformers').Processor} processor The processor to use for detection
constructor ( model , processor )
javascript
huggingface/transformers.js-examples
omniparser-node/detector.js
https://github.com/huggingface/transformers.js-examples/blob/master/omniparser-node/detector.js
Apache-2.0
async predict( input, { confidence_threshold = 0.25, iou_threshold = 0.7 } = {}, ) { const image = await RawImage.read(input); const { pixel_values } = await this.processor(image); // Run detection const { output0 } = await this.model({ images: pixel_values }); // Post-process output const permuted = output0[0].transpose(1, 0); // `permuted` is a Tensor of shape [ 5460, 5 ]: // - 5460 potential bounding boxes // - 5 parameters for each box: // - first 4 are coordinates for the bounding boxes (x-center, y-center, width, height) // - the last one is the confidence score // Format output const result = []; const [scaledHeight, scaledWidth] = pixel_values.dims.slice(-2); for (const [xc, yc, w, h, score] of permuted.tolist()) { // Filter if not confident enough if (score < confidence_threshold) continue; // Get pixel values, taking into account the original image size const x1 = ((xc - w / 2) / scaledWidth) * image.width; const y1 = ((yc - h / 2) / scaledHeight) * image.height; const x2 = ((xc + w / 2) / scaledWidth) * image.width; const y2 = ((yc + h / 2) / scaledHeight) * image.height; // Add to result result.push({ x1, x2, y1, y2, score }); } return nms(result, iou_threshold); }
Run detection on an image. @param {RawImage|string|URL} input The input image. @param {Object} [options] The options for detection. @param {number} [options.confidence_threshold=0.25] The confidence threshold. @param {number} [options.iou_threshold=0.7] The IoU threshold for NMS. @returns {Promise<Detection[]>} The list of detections
predict ( input , { confidence_threshold = 0 . 25 , iou_threshold = 0 . 7 } = { } , )
javascript
huggingface/transformers.js-examples
omniparser-node/detector.js
https://github.com/huggingface/transformers.js-examples/blob/master/omniparser-node/detector.js
Apache-2.0
export function nms(detections, iouThreshold) { const result = []; while (detections.length > 0) { const best = detections.reduce((acc, detection) => detection.score > acc.score ? detection : acc, ); result.push(best); detections = detections.filter( (detection) => iou(detection, best) < iouThreshold, ); } return result; } export class Detector { /** * Create a new YOLOv8 detector. * @param {import('@huggingface/transformers').PreTrainedModel} model The model to use for detection * @param {import('@huggingface/transformers').Processor} processor The processor to use for detection */ constructor(model, processor) { this.model = model; this.processor = processor; } /** * Run detection on an image. * @param {RawImage|string|URL} input The input image. * @param {Object} [options] The options for detection. * @param {number} [options.confidence_threshold=0.25] The confidence threshold. * @param {number} [options.iou_threshold=0.7] The IoU threshold for NMS. * @returns {Promise<Detection[]>} The list of detections */ async predict( input, { confidence_threshold = 0.25, iou_threshold = 0.7 } = {}, ) { const image = await RawImage.read(input); const { pixel_values } = await this.processor(image); // Run detection const { output0 } = await this.model({ images: pixel_values }); // Post-process output const permuted = output0[0].transpose(1, 0); // `permuted` is a Tensor of shape [ 5460, 5 ]: // - 5460 potential bounding boxes // - 5 parameters for each box: // - first 4 are coordinates for the bounding boxes (x-center, y-center, width, height) // - the last one is the confidence score // Format output const result = []; const [scaledHeight, scaledWidth] = pixel_values.dims.slice(-2); for (const [xc, yc, w, h, score] of permuted.tolist()) { // Filter if not confident enough if (score < confidence_threshold) continue; // Get pixel values, taking into account the original image size const x1 = ((xc - w / 2) / scaledWidth) * image.width; const y1 = ((yc - h / 2) / scaledHeight) * image.height; const x2 = ((xc + w / 2) / scaledWidth) * image.width; const y2 = ((yc + h / 2) / scaledHeight) * image.height; // Add to result result.push({ x1, x2, y1, y2, score }); } return nms(result, iou_threshold); } static async from_pretrained(model_id) { const model = await AutoModel.from_pretrained(model_id, { dtype: "fp32" }); const processor = await AutoProcessor.from_pretrained(model_id); return new Detector(model, processor); } }
Run Non-Maximum Suppression (NMS) on a list of detections. @param {Detection[]} detections The list of detections. @param {number} iouThreshold The IoU threshold for NMS.
nms ( detections , iouThreshold )
javascript
huggingface/transformers.js-examples
omniparser-node/detector.js
https://github.com/huggingface/transformers.js-examples/blob/master/omniparser-node/detector.js
Apache-2.0
function makeMap(str, expectsLowerCase) { const map = Object.create(null); const list = str.split(','); for (let i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val]; }
Make a map and return a function for checking if a key is in that map. IMPORTANT: all calls of this function must be prefixed with \/\*#\_\_PURE\_\_\*\/ So that rollup can tree-shake them if necessary.
makeMap ( str , expectsLowerCase )
javascript
byebyehair/minichat
static/vue.global.js
https://github.com/byebyehair/minichat/blob/master/static/vue.global.js
MIT
function includeBooleanAttr(value) { return !!value || value === ''; }
Boolean attributes should be included if the value is truthy or ''. e.g. `<select multiple>` compiles to `{ multiple: '' }`
includeBooleanAttr ( value )
javascript
byebyehair/minichat
static/vue.global.js
https://github.com/byebyehair/minichat/blob/master/static/vue.global.js
MIT
const toDisplayString = (val) => { return isString(val) ? val : val == null ? '' : isArray(val) || (isObject(val) && (val.toString === objectToString || !isFunction(val.toString))) ? JSON.stringify(val, replacer, 2) : String(val); };
For converting {{ interpolation }} values to displayed strings. @private
toDisplayString
javascript
byebyehair/minichat
static/vue.global.js
https://github.com/byebyehair/minichat/blob/master/static/vue.global.js
MIT
const looseToNumber = (val) => { const n = parseFloat(val); return isNaN(n) ? val : n; };
"123-foo" will be parsed to 123 This is used for the .number modifier in v-model
looseToNumber
javascript
byebyehair/minichat
static/vue.global.js
https://github.com/byebyehair/minichat/blob/master/static/vue.global.js
MIT
const toNumber = (val) => { const n = isString(val) ? Number(val) : NaN; return isNaN(n) ? val : n; };
Only conerces number-like strings "123-foo" will be returned as-is
toNumber
javascript
byebyehair/minichat
static/vue.global.js
https://github.com/byebyehair/minichat/blob/master/static/vue.global.js
MIT
function shallowReactive(target) { return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap); }
Return a shallowly-reactive copy of the original object, where only the root level properties are reactive. It also does not auto-unwrap refs (even at the root level).
shallowReactive ( target )
javascript
byebyehair/minichat
static/vue.global.js
https://github.com/byebyehair/minichat/blob/master/static/vue.global.js
MIT
function readonly(target) { return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap); }
Creates a readonly copy of the original object. Note the returned copy is not made reactive, but `readonly` can be called on an already reactive object.
readonly ( target )
javascript
byebyehair/minichat
static/vue.global.js
https://github.com/byebyehair/minichat/blob/master/static/vue.global.js
MIT
function shallowReadonly(target) { return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap); }
Returns a reactive-copy of the original object, where only the root level properties are readonly, and does NOT unwrap refs nor recursively convert returned properties. This is used for creating the props proxy object for stateful components.
shallowReadonly ( target )
javascript
byebyehair/minichat
static/vue.global.js
https://github.com/byebyehair/minichat/blob/master/static/vue.global.js
MIT
function setCurrentRenderingInstance(instance) { const prev = currentRenderingInstance; currentRenderingInstance = instance; currentScopeId = (instance && instance.type.__scopeId) || null; return prev; }
Note: rendering calls maybe nested. The function returns the parent rendering instance if present, which should be restored after the render is done: ```js const prev = setCurrentRenderingInstance(i) // ...render setCurrentRenderingInstance(prev) ```
setCurrentRenderingInstance ( instance )
javascript
byebyehair/minichat
static/vue.global.js
https://github.com/byebyehair/minichat/blob/master/static/vue.global.js
MIT
function pushScopeId(id) { currentScopeId = id; }
Set scope id when creating hoisted vnodes. @private compiler helper
pushScopeId ( id )
javascript
byebyehair/minichat
static/vue.global.js
https://github.com/byebyehair/minichat/blob/master/static/vue.global.js
MIT
function popScopeId() { currentScopeId = null; }
Technically we no longer need this after 3.0.8 but we need to keep the same API for backwards compat w/ code generated by compilers. @private
popScopeId ( )
javascript
byebyehair/minichat
static/vue.global.js
https://github.com/byebyehair/minichat/blob/master/static/vue.global.js
MIT
function setupNLS() { if (!setupNLSResult) { setupNLSResult = doSetupNLS(); } return setupNLSResult; }
@returns {Promise<INLSConfiguration | undefined>}
setupNLS ( )
javascript
drcika/apc-extension
resources/bootstrap-amd.js
https://github.com/drcika/apc-extension/blob/master/resources/bootstrap-amd.js
MIT
module.exports.load = function (entrypoint, onLoad, onError) { if (!entrypoint) { return; } entrypoint = `./${entrypoint}.js`; onLoad = onLoad || function () { }; onError = onError || function (err) { console.error(err); }; setupNLS().then(() => { performance.mark(`code/fork/willLoadCode`); import(entrypoint).then(onLoad, onError); }); };
@param {string=} entrypoint @param {(value: any) => void} [onLoad] @param {(err: Error) => void} [onError]
module.exports.load ( entrypoint , onLoad , onError )
javascript
drcika/apc-extension
resources/bootstrap-amd.js
https://github.com/drcika/apc-extension/blob/master/resources/bootstrap-amd.js
MIT
function _definePolyfillMarks(timeOrigin) { const _data = []; if (typeof timeOrigin === 'number') { _data.push('code/timeOrigin', timeOrigin); } function mark(name) { _data.push(name, Date.now()); } function getMarks() { const result = []; for (let i = 0; i < _data.length; i += 2) { result.push({ name: _data[i], startTime: _data[i + 1], }); } return result; } return { mark, getMarks }; }
@returns {{mark(name:string):void, getMarks():{name:string, startTime:number}[]}}
_definePolyfillMarks ( timeOrigin )
javascript
drcika/apc-extension
resources/performance.js
https://github.com/drcika/apc-extension/blob/master/resources/performance.js
MIT
const renderWrapper = (WrappedComponent) => { function SizeMeRenderer(props) { const { explicitRef, className, style, size, disablePlaceholder, onSize, ...restProps } = props const noSizeData = size == null || (size.width == null && size.height == null) const renderPlaceholder = noSizeData && !disablePlaceholder const renderProps = { className, style, } if (size != null) { renderProps.size = size } const toRender = renderPlaceholder ? ( <Placeholder className={className} style={style} /> ) : ( <WrappedComponent {...renderProps} {...restProps} /> ) return <ReferenceWrapper ref={explicitRef}>{toRender}</ReferenceWrapper> } SizeMeRenderer.displayName = `SizeMeRenderer(${getDisplayName( WrappedComponent, )})` return SizeMeRenderer }
As we need to maintain a ref on the root node that is rendered within our SizeMe component we need to wrap our entire render in a sub component. Without this, we lose the DOM ref after the placeholder is removed from the render and the actual component is rendered. It took me forever to figure this out, so tread extra careful on this one!
renderWrapper
javascript
ctrlplusb/react-sizeme
src/with-size.js
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
MIT
export default function BpmnModdle(packages, options) { Moddle.call(this, packages, options); }
A sub class of {@link Moddle} with support for import and export of BPMN 2.0 xml files. @class BpmnModdle @extends Moddle @param {Object|Array} packages to use for instantiating the model @param {Object} [options] additional options to pass over
BpmnModdle ( packages , options )
javascript
bpmn-io/bpmn-moddle
lib/bpmn-moddle.js
https://github.com/bpmn-io/bpmn-moddle/blob/master/lib/bpmn-moddle.js
MIT
BpmnModdle.prototype.fromXML = function(xmlStr, typeName, options) { if (!isString(typeName)) { options = typeName; typeName = 'bpmn:Definitions'; } var reader = new Reader(assign({ model: this, lax: true }, options)); var rootHandler = reader.handler(typeName); return reader.fromXML(xmlStr, rootHandler); };
Instantiates a BPMN model tree from a given xml string. @param {String} xmlStr @param {String} [typeName='bpmn:Definitions'] name of the root element @param {Object} [options] options to pass to the underlying reader @returns {Promise<ParseResult, ParseError>}
BpmnModdle.prototype.fromXML ( xmlStr , typeName , options )
javascript
bpmn-io/bpmn-moddle
lib/bpmn-moddle.js
https://github.com/bpmn-io/bpmn-moddle/blob/master/lib/bpmn-moddle.js
MIT
BpmnModdle.prototype.toXML = function(element, options) { var writer = new Writer(options); return new Promise(function(resolve, reject) { try { var result = writer.toXML(element); return resolve({ xml: result }); } catch (err) { return reject(err); } }); };
Serializes a BPMN 2.0 object tree to XML. @param {String} element the root element, typically an instance of `bpmn:Definitions` @param {Object} [options] to pass to the underlying writer @returns {Promise<SerializationResult, Error>}
BpmnModdle.prototype.toXML ( element , options )
javascript
bpmn-io/bpmn-moddle
lib/bpmn-moddle.js
https://github.com/bpmn-io/bpmn-moddle/blob/master/lib/bpmn-moddle.js
MIT
function initWPSSocket(messageHandler) { /** * The hard-coded options injection key from webpack-plugin-serve. * * [Ref](https://github.com/shellscape/webpack-plugin-serve/blob/aeb49f14e900802c98df4a4607a76bc67b1cffdf/lib/index.js#L258) * @type {Object | undefined} */ let options; try { options = ʎɐɹɔosǝʌɹǝs; } catch (e) { // Bail out because this indicates the plugin is not included return; } const { address, client = {}, secure } = options; const protocol = secure ? 'wss' : 'ws'; const socket = new ClientSocket(client, protocol + '://' + (client.address || address) + '/wps'); socket.addEventListener('message', function listener(message) { const { action, data } = JSON.parse(message.data); switch (action) { case 'done': { messageHandler({ type: 'ok' }); break; } case 'problems': { if (data.errors.length) { messageHandler({ type: 'errors', data: data.errors }); } else if (data.warnings.length) { messageHandler({ type: 'warnings', data: data.warnings }); } break; } default: { // Do nothing } } }); }
Initializes a socket server for HMR for webpack-plugin-serve. @param {function(*): void} messageHandler A handler to consume Webpack compilation messages. @returns {void}
initWPSSocket ( messageHandler )
javascript
pmmmwh/react-refresh-webpack-plugin
sockets/WPSSocket.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/sockets/WPSSocket.js
MIT
function initWHMEventSource(messageHandler) { const client = window[singletonKey]; client.useCustomOverlay({ showProblems: function showProblems(type, data) { const error = { data: data, type: type, }; messageHandler(error); }, clear: function clear() { messageHandler({ type: 'ok' }); }, }); }
Initializes a socket server for HMR for webpack-hot-middleware. @param {function(*): void} messageHandler A handler to consume Webpack compilation messages. @returns {void}
initWHMEventSource ( messageHandler )
javascript
pmmmwh/react-refresh-webpack-plugin
sockets/WHMEventSource.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/sockets/WHMEventSource.js
MIT
function initWDSSocket(messageHandler, resourceQuery) { if (typeof __webpack_dev_server_client__ !== 'undefined') { let SocketClient = __webpack_dev_server_client__; if (typeof __webpack_dev_server_client__.default !== 'undefined') { SocketClient = __webpack_dev_server_client__.default; } const wdsMeta = getWDSMetadata(SocketClient); const urlParts = getSocketUrlParts(resourceQuery, wdsMeta); const connection = new SocketClient(getUrlFromParts(urlParts, wdsMeta)); connection.onMessage(function onSocketMessage(data) { const message = JSON.parse(data); messageHandler(message); }); } }
Initializes a socket server for HMR for webpack-dev-server. @param {function(*): void} messageHandler A handler to consume Webpack compilation messages. @param {string} [resourceQuery] Webpack's `__resourceQuery` string. @returns {void}
initWDSSocket ( messageHandler , resourceQuery )
javascript
pmmmwh/react-refresh-webpack-plugin
sockets/WDSSocket.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/sockets/WDSSocket.js
MIT
function getSocketUrlParts(resourceQuery, metadata) { if (typeof metadata === 'undefined') { metadata = {}; } /** @type {SocketUrlParts} */ let urlParts = {}; // If the resource query is available, // parse it and ignore everything we received from the script host. if (resourceQuery) { const parsedQuery = {}; const searchParams = new URLSearchParams(resourceQuery.slice(1)); searchParams.forEach(function (value, key) { parsedQuery[key] = value; }); urlParts.hostname = parsedQuery.sockHost; urlParts.pathname = parsedQuery.sockPath; urlParts.port = parsedQuery.sockPort; // Make sure the protocol from resource query has a trailing colon if (parsedQuery.sockProtocol) { urlParts.protocol = parsedQuery.sockProtocol + ':'; } } else { const scriptSource = getCurrentScriptSource(); let url = {}; try { // The placeholder `baseURL` with `window.location.href`, // is to allow parsing of path-relative or protocol-relative URLs, // and will have no effect if `scriptSource` is a fully valid URL. url = new URL(scriptSource, window.location.href); } catch (e) { // URL parsing failed, do nothing. // We will still proceed to see if we can recover using `resourceQuery` } // Parse authentication credentials in case we need them if (url.username) { // Since HTTP basic authentication does not allow empty username, // we only include password if the username is not empty. // Result: <username> or <username>:<password> urlParts.auth = url.username; if (url.password) { urlParts.auth += ':' + url.password; } } // `file://` URLs has `'null'` origin if (url.origin !== 'null') { urlParts.hostname = url.hostname; } urlParts.protocol = url.protocol; urlParts.port = url.port; } if (!urlParts.pathname) { if (metadata.version === 4) { // This is hard-coded in WDS v4 urlParts.pathname = '/ws'; } else { // This is hard-coded in WDS v3 urlParts.pathname = '/sockjs-node'; } } // Check for IPv4 and IPv6 host addresses that correspond to any/empty. // This is important because `hostname` can be empty for some hosts, // such as 'about:blank' or 'file://' URLs. const isEmptyHostname = urlParts.hostname === '0.0.0.0' || urlParts.hostname === '[::]' || !urlParts.hostname; // We only re-assign the hostname if it is empty, // and if we are using HTTP/HTTPS protocols. if ( isEmptyHostname && window.location.hostname && window.location.protocol.indexOf('http') === 0 ) { urlParts.hostname = window.location.hostname; } // We only re-assign `protocol` when `protocol` is unavailable, // or if `hostname` is available and is empty, // since otherwise we risk creating an invalid URL. // We also do this when no sockProtocol was passed to the config and 'https' is used, // as it mandates the use of secure sockets. if ( !urlParts.protocol || (urlParts.hostname && (isEmptyHostname || (!resourceQuery && window.location.protocol === 'https:'))) ) { urlParts.protocol = window.location.protocol; } // We only re-assign port when it is not available if (!urlParts.port) { urlParts.port = window.location.port; } if (!urlParts.hostname || !urlParts.pathname) { throw new Error( [ '[React Refresh] Failed to get an URL for the socket connection.', "This usually means that the current executed script doesn't have a `src` attribute set.", 'You should either specify the socket path parameters under the `devServer` key in your Webpack config, or use the `overlay` option.', 'https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/main/docs/API.md#overlay', ].join('\n') ); } return { auth: urlParts.auth, hostname: urlParts.hostname, pathname: urlParts.pathname, protocol: urlParts.protocol, port: urlParts.port || undefined, }; }
Parse current location and Webpack's `__resourceQuery` into parts that can create a valid socket URL. @param {string} [resourceQuery] The Webpack `__resourceQuery` string. @param {import('./getWDSMetadata').WDSMetaObj} [metadata] The parsed WDS metadata object. @returns {SocketUrlParts} The parsed URL parts. @see https://webpack.js.org/api/module-variables/#__resourcequery-webpack-specific
getSocketUrlParts ( resourceQuery , metadata )
javascript
pmmmwh/react-refresh-webpack-plugin
sockets/utils/getSocketUrlParts.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/sockets/utils/getSocketUrlParts.js
MIT
function getWDSMetadata(SocketClient) { let enforceWs = false; if ( typeof SocketClient.name !== 'undefined' && SocketClient.name !== null && SocketClient.name.toLowerCase().includes('websocket') ) { enforceWs = true; } let version; // WDS versions <=3.5.0 if (!('onMessage' in SocketClient.prototype)) { version = 3; } else { // WDS versions >=3.5.0 <4 if ( 'getClientPath' in SocketClient || Object.getPrototypeOf(SocketClient).name === 'BaseClient' ) { version = 3; } else { version = 4; } } return { enforceWs: enforceWs, version: version, }; }
Derives WDS metadata from a compatible socket client. @param {Function} SocketClient A WDS socket client (SockJS/WebSocket). @returns {WDSMetaObj} The parsed WDS metadata object.
getWDSMetadata ( SocketClient )
javascript
pmmmwh/react-refresh-webpack-plugin
sockets/utils/getWDSMetadata.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/sockets/utils/getWDSMetadata.js
MIT
function urlFromParts(urlParts, metadata) { if (typeof metadata === 'undefined') { metadata = {}; } let fullProtocol = 'http:'; if (urlParts.protocol) { fullProtocol = urlParts.protocol; } if (metadata.enforceWs) { fullProtocol = fullProtocol.replace(/^(?:http|.+-extension|file)/i, 'ws'); } fullProtocol = fullProtocol + '//'; let fullHost = urlParts.hostname; if (urlParts.auth) { const fullAuth = urlParts.auth.split(':').map(encodeURIComponent).join(':') + '@'; fullHost = fullAuth + fullHost; } if (urlParts.port) { fullHost = fullHost + ':' + urlParts.port; } const url = new URL(urlParts.pathname, fullProtocol + fullHost); return url.href; }
Create a valid URL from parsed URL parts. @param {import('./getSocketUrlParts').SocketUrlParts} urlParts The parsed URL parts. @param {import('./getWDSMetadata').WDSMetaObj} [metadata] The parsed WDS metadata object. @returns {string} The generated URL.
urlFromParts ( urlParts , metadata )
javascript
pmmmwh/react-refresh-webpack-plugin
sockets/utils/getUrlFromParts.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/sockets/utils/getUrlFromParts.js
MIT
function getCurrentScriptSource() { // `document.currentScript` is the most accurate way to get the current running script, // but is not supported in all browsers (most notably, IE). if ('currentScript' in document) { // In some cases, `document.currentScript` would be `null` even if the browser supports it: // e.g. asynchronous chunks on Firefox. // We should not fallback to the list-approach as it would not be safe. if (document.currentScript == null) return; return document.currentScript.getAttribute('src'); } // Fallback to getting all scripts running in the document, // and finding the last one injected. else { const scriptElementsWithSrc = Array.prototype.filter.call( document.scripts || [], function (elem) { return elem.getAttribute('src'); } ); if (!scriptElementsWithSrc.length) return; const currentScript = scriptElementsWithSrc[scriptElementsWithSrc.length - 1]; return currentScript.getAttribute('src'); } }
Gets the source (i.e. host) of the script currently running. @returns {string}
getCurrentScriptSource ( )
javascript
pmmmwh/react-refresh-webpack-plugin
sockets/utils/getCurrentScriptSource.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/sockets/utils/getCurrentScriptSource.js
MIT
function debounce(fn, wait) { /** * A cached setTimeout handler. * @type {number | undefined} */ let timer; /** * @returns {void} */ function debounced() { const context = this; const args = arguments; clearTimeout(timer); timer = setTimeout(function () { return fn.apply(context, args); }, wait); } return debounced; }
Debounce a function to delay invoking until wait (ms) have elapsed since the last invocation. @param {function(...*): *} fn The function to be debounced. @param {number} wait Milliseconds to wait before invoking again. @return {function(...*): void} The debounced function.
debounce ( fn , wait )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/utils.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/utils.js
MIT
function removeAllChildren(element, skip) { /** @type {Node[]} */ const childList = Array.prototype.slice.call( element.childNodes, typeof skip !== 'undefined' ? skip : 0 ); for (let i = 0; i < childList.length; i += 1) { element.removeChild(childList[i]); } } module.exports = { debounce: debounce, formatFilename: formatFilename, removeAllChildren: removeAllChildren, };
Remove all children of an element. @param {HTMLElement} element A valid HTML element. @param {number} [skip] Number of elements to skip removing. @returns {void}
removeAllChildren ( element , skip )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/utils.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/utils.js
MIT
function IframeRoot(document, root, props) { const iframe = document.createElement('iframe'); iframe.id = 'react-refresh-overlay'; iframe.src = 'about:blank'; iframe.style.border = 'none'; iframe.style.height = '100%'; iframe.style.left = '0'; iframe.style.minHeight = '100vh'; iframe.style.minHeight = '-webkit-fill-available'; iframe.style.position = 'fixed'; iframe.style.top = '0'; iframe.style.width = '100vw'; iframe.style.zIndex = '2147483647'; iframe.addEventListener('load', function onLoad() { // Reset margin of iframe body iframe.contentDocument.body.style.margin = '0'; props.onIframeLoad(); }); // We skip mounting and returns as we need to ensure // the load event is fired after we setup the global variable return iframe; }
Creates the main `iframe` the overlay will attach to. Accepts a callback to be ran after iframe is initialized. @param {Document} document @param {HTMLElement} root @param {IframeProps} props @returns {HTMLIFrameElement}
IframeRoot ( document , root , props )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/index.js
MIT
function OverlayRoot(document, root) { const div = document.createElement('div'); div.id = 'react-refresh-overlay-error'; // Style the contents container div.style.backgroundColor = '#' + theme.grey; div.style.boxSizing = 'border-box'; div.style.color = '#' + theme.white; div.style.fontFamily = [ '-apple-system', 'BlinkMacSystemFont', '"Segoe UI"', '"Helvetica Neue"', 'Helvetica', 'Arial', 'sans-serif', '"Apple Color Emoji"', '"Segoe UI Emoji"', 'Segoe UI Symbol', ].join(', '); div.style.fontSize = '0.875rem'; div.style.height = '100%'; div.style.lineHeight = '1.3'; div.style.overflow = 'auto'; div.style.padding = '1rem 1.5rem 0'; div.style.paddingTop = 'max(1rem, env(safe-area-inset-top))'; div.style.paddingRight = 'max(1.5rem, env(safe-area-inset-right))'; div.style.paddingBottom = 'env(safe-area-inset-bottom)'; div.style.paddingLeft = 'max(1.5rem, env(safe-area-inset-left))'; div.style.width = '100vw'; root.appendChild(div); return div; }
Creates the main `div` element for the overlay to render. @param {Document} document @param {HTMLElement} root @returns {HTMLDivElement}
OverlayRoot ( document , root )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/index.js
MIT
function ensureRootExists(renderFn) { if (root) { // Overlay root is ready, we can render right away. renderFn(); return; } // Creating an iframe may be asynchronous so we'll defer render. // In case of multiple calls, function from the last call will be used. scheduledRenderFn = renderFn; if (iframeRoot) { // Iframe is already ready, it will fire the load event. return; } // Create the iframe root, and, the overlay root inside it when it is ready. iframeRoot = IframeRoot(document, document.body, { onIframeLoad: function onIframeLoad() { rootDocument = iframeRoot.contentDocument; root = OverlayRoot(rootDocument, rootDocument.body); scheduledRenderFn(); }, }); // We have to mount here to ensure `iframeRoot` is set when `onIframeLoad` fires. // This is because onIframeLoad() will be called synchronously // or asynchronously depending on the browser. document.body.appendChild(iframeRoot); }
Ensures the iframe root and the overlay root are both initialized before render. If check fails, render will be deferred until both roots are initialized. @param {RenderFn} renderFn A function that triggers a DOM render. @returns {void}
ensureRootExists ( renderFn )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/index.js
MIT
function render() { ensureRootExists(function () { const currentFocus = rootDocument.activeElement; let currentFocusId; if (currentFocus.localName === 'button' && currentFocus.id) { currentFocusId = currentFocus.id; } utils.removeAllChildren(root); if (currentCompileErrorMessage) { currentMode = 'compileError'; CompileErrorContainer(rootDocument, root, { errorMessage: currentCompileErrorMessage, }); } else if (currentRuntimeErrors.length) { currentMode = 'runtimeError'; RuntimeErrorHeader(rootDocument, root, { currentErrorIndex: currentRuntimeErrorIndex, totalErrors: currentRuntimeErrors.length, }); RuntimeErrorContainer(rootDocument, root, { currentError: currentRuntimeErrors[currentRuntimeErrorIndex], }); RuntimeErrorFooter(rootDocument, root, { initialFocus: currentFocusId, multiple: currentRuntimeErrors.length > 1, onClickCloseButton: function onClose() { clearRuntimeErrors(); }, onClickNextButton: function onNext() { if (currentRuntimeErrorIndex === currentRuntimeErrors.length - 1) { return; } currentRuntimeErrorIndex += 1; ensureRootExists(render); }, onClickPrevButton: function onPrev() { if (currentRuntimeErrorIndex === 0) { return; } currentRuntimeErrorIndex -= 1; ensureRootExists(render); }, }); } }); }
Creates the main `div` element for the overlay to render. @returns {void}
render ( )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/index.js
MIT
function cleanup() { // Clean up and reset all internal state. document.body.removeChild(iframeRoot); scheduledRenderFn = null; root = null; iframeRoot = null; }
Destroys the state of the overlay. @returns {void}
cleanup ( )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/index.js
MIT
function clearCompileError() { if (!root || currentMode !== 'compileError') { return; } currentCompileErrorMessage = ''; currentMode = null; cleanup(); }
Clears Webpack compilation errors and dismisses the compile error overlay. @returns {void}
clearCompileError ( )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/index.js
MIT
function clearRuntimeErrors(dismissOverlay) { if (!root || currentMode !== 'runtimeError') { return; } currentRuntimeErrorIndex = 0; currentRuntimeErrors = []; if (typeof dismissOverlay === 'undefined' || dismissOverlay) { currentMode = null; cleanup(); } }
Clears runtime error records and dismisses the runtime error overlay. @param {boolean} [dismissOverlay] Whether to dismiss the overlay or not. @returns {void}
clearRuntimeErrors ( dismissOverlay )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/index.js
MIT
function showCompileError(message) { if (!message) { return; } currentCompileErrorMessage = message; render(); }
Shows the compile error overlay with the specific Webpack error message. @param {string} message @returns {void}
showCompileError ( message )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/index.js
MIT
function showRuntimeErrors(errors) { if (!errors || !errors.length) { return; } currentRuntimeErrors = errors; render(); }
Shows the runtime error overlay with the specific error records. @param {Error[]} errors @returns {void}
showRuntimeErrors ( errors )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/index.js
MIT
function handleRuntimeError(error) { if (error && !isWebpackCompileError(error) && currentRuntimeErrors.indexOf(error) === -1) { currentRuntimeErrors = currentRuntimeErrors.concat(error); } debouncedShowRuntimeErrors(currentRuntimeErrors); }
Handles runtime error contexts captured with EventListeners. Integrates with a runtime error overlay. @param {Error} error A valid error object. @returns {void}
handleRuntimeError ( error )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/index.js
MIT
function isWebpackCompileError(error) { return /Module [A-z ]+\(from/.test(error.message) || /Cannot find module/.test(error.message); } /** * Handles runtime error contexts captured with EventListeners. * Integrates with a runtime error overlay. * @param {Error} error A valid error object. * @returns {void} */ function handleRuntimeError(error) { if (error && !isWebpackCompileError(error) && currentRuntimeErrors.indexOf(error) === -1) { currentRuntimeErrors = currentRuntimeErrors.concat(error); } debouncedShowRuntimeErrors(currentRuntimeErrors); } module.exports = Object.freeze({ clearCompileError: clearCompileError, clearRuntimeErrors: clearRuntimeErrors, handleRuntimeError: handleRuntimeError, showCompileError: showCompileError, showRuntimeErrors: showRuntimeErrors, });
Detects if an error is a Webpack compilation error. @param {Error} error The error of interest. @returns {boolean} If the error is a Webpack compilation error.
isWebpackCompileError ( error )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/index.js
MIT
function RuntimeErrorHeader(document, root, props) { const header = document.createElement('div'); header.innerText = 'Error ' + (props.currentErrorIndex + 1) + ' of ' + props.totalErrors; header.style.backgroundColor = '#' + theme.red; header.style.color = '#' + theme.white; header.style.fontWeight = '500'; header.style.height = '2.5rem'; header.style.left = '0'; header.style.lineHeight = '2.5rem'; header.style.position = 'fixed'; header.style.textAlign = 'center'; header.style.top = '0'; header.style.width = '100vw'; header.style.zIndex = '2'; root.appendChild(header); Spacer(document, root, { space: '2.5rem' }); }
A fixed header that shows the total runtime error count. @param {Document} document @param {HTMLElement} root @param {RuntimeErrorHeaderProps} props @returns {void}
RuntimeErrorHeader ( document , root , props )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/components/RuntimeErrorHeader.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/components/RuntimeErrorHeader.js
MIT
function CompileErrorTrace(document, root, props) { const errorParts = props.errorMessage.split('\n'); if (errorParts.length) { if (errorParts[0]) { errorParts[0] = utils.formatFilename(errorParts[0]); } const errorMessage = errorParts.splice(1, 1)[0]; if (errorMessage) { // Strip filename from the error message errorParts.unshift(errorMessage.replace(/^(.*:)\s.*:(\s.*)$/, '$1$2')); } } const stackContainer = document.createElement('pre'); stackContainer.innerHTML = entities.decode( ansiHTML(entities.encode(errorParts.join('\n'), { level: 'html5', mode: 'nonAscii' })), { level: 'html5' } ); stackContainer.style.fontFamily = [ '"Operator Mono SSm"', '"Operator Mono"', '"Fira Code Retina"', '"Fira Code"', '"FiraCode-Retina"', '"Andale Mono"', '"Lucida Console"', 'Menlo', 'Consolas', 'Monaco', 'monospace', ].join(', '); stackContainer.style.margin = '0'; stackContainer.style.whiteSpace = 'pre-wrap'; root.appendChild(stackContainer); }
A formatter that turns Webpack compile error messages into highlighted HTML source traces. @param {Document} document @param {HTMLElement} root @param {CompileErrorTraceProps} props @returns {void}
CompileErrorTrace ( document , root , props )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/components/CompileErrorTrace.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/components/CompileErrorTrace.js
MIT
function Spacer(document, root, props) { const spacer = document.createElement('div'); spacer.style.paddingBottom = props.space; root.appendChild(spacer); }
An empty element to add spacing manually. @param {Document} document @param {HTMLElement} root @param {SpacerProps} props @returns {void}
Spacer ( document , root , props )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/components/Spacer.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/components/Spacer.js
MIT
function RuntimeErrorFooter(document, root, props) { const footer = document.createElement('div'); footer.style.backgroundColor = '#' + theme.dimgrey; footer.style.bottom = '0'; footer.style.boxShadow = '0 -1px 4px rgba(0, 0, 0, 0.3)'; footer.style.height = '2.5rem'; footer.style.left = '0'; footer.style.right = '0'; footer.style.lineHeight = '2.5rem'; footer.style.paddingBottom = '0'; footer.style.paddingBottom = 'env(safe-area-inset-bottom)'; footer.style.position = 'fixed'; footer.style.textAlign = 'center'; footer.style.zIndex = '2'; const BUTTON_CONFIGS = { prev: { id: 'prev', label: '◀&ensp;Prev', onClick: props.onClickPrevButton, }, close: { id: 'close', label: '×&ensp;Close', onClick: props.onClickCloseButton, }, next: { id: 'next', label: 'Next&ensp;▶', onClick: props.onClickNextButton, }, }; let buttons = [BUTTON_CONFIGS.close]; if (props.multiple) { buttons = [BUTTON_CONFIGS.prev, BUTTON_CONFIGS.close, BUTTON_CONFIGS.next]; } /** @type {HTMLButtonElement | undefined} */ let initialFocusButton; for (let i = 0; i < buttons.length; i += 1) { const buttonConfig = buttons[i]; const button = document.createElement('button'); button.id = buttonConfig.id; button.innerHTML = buttonConfig.label; button.tabIndex = 1; button.style.backgroundColor = '#' + theme.dimgrey; button.style.border = 'none'; button.style.color = '#' + theme.white; button.style.cursor = 'pointer'; button.style.fontSize = 'inherit'; button.style.height = '100%'; button.style.padding = '0.5rem 0.75rem'; button.style.width = (100 / buttons.length).toString(10) + '%'; button.addEventListener('click', buttonConfig.onClick); if (buttonConfig.id === props.initialFocus) { initialFocusButton = button; } footer.appendChild(button); } root.appendChild(footer); Spacer(document, root, { space: '2.5rem' }); if (initialFocusButton) { initialFocusButton.focus(); } }
A fixed footer that handles pagination of runtime errors. @param {Document} document @param {HTMLElement} root @param {RuntimeErrorFooterProps} props @returns {void}
RuntimeErrorFooter ( document , root , props )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/components/RuntimeErrorFooter.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/components/RuntimeErrorFooter.js
MIT
function RuntimeErrorStack(document, root, props) { const stackTitle = document.createElement('h4'); stackTitle.innerText = 'Call Stack'; stackTitle.style.color = '#' + theme.white; stackTitle.style.fontSize = '1.0625rem'; stackTitle.style.fontWeight = '500'; stackTitle.style.lineHeight = '1.3'; stackTitle.style.margin = '0 0 0.5rem'; const stackContainer = document.createElement('div'); stackContainer.style.fontSize = '0.8125rem'; stackContainer.style.lineHeight = '1.3'; stackContainer.style.whiteSpace = 'pre-wrap'; let errorStacks; try { errorStacks = ErrorStackParser.parse(props.error); } catch (e) { errorStacks = []; stackContainer.innerHTML = 'No stack trace is available for this error!'; } for (let i = 0; i < Math.min(errorStacks.length, 10); i += 1) { const currentStack = errorStacks[i]; const functionName = document.createElement('code'); functionName.innerHTML = '&emsp;' + currentStack.functionName || '(anonymous function)'; functionName.style.color = '#' + theme.yellow; functionName.style.fontFamily = [ '"Operator Mono SSm"', '"Operator Mono"', '"Fira Code Retina"', '"Fira Code"', '"FiraCode-Retina"', '"Andale Mono"', '"Lucida Console"', 'Menlo', 'Consolas', 'Monaco', 'monospace', ].join(', '); const fileName = document.createElement('div'); fileName.innerHTML = '&emsp;&emsp;' + utils.formatFilename(currentStack.fileName) + ':' + currentStack.lineNumber + ':' + currentStack.columnNumber; fileName.style.color = '#' + theme.white; fileName.style.fontSize = '0.6875rem'; fileName.style.marginBottom = '0.25rem'; stackContainer.appendChild(functionName); stackContainer.appendChild(fileName); } root.appendChild(stackTitle); root.appendChild(stackContainer); }
A formatter that turns runtime error stacks into highlighted HTML stacks. @param {Document} document @param {HTMLElement} root @param {RuntimeErrorStackProps} props @returns {void}
RuntimeErrorStack ( document , root , props )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/components/RuntimeErrorStack.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/components/RuntimeErrorStack.js
MIT
function RuntimeErrorContainer(document, root, props) { PageHeader(document, root, { message: props.currentError.message, title: props.currentError.name, topOffset: '2.5rem', }); RuntimeErrorStack(document, root, { error: props.currentError, }); Spacer(document, root, { space: '1rem' }); }
A container to render runtime error messages with stack trace. @param {Document} document @param {HTMLElement} root @param {RuntimeErrorContainerProps} props @returns {void}
RuntimeErrorContainer ( document , root , props )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/containers/RuntimeErrorContainer.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/containers/RuntimeErrorContainer.js
MIT
function CompileErrorContainer(document, root, props) { PageHeader(document, root, { title: 'Failed to compile.', }); CompileErrorTrace(document, root, { errorMessage: props.errorMessage }); Spacer(document, root, { space: '1rem' }); }
A container to render Webpack compilation error messages with source trace. @param {Document} document @param {HTMLElement} root @param {CompileErrorContainerProps} props @returns {void}
CompileErrorContainer ( document , root , props )
javascript
pmmmwh/react-refresh-webpack-plugin
overlay/containers/CompileErrorContainer.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/overlay/containers/CompileErrorContainer.js
MIT
function tryDismissErrorOverlay() { __react_refresh_error_overlay__.clearCompileError(); __react_refresh_error_overlay__.clearRuntimeErrors(!hasRuntimeErrors); hasRuntimeErrors = false; }
Try dismissing the compile error overlay. This will also reset runtime error records (if any), because we have new source to evaluate. @returns {void}
tryDismissErrorOverlay ( )
javascript
pmmmwh/react-refresh-webpack-plugin
client/ErrorOverlayEntry.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/client/ErrorOverlayEntry.js
MIT
function handleCompileSuccess() { isHotReload = true; if (isHotReload) { tryDismissErrorOverlay(); } }
A function called after a compile success signal is received from Webpack. @returns {void}
handleCompileSuccess ( )
javascript
pmmmwh/react-refresh-webpack-plugin
client/ErrorOverlayEntry.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/client/ErrorOverlayEntry.js
MIT
function handleCompileErrors(errors) { isHotReload = true; const formattedErrors = formatWebpackErrors(errors); // Only show the first error __react_refresh_error_overlay__.showCompileError(formattedErrors[0]); }
A function called after a compile errored signal is received from Webpack. @param {string[]} errors @returns {void}
handleCompileErrors ( errors )
javascript
pmmmwh/react-refresh-webpack-plugin
client/ErrorOverlayEntry.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/client/ErrorOverlayEntry.js
MIT
function runWithPatchedUrl(callback) { var __originalURL; var __originalURLSearchParams; // Polyfill the DOM URL and URLSearchParams constructors if (__react_refresh_polyfill_url__ || !window.URL) { __originalURL = window.URL; window.URL = require('core-js-pure/web/url'); } if (__react_refresh_polyfill_url__ || !window.URLSearchParams) { __originalURLSearchParams = window.URLSearchParams; window.URLSearchParams = require('core-js-pure/web/url-search-params'); } // Pass in URL APIs in case they are needed callback({ URL: window.URL, URLSearchParams: window.URLSearchParams }); // Restore polyfill-ed APIs to their original state if (__originalURL) { window.URL = __originalURL; } if (__originalURLSearchParams) { window.URLSearchParams = __originalURLSearchParams; } }
Runs a callback with patched the DOM URL APIs. @param {function(UrlAPIs): void} callback The code to run with patched URL globals. @returns {void}
runWithPatchedUrl ( callback )
javascript
pmmmwh/react-refresh-webpack-plugin
client/utils/patchUrl.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/client/utils/patchUrl.js
MIT
function createErrorHandler(callback) { return function errorHandler(event) { if (!event || !event.error) { return callback(null); } if (event.error instanceof Error) { return callback(event.error); } // A non-error was thrown, we don't have a trace. :( // Look in your browser's devtools for more information return callback(new Error(event.error)); }; }
A function that creates an event handler for the `error` event. @param {EventCallback} callback A function called to handle the error context. @returns {EventHandler} A handler for the `error` event.
createErrorHandler ( callback )
javascript
pmmmwh/react-refresh-webpack-plugin
client/utils/errorEventHandlers.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/client/utils/errorEventHandlers.js
MIT
function createRejectionHandler(callback) { return function rejectionHandler(event) { if (!event || !event.reason) { return callback(new Error('Unknown')); } if (event.reason instanceof Error) { return callback(event.reason); } // A non-error was rejected, we don't have a trace :( // Look in your browser's devtools for more information return callback(new Error(event.reason)); }; }
A function that creates an event handler for the `unhandledrejection` event. @param {EventCallback} callback A function called to handle the error context. @returns {EventHandler} A handler for the `unhandledrejection` event.
createRejectionHandler ( callback )
javascript
pmmmwh/react-refresh-webpack-plugin
client/utils/errorEventHandlers.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/client/utils/errorEventHandlers.js
MIT
function unregister() { if (eventHandler === null) { return; } window.removeEventListener(eventType, eventHandler); eventHandler = null; }
Unregisters an EventListener if it has been registered. @returns {void}
unregister ( )
javascript
pmmmwh/react-refresh-webpack-plugin
client/utils/errorEventHandlers.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/client/utils/errorEventHandlers.js
MIT
function register(callback) { if (eventHandler !== null) { return; } eventHandler = createHandler(callback); window.addEventListener(eventType, eventHandler); return unregister; }
Registers an EventListener if it hasn't been registered. @param {EventCallback} callback A function called after the event handler to handle its context. @returns {unregister | void} A function to unregister the registered EventListener if registration is performed.
register ( callback )
javascript
pmmmwh/react-refresh-webpack-plugin
client/utils/errorEventHandlers.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/client/utils/errorEventHandlers.js
MIT
function createWindowEventHandler(eventType, createHandler) { /** * @type {EventHandler | null} A cached event handler function. */ let eventHandler = null; /** * Unregisters an EventListener if it has been registered. * @returns {void} */ function unregister() { if (eventHandler === null) { return; } window.removeEventListener(eventType, eventHandler); eventHandler = null; } /** * Registers an EventListener if it hasn't been registered. * @param {EventCallback} callback A function called after the event handler to handle its context. * @returns {unregister | void} A function to unregister the registered EventListener if registration is performed. */ function register(callback) { if (eventHandler !== null) { return; } eventHandler = createHandler(callback); window.addEventListener(eventType, eventHandler); return unregister; } return register; }
Creates a handler that registers an EventListener on window for a valid type and calls a callback when the event fires. @param {string} eventType A valid DOM event type. @param {function(EventCallback): EventHandler} createHandler A function that creates an event handler. @returns {register} A function that registers the EventListener given a callback.
createWindowEventHandler ( eventType , createHandler )
javascript
pmmmwh/react-refresh-webpack-plugin
client/utils/errorEventHandlers.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/client/utils/errorEventHandlers.js
MIT
function isLikelyASyntaxError(message) { return message.indexOf(friendlySyntaxErrorLabel) !== -1; }
Checks if the error message is for a syntax error. @param {string} message The raw Webpack error message. @returns {boolean} Whether the error message is for a syntax error.
isLikelyASyntaxError ( message )
javascript
pmmmwh/react-refresh-webpack-plugin
client/utils/formatWebpackErrors.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/client/utils/formatWebpackErrors.js
MIT
function formatWebpackErrors(errors) { let formattedErrors = errors.map(function (errorObjOrMessage) { // Webpack 5 compilation errors are in the form of descriptor objects, // so we have to join pieces to get the format we want. if (typeof errorObjOrMessage === 'object') { return formatMessage([errorObjOrMessage.moduleName, errorObjOrMessage.message].join('\n')); } // Webpack 4 compilation errors are strings return formatMessage(errorObjOrMessage); }); if (formattedErrors.some(isLikelyASyntaxError)) { // If there are any syntax errors, show just them. formattedErrors = formattedErrors.filter(isLikelyASyntaxError); } return formattedErrors; }
Formats Webpack error messages into a more readable format. @param {Array<string | WebpackErrorObj>} errors An array of Webpack error messages. @returns {string[]} The formatted Webpack error messages.
formatWebpackErrors ( errors )
javascript
pmmmwh/react-refresh-webpack-plugin
client/utils/formatWebpackErrors.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/client/utils/formatWebpackErrors.js
MIT
function formatMessage(message) { let lines = message.split('\n'); // Strip Webpack-added headers off errors/warnings // https://github.com/webpack/webpack/blob/master/lib/ModuleError.js lines = lines.filter(function (line) { return !/Module [A-z ]+\(from/.test(line); }); // Remove leading newline if (lines.length > 2 && lines[1].trim() === '') { lines.splice(1, 1); } // Remove duplicated newlines lines = lines.filter(function (line, index, arr) { return index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim(); }); // Clean up the file name lines[0] = lines[0].replace(/^(.*) \d+:\d+-\d+$/, '$1'); // Cleans up verbose "module not found" messages for files and packages. if (lines[1] && lines[1].indexOf('Module not found: ') === 0) { lines = [ lines[0], lines[1] .replace('Error: ', '') .replace('Module not found: Cannot find file:', 'Cannot find file:'), ]; } message = lines.join('\n'); // Clean up syntax errors message = message.replace('SyntaxError:', friendlySyntaxErrorLabel); // Internal stacks are generally useless, so we strip them - // except the stacks containing `webpack:`, // because they're normally from user code generated by webpack. message = message.replace(/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm, ''); // at ... ...:x:y message = message.replace(/^\s*at\s((?!webpack:).)*<anonymous>[\s)]*(\n|$)/gm, ''); // at ... <anonymous> message = message.replace(/^\s*at\s<anonymous>(\n|$)/gm, ''); // at <anonymous> return message.trim(); } /** * Formats Webpack error messages into a more readable format. * @param {Array<string | WebpackErrorObj>} errors An array of Webpack error messages. * @returns {string[]} The formatted Webpack error messages. */ function formatWebpackErrors(errors) { let formattedErrors = errors.map(function (errorObjOrMessage) { // Webpack 5 compilation errors are in the form of descriptor objects, // so we have to join pieces to get the format we want. if (typeof errorObjOrMessage === 'object') { return formatMessage([errorObjOrMessage.moduleName, errorObjOrMessage.message].join('\n')); } // Webpack 4 compilation errors are strings return formatMessage(errorObjOrMessage); }); if (formattedErrors.some(isLikelyASyntaxError)) { // If there are any syntax errors, show just them. formattedErrors = formattedErrors.filter(isLikelyASyntaxError); } return formattedErrors; } module.exports = formatWebpackErrors;
Cleans up Webpack error messages. This implementation is based on the one from [create-react-app](https://github.com/facebook/create-react-app/blob/edc671eeea6b7d26ac3f1eb2050e50f75cf9ad5d/packages/react-dev-utils/formatWebpackMessages.js). @param {string} message The raw Webpack error message. @returns {string} The formatted Webpack error message.
formatMessage ( message )
javascript
pmmmwh/react-refresh-webpack-plugin
client/utils/formatWebpackErrors.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/client/utils/formatWebpackErrors.js
MIT
module.exports.getRefreshGlobalScope = (runtimeGlobals) => { return `${runtimeGlobals.require || '__webpack_require__'}.$Refresh$`; };
Gets current bundle's global scope identifier for React Refresh. @param {Record<string, string>} runtimeGlobals The Webpack runtime globals. @returns {string} The React Refresh global scope within the Webpack bundle.
module.exports.getRefreshGlobalScope
javascript
pmmmwh/react-refresh-webpack-plugin
lib/globals.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/globals.js
MIT
module.exports.getWebpackVersion = (compiler) => { if (!compiler.hooks) { throw new Error(`[ReactRefreshPlugin] Webpack version is not supported!`); } // Webpack v5+ implements compiler caching return 'cache' in compiler ? 5 : 4; };
Gets current Webpack version according to features on the compiler instance. @param {import('webpack').Compiler} compiler The current Webpack compiler instance. @returns {number} The current Webpack version.
module.exports.getWebpackVersion
javascript
pmmmwh/react-refresh-webpack-plugin
lib/globals.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/globals.js
MIT
constructor(options = {}) { validateOptions(schema, options, { name: 'React Refresh Plugin', baseDataPath: 'options', }); /** * @readonly * @type {import('./types').NormalizedPluginOptions} */ this.options = normalizeOptions(options); }
@param {import('./types').ReactRefreshPluginOptions} [options] Options for react-refresh-plugin.
constructor ( options = { } )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/index.js
MIT
function injectRefreshLoader(moduleData, injectOptions) { const { match, options } = injectOptions; // Include and exclude user-specified files if (!match(moduleData.matchResource || moduleData.resource)) return moduleData; // Include and exclude dynamically generated modules from other loaders if (moduleData.matchResource && !match(moduleData.request)) return moduleData; // Exclude files referenced as assets if (moduleData.type.includes('asset')) return moduleData; // Check to prevent double injection if (moduleData.loaders.find(({ loader }) => loader === resolvedLoader)) return moduleData; // Skip react-refresh and the plugin's runtime utils to prevent self-referencing - // this is useful when using the plugin as a direct dependency, // or when node_modules are specified to be processed. if ( moduleData.resource.includes(reactRefreshPath) || moduleData.resource.includes(refreshUtilsPath) ) { return moduleData; } // As we inject runtime code for each module, // it is important to run the injected loader after everything. // This way we can ensure that all code-processing have been done, // and we won't risk breaking tools like Flow or ESLint. moduleData.loaders.unshift({ loader: resolvedLoader, options, }); return moduleData; }
Injects refresh loader to all JavaScript-like and user-specified files. @param {*} moduleData Module factory creation data. @param {InjectLoaderOptions} injectOptions Options to alter how the loader is injected. @returns {*} The injected module factory creation data.
injectRefreshLoader ( moduleData , injectOptions )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/utils/injectRefreshLoader.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/utils/injectRefreshLoader.js
MIT
function getSocketIntegration(integrationType) { let resolvedSocketIntegration; switch (integrationType) { case 'wds': { resolvedSocketIntegration = require.resolve('../../sockets/WDSSocket'); break; } case 'whm': { resolvedSocketIntegration = require.resolve('../../sockets/WHMEventSource'); break; } case 'wps': { resolvedSocketIntegration = require.resolve('../../sockets/WPSSocket'); break; } default: { resolvedSocketIntegration = require.resolve(integrationType); break; } } return resolvedSocketIntegration; }
Gets the socket integration to use for Webpack messages. @param {'wds' | 'whm' | 'wps' | string} integrationType A valid socket integration type or a path to a module. @returns {string} Path to the resolved socket integration module.
getSocketIntegration ( integrationType )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/utils/getSocketIntegration.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/utils/getSocketIntegration.js
MIT
const normalizeOptions = (options) => { d(options, 'exclude', /node_modules/i); d(options, 'include', /\.([cm]js|[jt]sx?|flow)$/i);
Normalizes the options for the plugin. @param {import('../types').ReactRefreshPluginOptions} options Non-normalized plugin options. @returns {import('../types').NormalizedPluginOptions} Normalized plugin options.
normalizeOptions
javascript
pmmmwh/react-refresh-webpack-plugin
lib/utils/normalizeOptions.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/utils/normalizeOptions.js
MIT
encodeURIComponent(string) { return string; },
@param {string} string @returns {string}
encodeURIComponent ( string )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/utils/getAdditionalEntries.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/utils/getAdditionalEntries.js
MIT
function getAdditionalEntries({ devServer, options }) { /** @type {Record<string, string | number>} */ let resourceQuery = {}; if (devServer) { const { client, https, http2, sockHost, sockPath, sockPort } = devServer; let { host, path, port } = devServer; let protocol = https || http2 ? 'https' : 'http'; if (sockHost) host = sockHost; if (sockPath) path = sockPath; if (sockPort) port = sockPort; if (client && client.webSocketURL != null) { let parsedUrl = client.webSocketURL; if (typeof parsedUrl === 'string') parsedUrl = new URL(parsedUrl); let auth; if (parsedUrl.username) { auth = parsedUrl.username; if (parsedUrl.password) { auth += ':' + parsedUrl.password; } } if (parsedUrl.hostname != null) { host = [auth != null && auth, parsedUrl.hostname].filter(Boolean).join('@'); } if (parsedUrl.pathname != null) { path = parsedUrl.pathname; } if (parsedUrl.port != null) { port = !['0', 'auto'].includes(String(parsedUrl.port)) ? parsedUrl.port : undefined; } if (parsedUrl.protocol != null) { protocol = parsedUrl.protocol !== 'auto' ? parsedUrl.protocol.replace(':', '') : 'ws'; } } if (host) resourceQuery.sockHost = host; if (path) resourceQuery.sockPath = path; if (port) resourceQuery.sockPort = port; resourceQuery.sockProtocol = protocol; } if (options.overlay) { const { sockHost, sockPath, sockPort, sockProtocol } = options.overlay; if (sockHost) resourceQuery.sockHost = sockHost; if (sockPath) resourceQuery.sockPath = sockPath; if (sockPort) resourceQuery.sockPort = sockPort; if (sockProtocol) resourceQuery.sockProtocol = sockProtocol; } // We don't need to URI encode the resourceQuery as it will be parsed by Webpack const queryString = querystring.stringify(resourceQuery, undefined, undefined, { /** * @param {string} string * @returns {string} */ encodeURIComponent(string) { return string; }, }); const prependEntries = [ // React-refresh runtime require.resolve('../../client/ReactRefreshEntry'), ]; const overlayEntries = [ // Error overlay runtime options.overlay && options.overlay.entry && `${require.resolve(options.overlay.entry)}${queryString ? `?${queryString}` : ''}`, ].filter(Boolean); return { prependEntries, overlayEntries }; }
Creates an object that contains two entry arrays: the prependEntries and overlayEntries @param {Object} optionsContainer This is the container for the options to this function @param {import('../types').NormalizedPluginOptions} optionsContainer.options Configuration options for this plugin. @param {import('webpack').Compiler["options"]["devServer"]} [optionsContainer.devServer] The webpack devServer config @returns {AdditionalEntries} An object that contains the Webpack entries for prepending and the overlay feature
getAdditionalEntries ( { devServer , options } )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/utils/getAdditionalEntries.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/utils/getAdditionalEntries.js
MIT
function getIntegrationEntry(integrationType) { let resolvedEntry; switch (integrationType) { case 'whm': { resolvedEntry = 'webpack-hot-middleware/client'; break; } case 'wps': { resolvedEntry = 'webpack-plugin-serve/client'; break; } } return resolvedEntry; }
Gets entry point of a supported socket integration. @param {'wds' | 'whm' | 'wps' | string} integrationType A valid socket integration type or a path to a module. @returns {string | undefined} Path to the resolved integration entry point.
getIntegrationEntry ( integrationType )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/utils/getIntegrationEntry.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/utils/getIntegrationEntry.js
MIT
function isSocketEntry(entry) { return socketEntries.some((socketEntry) => entry.includes(socketEntry)); }
Checks if a Webpack entry string is related to socket integrations. @param {string} entry A Webpack entry string. @returns {boolean} Whether the entry is related to socket integrations.
isSocketEntry ( entry )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/utils/injectRefreshEntry.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/utils/injectRefreshEntry.js
MIT
function getRefreshGlobal( Template, RuntimeGlobals = {}, RuntimeTemplate = { basicFunction(args, body) { return `function(${args}) {\n${Template.indent(body)}\n}`; },
Generates the refresh global runtime template. @param {import('webpack').Template} Template The template helpers. @param {Record<string, string>} [RuntimeGlobals] The runtime globals. @param {RuntimeTemplate} [RuntimeTemplate] The runtime template helpers. @returns {string} The refresh global runtime template.
getRefreshGlobal ( Template , RuntimeGlobals = { } , RuntimeTemplate = { basicFunction ( args , body )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/utils/getRefreshGlobal.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/utils/getRefreshGlobal.js
MIT
function getModuleExports(moduleId) { if (typeof moduleId === 'undefined') { // `moduleId` is unavailable, which indicates that this module is not in the cache, // which means we won't be able to capture any exports, // and thus they cannot be refreshed safely. // These are likely runtime or dynamically generated modules. return {}; } var maybeModule = __webpack_require__.c[moduleId]; if (typeof maybeModule === 'undefined') { // `moduleId` is available but the module in cache is unavailable, // which indicates the module is somehow corrupted (e.g. broken Webpacak `module` globals). // We will warn the user (as this is likely a mistake) and assume they cannot be refreshed. console.warn('[React Refresh] Failed to get exports for module: ' + moduleId + '.'); return {}; } var exportsOrPromise = maybeModule.exports; if (typeof Promise !== 'undefined' && exportsOrPromise instanceof Promise) { return exportsOrPromise.then(function (exports) { return exports; }); } return exportsOrPromise; }
Extracts exports from a webpack module object. @param {string} moduleId A Webpack module ID. @returns {*} An exports object from the module.
getModuleExports ( moduleId )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/runtime/RefreshUtils.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/runtime/RefreshUtils.js
MIT
function getReactRefreshBoundarySignature(moduleExports) { var signature = []; signature.push(Refresh.getFamilyByType(moduleExports)); if (moduleExports == null || typeof moduleExports !== 'object') { // Exit if we can't iterate over exports. return signature; } for (var key in moduleExports) { if (key === '__esModule') { continue; } signature.push(key); signature.push(Refresh.getFamilyByType(moduleExports[key])); } return signature; }
Calculates the signature of a React refresh boundary. If this signature changes, it's unsafe to accept the boundary. This implementation is based on the one in [Metro](https://github.com/facebook/metro/blob/907d6af22ac6ebe58572be418e9253a90665ecbd/packages/metro/src/lib/polyfills/require.js#L795-L816). @param {*} moduleExports A Webpack module exports object. @returns {string[]} A React refresh boundary signature array.
getReactRefreshBoundarySignature ( moduleExports )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/runtime/RefreshUtils.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/runtime/RefreshUtils.js
MIT
function enqueueUpdate(callback) { if (typeof refreshTimeout === 'undefined') { refreshTimeout = setTimeout(function () { refreshTimeout = undefined; Refresh.performReactRefresh(); callback(); }, 30); } }
Performs react refresh on a delay and clears the error overlay. @param {function(): void} callback @returns {void}
enqueueUpdate ( callback )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/runtime/RefreshUtils.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/runtime/RefreshUtils.js
MIT
function createDebounceUpdate() { /** * A cached setTimeout handler. * @type {number | undefined} */ var refreshTimeout; /** * Performs react refresh on a delay and clears the error overlay. * @param {function(): void} callback * @returns {void} */ function enqueueUpdate(callback) { if (typeof refreshTimeout === 'undefined') { refreshTimeout = setTimeout(function () { refreshTimeout = undefined; Refresh.performReactRefresh(); callback(); }, 30); } } return enqueueUpdate; }
Creates a helper that performs a delayed React refresh. @returns {function(function(): void): void} A debounced React refresh function.
createDebounceUpdate ( )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/runtime/RefreshUtils.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/runtime/RefreshUtils.js
MIT
function isReactRefreshBoundary(moduleExports) { if (Refresh.isLikelyComponentType(moduleExports)) { return true; } if (moduleExports === undefined || moduleExports === null || typeof moduleExports !== 'object') { // Exit if we can't iterate over exports. return false; } var hasExports = false; var areAllExportsComponents = true; for (var key in moduleExports) { hasExports = true; // This is the ES Module indicator flag if (key === '__esModule') { continue; } // We can (and have to) safely execute getters here, // as Webpack manually assigns harmony exports to getters, // without any side-effects attached. // Ref: https://github.com/webpack/webpack/blob/b93048643fe74de2a6931755911da1212df55897/lib/MainTemplate.js#L281 var exportValue = moduleExports[key]; if (!Refresh.isLikelyComponentType(exportValue)) { areAllExportsComponents = false; } } return hasExports && areAllExportsComponents; }
Checks if all exports are likely a React component. This implementation is based on the one in [Metro](https://github.com/facebook/metro/blob/febdba2383113c88296c61e28e4ef6a7f4939fda/packages/metro/src/lib/polyfills/require.js#L748-L774). @param {*} moduleExports A Webpack module exports object. @returns {boolean} Whether the exports are React component like.
isReactRefreshBoundary ( moduleExports )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/runtime/RefreshUtils.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/runtime/RefreshUtils.js
MIT
function registerExportsForReactRefresh(moduleExports, moduleId) { if (Refresh.isLikelyComponentType(moduleExports)) { // Register module.exports if it is likely a component Refresh.register(moduleExports, moduleId + ' %exports%'); } if (moduleExports === undefined || moduleExports === null || typeof moduleExports !== 'object') { // Exit if we can't iterate over the exports. return; } for (var key in moduleExports) { // Skip registering the ES Module indicator if (key === '__esModule') { continue; } var exportValue = moduleExports[key]; if (Refresh.isLikelyComponentType(exportValue)) { var typeID = moduleId + ' %exports% ' + key; Refresh.register(exportValue, typeID); } } }
Checks if exports are likely a React component and registers them. This implementation is based on the one in [Metro](https://github.com/facebook/metro/blob/febdba2383113c88296c61e28e4ef6a7f4939fda/packages/metro/src/lib/polyfills/require.js#L818-L835). @param {*} moduleExports A Webpack module exports object. @param {string} moduleId A Webpack module ID. @returns {void}
registerExportsForReactRefresh ( moduleExports , moduleId )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/runtime/RefreshUtils.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/runtime/RefreshUtils.js
MIT