code stringlengths 24 2.07M | docstring stringlengths 25 85.3k | func_name stringlengths 1 92 | language stringclasses 1
value | repo stringlengths 5 64 | path stringlengths 4 172 | url stringlengths 44 218 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
function error(msg) {
if (topWindow.console) {
if (topWindow.console.error) {
topWindow.console.error(msg);
} else if (topWindow.console.log) {
topWindow.console.log(msg);
}
}
} | Loads a shader.
@param {WebGLRenderingContext} gl The WebGLRenderingContext to use.
@param {string} shaderSource The shader source.
@param {number} shaderType The type of shader.
@param {module:webgl-utils.ErrorCallback} opt_errorCallback callback for errors.
@return {WebGLShader} The created shader. | error | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function loadShader(gl, shaderSource, shaderType, opt_errorCallback) {
const errFn = opt_errorCallback || error;
// Create the shader object
const shader = gl.createShader(shaderType);
// Load the shader source
gl.shaderSource(shader, shaderSource);
// Compile the shader
... | Creates a program, attaches shaders, binds attrib locations, links the
program and calls useProgram.
@param {WebGLShader[]} shaders The shaders to attach
@param {string[]} [opt_attribs] An array of attribs names. Locations will be assigned by index if not passed in
@param {number[]} [opt_locations] The locations for th... | loadShader | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function createProgram(
gl, shaders, opt_attribs, opt_locations, opt_errorCallback) {
const errFn = opt_errorCallback || error;
const program = gl.createProgram();
shaders.forEach(function(shader) {
gl.attachShader(program, shader);
});
if (opt_attribs) {
opt_attrib... | Loads a shader from a script tag.
@param {WebGLRenderingContext} gl The WebGLRenderingContext to use.
@param {string} scriptId The id of the script tag.
@param {number} opt_shaderType The type of shader. If not passed in it will
be derived from the type of the script tag.
@param {module:webgl-utils.ErrorCallback} o... | createProgram | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function createShaderFromScript(
gl, scriptId, opt_shaderType, opt_errorCallback) {
let shaderSource = '';
let shaderType;
const shaderScript = document.getElementById(scriptId);
if (!shaderScript) {
throw ('*** Error: unknown script element' + scriptId);
}
shaderSour... | Creates a program from 2 script tags.
@param {WebGLRenderingContext} gl The WebGLRenderingContext
to use.
@param {string[]} shaderScriptIds Array of ids of the script
tags for the shaders. The first is assumed to be the
vertex shader, the second the fragment shader.
@param {string[]} [opt_attribs]... | createShaderFromScript | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function createProgramFromScripts(
gl, shaderScriptIds, opt_attribs, opt_locations, opt_errorCallback) {
const shaders = [];
for (let ii = 0; ii < shaderScriptIds.length; ++ii) {
shaders.push(createShaderFromScript(
gl, shaderScriptIds[ii], gl[defaultShaderType[ii]], opt_errorCal... | Returns the corresponding bind point for a given sampler type | createProgramFromScripts | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function createProgramFromSources(
gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback) {
const shaders = [];
for (let ii = 0; ii < shaderSources.length; ++ii) {
shaders.push(loadShader(
gl, shaderSources[ii], gl[defaultShaderType[ii]], opt_errorCallback));
}
... | Creates a setter for a uniform of the given program with it's
location embedded in the setter.
@param {WebGLProgram} program
@param {WebGLUniformInfo} uniformInfo
@returns {function} the created setter. | createProgramFromSources | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function getBindPointForSamplerType(gl, type) {
if (type === gl.SAMPLER_2D) return gl.TEXTURE_2D; // eslint-disable-line
if (type === gl.SAMPLER_CUBE) return gl.TEXTURE_CUBE_MAP; // eslint-disable-line
return undefined;
} | Creates a setter for a uniform of the given program with it's
location embedded in the setter.
@param {WebGLProgram} program
@param {WebGLUniformInfo} uniformInfo
@returns {function} the created setter. | getBindPointForSamplerType | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function createUniformSetters(gl, program) {
let textureUnit = 0;
/**
* Creates a setter for a uniform of the given program with it's
* location embedded in the setter.
* @param {WebGLProgram} program
* @param {WebGLUniformInfo} uniformInfo
* @returns {function} the cre... | Creates a setter for a uniform of the given program with it's
location embedded in the setter.
@param {WebGLProgram} program
@param {WebGLUniformInfo} uniformInfo
@returns {function} the created setter. | createUniformSetters | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function createUniformSetter(program, uniformInfo) {
const location = gl.getUniformLocation(program, uniformInfo.name);
const type = uniformInfo.type;
// Check if this uniform is an array
const isArray = (uniformInfo.size > 1 && uniformInfo.name.substr(-3) === '[0]');
if (type ==... | Creates a setter for a uniform of the given program with it's
location embedded in the setter.
@param {WebGLProgram} program
@param {WebGLUniformInfo} uniformInfo
@returns {function} the created setter. | createUniformSetter | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function setUniforms(setters, ...values) {
setters = setters.uniformSetters || setters;
for (const uniforms of values) {
Object.keys(uniforms).forEach(function(name) {
const setter = setters[name];
if (setter) {
setter(uniforms[name]);
}
});
}
... | Creates setter functions for all attributes of a shader
program. You can pass this to {@link module:webgl-utils.setBuffersAndAttributes} to set all your buffers and attributes.
@see {@link module:webgl-utils.setAttributes} for example
@param {WebGLProgram} program the program to create setters for.
@return {Object.<st... | setUniforms | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function createAttributeSetters(gl, program) {
const attribSetters = {
};
function createAttribSetter(index) {
return function(b) {
if (b.value) {
gl.disableVertexAttribArray(index);
switch (b.value.length) {
case 4:
... | Creates setter functions for all attributes of a shader
program. You can pass this to {@link module:webgl-utils.setBuffersAndAttributes} to set all your buffers and attributes.
@see {@link module:webgl-utils.setAttributes} for example
@param {WebGLProgram} program the program to create setters for.
@return {Object.<st... | createAttributeSetters | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function createAttribSetter(index) {
return function(b) {
if (b.value) {
gl.disableVertexAttribArray(index);
switch (b.value.length) {
case 4:
gl.vertexAttrib4fv(index, b.value);
break;
case 3:
... | Creates setter functions for all attributes of a shader
program. You can pass this to {@link module:webgl-utils.setBuffersAndAttributes} to set all your buffers and attributes.
@see {@link module:webgl-utils.setAttributes} for example
@param {WebGLProgram} program the program to create setters for.
@return {Object.<st... | createAttribSetter | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function setAttributes(setters, attribs) {
setters = setters.attribSetters || setters;
Object.keys(attribs).forEach(function(name) {
const setter = setters[name];
if (setter) {
setter(attribs[name]);
}
});
} | Creates a vertex array object and then sets the attributes
on it
@param {WebGLRenderingContext} gl The WebGLRenderingContext
to use.
@param {Object.<string, function>| module:webgl-utils.ProgramInfo} programInfo as returned from createProgramInfo or Attribute setters as returned from createAttributeSetters
@par... | setAttributes | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function createVAOAndSetAttributes(gl, setters, attribs, indices) {
const vao = gl.createVertexArray();
gl.bindVertexArray(vao);
setAttributes(setters, attribs);
if (indices) {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indices);
}
// We unbind this because otherwise any change t... | @typedef {Object} ProgramInfo
@property {WebGLProgram} program A shader program
@property {Object<string, function>} uniformSetters: object of setters as returned from createUniformSetters,
@property {Object<string, function>} attribSetters: object of setters as returned from createAttribSetters,
@memberOf module:webgl... | createVAOAndSetAttributes | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function createVAOFromBufferInfo(gl, programInfo, bufferInfo) {
return createVAOAndSetAttributes(gl, programInfo.attribSetters || programInfo, bufferInfo.attribs, bufferInfo.indices);
} | Creates a ProgramInfo from 2 sources.
A ProgramInfo contains
programInfo = {
program: WebGLProgram,
uniformSetters: object of setters as returned from createUniformSetters,
attribSetters: object of setters as returned from createAttribSetters,
}
@param {WebGLRenderingContext} gl The WebG... | createVAOFromBufferInfo | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function createProgramInfo(
gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback) {
shaderSources = shaderSources.map(function(source) {
const script = document.getElementById(source);
return script ? script.text : source;
});
const program = webglUtils.createProgra... | Creates a ProgramInfo from 2 sources.
A ProgramInfo contains
programInfo = {
program: WebGLProgram,
uniformSetters: object of setters as returned from createUniformSetters,
attribSetters: object of setters as returned from createAttribSetters,
}
@param {WebGLRenderingContext} gl The WebG... | createProgramInfo | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function setBuffersAndAttributes(gl, setters, buffers) {
setAttributes(setters, buffers.attribs);
if (buffers.indices) {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);
}
} | Resize a canvas to match the size its displayed.
@param {HTMLCanvasElement} canvas The canvas to resize.
@param {number} [multiplier] amount to multiply by.
Pass in window.devicePixelRatio for native pixels.
@return {boolean} true if the canvas was resized.
@memberOf module:webgl-utils | setBuffersAndAttributes | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function getExtensionWithKnownPrefixes(gl, name) {
for (let ii = 0; ii < browserPrefixes.length; ++ii) {
const prefixedName = browserPrefixes[ii] + name;
const ext = gl.getExtension(prefixedName);
if (ext) {
return ext;
}
}
return undefined;
} | Resize a canvas to match the size its displayed.
@param {HTMLCanvasElement} canvas The canvas to resize.
@param {number} [multiplier] amount to multiply by.
Pass in window.devicePixelRatio for native pixels.
@return {boolean} true if the canvas was resized.
@memberOf module:webgl-utils | getExtensionWithKnownPrefixes | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function resizeCanvasToDisplaySize(canvas, multiplier) {
multiplier = multiplier || 1;
const width = canvas.clientWidth * multiplier | 0;
const height = canvas.clientHeight * multiplier | 0;
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canva... | Resize a canvas to match the size its displayed.
@param {HTMLCanvasElement} canvas The canvas to resize.
@param {number} [multiplier] amount to multiply by.
Pass in window.devicePixelRatio for native pixels.
@return {boolean} true if the canvas was resized.
@memberOf module:webgl-utils | resizeCanvasToDisplaySize | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function augmentTypedArray(typedArray, numComponents) {
let cursor = 0;
typedArray.push = function() {
for (let ii = 0; ii < arguments.length; ++ii) {
const value = arguments[ii];
if (value instanceof Array || (value.buffer && value.buffer instanceof ArrayBuffer)) {
f... | creates a typed array with a `push` function attached
so that you can easily *push* values.
`push` can take multiple arguments. If an argument is an array each element
of the array will be added to the typed array.
Example:
let array = createAugmentedTypedArray(3, 2); // creates a Float32Array with 6 values
... | augmentTypedArray | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function createAugmentedTypedArray(numComponents, numElements, opt_type) {
const Type = opt_type || Float32Array;
return augmentTypedArray(new Type(numComponents * numElements), numComponents);
} | creates a typed array with a `push` function attached
so that you can easily *push* values.
`push` can take multiple arguments. If an argument is an array each element
of the array will be added to the typed array.
Example:
let array = createAugmentedTypedArray(3, 2); // creates a Float32Array with 6 values
... | createAugmentedTypedArray | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function createBufferFromTypedArray(gl, array, type, drawType) {
type = type || gl.ARRAY_BUFFER;
const buffer = gl.createBuffer();
gl.bindBuffer(type, buffer);
gl.bufferData(type, array, drawType || gl.STATIC_DRAW);
return buffer;
} | creates a typed array with a `push` function attached
so that you can easily *push* values.
`push` can take multiple arguments. If an argument is an array each element
of the array will be added to the typed array.
Example:
let array = createAugmentedTypedArray(3, 2); // creates a Float32Array with 6 values
... | createBufferFromTypedArray | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function allButIndices(name) {
return name !== 'indices';
} | creates a typed array with a `push` function attached
so that you can easily *push* values.
`push` can take multiple arguments. If an argument is an array each element
of the array will be added to the typed array.
Example:
let array = createAugmentedTypedArray(3, 2); // creates a Float32Array with 6 values
... | allButIndices | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function createMapping(obj) {
const mapping = {};
Object.keys(obj).filter(allButIndices).forEach(function(key) {
mapping['a_' + key] = key;
});
return mapping;
} | creates a typed array with a `push` function attached
so that you can easily *push* values.
`push` can take multiple arguments. If an argument is an array each element
of the array will be added to the typed array.
Example:
let array = createAugmentedTypedArray(3, 2); // creates a Float32Array with 6 values
... | createMapping | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function getGLTypeForTypedArray(gl, typedArray) {
if (typedArray instanceof Int8Array) { return gl.BYTE; } // eslint-disable-line
if (typedArray instanceof Uint8Array) { return gl.UNSIGNED_BYTE; } // eslint-disable-line
if (typedArray instanceof Int16Array) { return gl.SHORT; } ... | creates a typed array with a `push` function attached
so that you can easily *push* values.
`push` can take multiple arguments. If an argument is an array each element
of the array will be added to the typed array.
Example:
let array = createAugmentedTypedArray(3, 2); // creates a Float32Array with 6 values
... | getGLTypeForTypedArray | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function getNormalizationForTypedArray(typedArray) {
if (typedArray instanceof Int8Array) { return true; } // eslint-disable-line
if (typedArray instanceof Uint8Array) { return true; } // eslint-disable-line
return false;
} | creates a typed array with a `push` function attached
so that you can easily *push* values.
`push` can take multiple arguments. If an argument is an array each element
of the array will be added to the typed array.
Example:
let array = createAugmentedTypedArray(3, 2); // creates a Float32Array with 6 values
... | getNormalizationForTypedArray | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function isArrayBuffer(a) {
return a.buffer && a.buffer instanceof ArrayBuffer;
} | creates a typed array with a `push` function attached
so that you can easily *push* values.
`push` can take multiple arguments. If an argument is an array each element
of the array will be added to the typed array.
Example:
let array = createAugmentedTypedArray(3, 2); // creates a Float32Array with 6 values
... | isArrayBuffer | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function guessNumComponentsFromName(name, length) {
let numComponents;
if (name.indexOf('coord') >= 0) {
numComponents = 2;
} else if (name.indexOf('color') >= 0) {
numComponents = 4;
} else {
numComponents = 3; // position, normals, indices ...
}
if (leng... | creates a typed array with a `push` function attached
so that you can easily *push* values.
`push` can take multiple arguments. If an argument is an array each element
of the array will be added to the typed array.
Example:
let array = createAugmentedTypedArray(3, 2); // creates a Float32Array with 6 values
... | guessNumComponentsFromName | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function makeTypedArray(array, name) {
if (isArrayBuffer(array)) {
return array;
}
if (array.data && isArrayBuffer(array.data)) {
return array.data;
}
if (Array.isArray(array)) {
array = {
data: array,
};
}
if (!array.numCompon... | @typedef {Object} AttribInfo
@property {number} [numComponents] the number of components for this attribute.
@property {number} [size] the number of components for this attribute.
@property {number} [type] the type of the attribute (eg. `gl.FLOAT`, `gl.UNSIGNED_BYTE`, etc...) Default = `gl.FLOAT`
@property {boolean} [n... | makeTypedArray | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function createAttribsFromArrays(gl, arrays, opt_mapping) {
const mapping = opt_mapping || createMapping(arrays);
const attribs = {};
Object.keys(mapping).forEach(function(attribName) {
const bufferName = mapping[attribName];
const origArray = arrays[bufferName];
if (origArray.... | tries to get the number of elements from a set of arrays. | createAttribsFromArrays | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function getArray(array) {
return array.length ? array : array.data;
} | tries to get the number of elements from a set of arrays. | getArray | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function guessNumComponentsFromName(name, length) {
let numComponents;
if (texcoordRE.test(name)) {
numComponents = 2;
} else if (colorRE.test(name)) {
numComponents = 4;
} else {
numComponents = 3; // position, normals, indices ...
}
if (length % numCompo... | @typedef {Object} BufferInfo
@property {number} numElements The number of elements to pass to `gl.drawArrays` or `gl.drawElements`.
@property {WebGLBuffer} [indices] The indices `ELEMENT_ARRAY_BUFFER` if any indices exist.
@property {Object.<string, module:webgl-utils.AttribInfo>} attribs The attribs approriate to call... | guessNumComponentsFromName | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function getNumComponents(array, arrayName) {
return array.numComponents || array.size || guessNumComponentsFromName(arrayName, getArray(array).length);
} | @typedef {Object} BufferInfo
@property {number} numElements The number of elements to pass to `gl.drawArrays` or `gl.drawElements`.
@property {WebGLBuffer} [indices] The indices `ELEMENT_ARRAY_BUFFER` if any indices exist.
@property {Object.<string, module:webgl-utils.AttribInfo>} attribs The attribs approriate to call... | getNumComponents | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function getNumElementsFromNonIndexedArrays(arrays) {
let key;
for (const k of positionKeys) {
if (k in arrays) {
key = k;
break;
}
}
key = key || Object.keys(arrays)[0];
const array = arrays[key];
const length = getArray(array).length;
const... | @typedef {Object} BufferInfo
@property {number} numElements The number of elements to pass to `gl.drawArrays` or `gl.drawElements`.
@property {WebGLBuffer} [indices] The indices `ELEMENT_ARRAY_BUFFER` if any indices exist.
@property {Object.<string, module:webgl-utils.AttribInfo>} attribs The attribs approriate to call... | getNumElementsFromNonIndexedArrays | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function createBufferInfoFromArrays(gl, arrays, opt_mapping) {
const bufferInfo = {
attribs: createAttribsFromArrays(gl, arrays, opt_mapping),
};
let indices = arrays.indices;
if (indices) {
indices = makeTypedArray(indices, 'indices');
bufferInfo.indices = createBufferFr... | Creates buffers from typed arrays
Given something like this
let arrays = {
positions: [1, 2, 3],
normals: [0, 0, 1],
}
returns something like
buffers = {
positions: WebGLBuffer,
normals: WebGLBuffer,
}
If the buffer is named 'indices' it will be made an ELEMENT_ARRAY_BUFFE... | createBufferInfoFromArrays | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function drawBufferInfo(gl, bufferInfo, primitiveType, count, offset) {
const indices = bufferInfo.indices;
primitiveType = primitiveType === undefined ? gl.TRIANGLES : primitiveType;
const numElements = count === undefined ? bufferInfo.numElements : count;
offset = offset === undefined ? 0 : of... | Draws a list of objects
@param {WebGLRenderingContext} gl A WebGLRenderingContext
@param {DrawObject[]} objectsToDraw an array of objects to draw.
@memberOf module:webgl-utils | drawBufferInfo | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function drawObjectList(gl, objectsToDraw) {
let lastUsedProgramInfo = null;
let lastUsedBufferInfo = null;
objectsToDraw.forEach(function(object) {
const programInfo = object.programInfo;
const bufferInfo = object.bufferInfo;
let bindBuffers = false;
if (programI... | Draws a list of objects
@param {WebGLRenderingContext} gl A WebGLRenderingContext
@param {DrawObject[]} objectsToDraw an array of objects to draw.
@memberOf module:webgl-utils | drawObjectList | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function glEnumToString(gl, v) {
const results = [];
for (const key in gl) {
if (gl[key] === v) {
results.push(key);
}
}
return results.length
? results.join(' | ')
: `0x${v.toString(16)}`;
} | Draws a list of objects
@param {WebGLRenderingContext} gl A WebGLRenderingContext
@param {DrawObject[]} objectsToDraw an array of objects to draw.
@memberOf module:webgl-utils | glEnumToString | javascript | limbopro/Adblock4limbo | Adguard/twdl.webgl.user.js | https://github.com/limbopro/Adblock4limbo/blob/master/Adguard/twdl.webgl.user.js | MIT |
function cleanSequence() {
return parallel(packageRunner('build_packages_clean', 'all', cleanPackage));
} | /*',
// Don't delete anything under src.
`!${packagePath}/src/* | cleanSequence | javascript | GoogleChrome/workbox | gulp-tasks/build-packages.js | https://github.com/GoogleChrome/workbox/blob/master/gulp-tasks/build-packages.js | MIT |
async function test_node_prod() {
await runNodeTestsWithEnv(global.packageOrStar, constants.BUILD_TYPES.prod);
} | /*.{js,mjs}`,
...options,
],
{preferLocal: true},
);
console.log(stdout);
} finally {
process.env.NODE_ENV = originalNodeEnv;
}
}
async function runNodeTestsWithEnv(testGroup, nodeEnv) {
const globConfig = {
ignore: ['* | test_node_prod | javascript | GoogleChrome/workbox | gulp-tasks/test-node.js | https://github.com/GoogleChrome/workbox/blob/master/gulp-tasks/test-node.js | MIT |
async function test_node_dev() {
await runNodeTestsWithEnv(global.packageOrStar, constants.BUILD_TYPES.dev);
} | /*.{js,mjs}`,
...options,
],
{preferLocal: true},
);
console.log(stdout);
} finally {
process.env.NODE_ENV = originalNodeEnv;
}
}
async function runNodeTestsWithEnv(testGroup, nodeEnv) {
const globConfig = {
ignore: ['* | test_node_dev | javascript | GoogleChrome/workbox | gulp-tasks/test-node.js | https://github.com/GoogleChrome/workbox/blob/master/gulp-tasks/test-node.js | MIT |
async function test_node_all() {
await runNodeTestsWithEnv('all', constants.BUILD_TYPES.prod);
} | /*.{js,mjs}`,
...options,
],
{preferLocal: true},
);
console.log(stdout);
} finally {
process.env.NODE_ENV = originalNodeEnv;
}
}
async function runNodeTestsWithEnv(testGroup, nodeEnv) {
const globConfig = {
ignore: ['* | test_node_all | javascript | GoogleChrome/workbox | gulp-tasks/test-node.js | https://github.com/GoogleChrome/workbox/blob/master/gulp-tasks/test-node.js | MIT |
async function test_node_clean() {
await fse.remove(upath.join(__dirname, '..', '.nyc_output'));
} | /*.{js,mjs}`,
...options,
],
{preferLocal: true},
);
console.log(stdout);
} finally {
process.env.NODE_ENV = originalNodeEnv;
}
}
async function runNodeTestsWithEnv(testGroup, nodeEnv) {
const globConfig = {
ignore: ['* | test_node_clean | javascript | GoogleChrome/workbox | gulp-tasks/test-node.js | https://github.com/GoogleChrome/workbox/blob/master/gulp-tasks/test-node.js | MIT |
async function test_node_coverage() {
const runOptions = [];
if (global.packageOrStar !== '*') {
runOptions.push('--include');
runOptions.push(upath.join('packages', global.packageOrStar, '**', '*'));
}
const {stdout} = await execa(
'nyc',
['report', '--reporter', 'lcov', '--reporter', 'text', ... | /*.{js,mjs}`,
...options,
],
{preferLocal: true},
);
console.log(stdout);
} finally {
process.env.NODE_ENV = originalNodeEnv;
}
}
async function runNodeTestsWithEnv(testGroup, nodeEnv) {
const globConfig = {
ignore: ['* | test_node_coverage | javascript | GoogleChrome/workbox | gulp-tasks/test-node.js | https://github.com/GoogleChrome/workbox/blob/master/gulp-tasks/test-node.js | MIT |
async function queueTranspile(packageName, options) {
if (!debouncedTranspilerMap[packageName]) {
debouncedTranspilerMap[packageName] = new AsyncDebounce(async () => {
await transpile_typescript();
});
}
await debouncedTranspilerMap[packageName].call();
debouncedTranspilerMap[packageName] = null;
... | Takes a package name and schedules that package's source TypeScript code
to be converted to JavaScript. If a transpilation is already scheduled, it
won't be queued twice, so this function is safe to call as frequently as
needed.
@param {string} packageName
@param {Object} [options] | queueTranspile | javascript | GoogleChrome/workbox | gulp-tasks/transpile-typescript.js | https://github.com/GoogleChrome/workbox/blob/master/gulp-tasks/transpile-typescript.js | MIT |
function needsTranspile(packageName) {
return pendingChangesMap[packageName] === true;
} | Returns true if a TypeScript file has been modified in the package since
the last time it was transpiled.
@param {string} packageName | needsTranspile | javascript | GoogleChrome/workbox | gulp-tasks/transpile-typescript.js | https://github.com/GoogleChrome/workbox/blob/master/gulp-tasks/transpile-typescript.js | MIT |
async function transpile_typescript() {
await execa('tsc', ['--build', 'tsconfig.json'], {preferLocal: true});
const jsFiles = await globby(`packages/*/**/*.js`, {
ignore: ['**/build/**', '**/src/**'],
});
for (const jsFile of jsFiles) {
const {dir, name} = upath.parse(jsFile);
const mjsFile = upa... | Transpiles all packages listed in the root tsconfig.json's references section
into .js and .d.ts files. Creates stub .mjs files that re-export the contents
of the .js files.
Unlike other scripts, this does not take the --package= command line param
into account. Each project in packages/ theoretically could depend on ... | transpile_typescript | javascript | GoogleChrome/workbox | gulp-tasks/transpile-typescript.js | https://github.com/GoogleChrome/workbox/blob/master/gulp-tasks/transpile-typescript.js | MIT |
function getPackages(typeFilter) {
return globSync(`packages/${global.packageOrStar}/package.json`, {
absolute: true,
}).filter((pathToPackageJson) => {
const pkgInfo = require(pathToPackageJson);
const packageType = pkgInfo.workbox.packageType;
if (!packageType) {
throw Error(oneLine`Unable t... | @param {string} typeFilter The type of packages to return: 'node', 'sw',
or 'all'.
@return Array<string> Paths to package.json files for the matching packages. | getPackages | javascript | GoogleChrome/workbox | gulp-tasks/utils/package-runner.js | https://github.com/GoogleChrome/workbox/blob/master/gulp-tasks/utils/package-runner.js | MIT |
generateVariantTests = (itTitle, variants, func) => {
variants.forEach((variant) => {
// We are using function() {} here and NOT ARROW FUNCTIONS
// to work with Mocha's binding for tests.
it(`${itTitle}. Variant: '${JSON.stringify(variant)}'`, function () {
// Use .call to get the correct `this` bin... | This is a helper function that will auto-generate mocha unit tests
for various inputs.
@param {string} itTitle This is the title that will be passed to the it()
function. The variant will be added to the end of this title to help
idenfity the failing test.
@param {Array<Object>} variants This should be all the variati... | generateVariantTests | javascript | GoogleChrome/workbox | infra/testing/generate-variant-tests.js | https://github.com/GoogleChrome/workbox/blob/master/infra/testing/generate-variant-tests.js | MIT |
generateVariantTests = (itTitle, variants, func) => {
variants.forEach((variant) => {
// We are using function() {} here and NOT ARROW FUNCTIONS
// to work with Mocha's binding for tests.
it(`${itTitle}. Variant: '${JSON.stringify(variant)}'`, function () {
// Use .call to get the correct `this` bin... | This is a helper function that will auto-generate mocha unit tests
for various inputs.
@param {string} itTitle This is the title that will be passed to the it()
function. The variant will be added to the end of this title to help
idenfity the failing test.
@param {Array<Object>} variants This should be all the variati... | generateVariantTests | javascript | GoogleChrome/workbox | infra/testing/generate-variant-tests.js | https://github.com/GoogleChrome/workbox/blob/master/infra/testing/generate-variant-tests.js | MIT |
executeAsyncAndCatch = async (...args) => {
const result = await webdriver.executeAsyncScript(...args);
if (result && result.error) {
console.error(result.error);
throw new Error('Error executing async script');
}
return result;
} | Executes the passed function (and args) async and logs any errors that
occur. Errors are assumed to be passed to the callback as an object
with the `error` property.
@param {...*} args
@return {*} | executeAsyncAndCatch | javascript | GoogleChrome/workbox | infra/testing/webdriver/executeAsyncAndCatch.js | https://github.com/GoogleChrome/workbox/blob/master/infra/testing/webdriver/executeAsyncAndCatch.js | MIT |
executeAsyncAndCatch = async (...args) => {
const result = await webdriver.executeAsyncScript(...args);
if (result && result.error) {
console.error(result.error);
throw new Error('Error executing async script');
}
return result;
} | Executes the passed function (and args) async and logs any errors that
occur. Errors are assumed to be passed to the callback as an object
with the `error` property.
@param {...*} args
@return {*} | executeAsyncAndCatch | javascript | GoogleChrome/workbox | infra/testing/webdriver/executeAsyncAndCatch.js | https://github.com/GoogleChrome/workbox/blob/master/infra/testing/webdriver/executeAsyncAndCatch.js | MIT |
unregisterAllSWs = async () => {
await executeAsyncAndCatch(async (cb) => {
try {
const regs = await navigator.serviceWorker.getRegistrations();
for (const reg of regs) {
await reg.unregister();
}
cb();
} catch (error) {
cb({error: error.stack});
}
});
} | Unregisters any active SWs so the next page load can start clean.
Note: a new page load is needed before controlling SWs stop being active. | unregisterAllSWs | javascript | GoogleChrome/workbox | infra/testing/webdriver/unregisterAllSWs.js | https://github.com/GoogleChrome/workbox/blob/master/infra/testing/webdriver/unregisterAllSWs.js | MIT |
unregisterAllSWs = async () => {
await executeAsyncAndCatch(async (cb) => {
try {
const regs = await navigator.serviceWorker.getRegistrations();
for (const reg of regs) {
await reg.unregister();
}
cb();
} catch (error) {
cb({error: error.stack});
}
});
} | Unregisters any active SWs so the next page load can start clean.
Note: a new page load is needed before controlling SWs stop being active. | unregisterAllSWs | javascript | GoogleChrome/workbox | infra/testing/webdriver/unregisterAllSWs.js | https://github.com/GoogleChrome/workbox/blob/master/infra/testing/webdriver/unregisterAllSWs.js | MIT |
windowLoaded = async () => {
// Wait for the window to load, so the `Workbox` global is available.
await executeAsyncAndCatch(async (cb) => {
const loaded = () => {
if (!window.Workbox) {
cb({
error: `window.Workbox is undefined; location is ${location.href}`,
});
} else {
... | Waits for the current window to load if it's not already loaded. | windowLoaded | javascript | GoogleChrome/workbox | infra/testing/webdriver/windowLoaded.js | https://github.com/GoogleChrome/workbox/blob/master/infra/testing/webdriver/windowLoaded.js | MIT |
windowLoaded = async () => {
// Wait for the window to load, so the `Workbox` global is available.
await executeAsyncAndCatch(async (cb) => {
const loaded = () => {
if (!window.Workbox) {
cb({
error: `window.Workbox is undefined; location is ${location.href}`,
});
} else {
... | Waits for the current window to load if it's not already loaded. | windowLoaded | javascript | GoogleChrome/workbox | infra/testing/webdriver/windowLoaded.js | https://github.com/GoogleChrome/workbox/blob/master/infra/testing/webdriver/windowLoaded.js | MIT |
loaded = () => {
if (!window.Workbox) {
cb({
error: `window.Workbox is undefined; location is ${location.href}`,
});
} else {
cb();
}
} | Waits for the current window to load if it's not already loaded. | loaded | javascript | GoogleChrome/workbox | infra/testing/webdriver/windowLoaded.js | https://github.com/GoogleChrome/workbox/blob/master/infra/testing/webdriver/windowLoaded.js | MIT |
loaded = () => {
if (!window.Workbox) {
cb({
error: `window.Workbox is undefined; location is ${location.href}`,
});
} else {
cb();
}
} | Waits for the current window to load if it's not already loaded. | loaded | javascript | GoogleChrome/workbox | infra/testing/webdriver/windowLoaded.js | https://github.com/GoogleChrome/workbox/blob/master/infra/testing/webdriver/windowLoaded.js | MIT |
function validate(runtimeCachingOptions, convertedOptions) {
expect(convertedOptions).to.have.lengthOf(runtimeCachingOptions.length);
const globalScope = {
workbox_cacheable_response_CacheableResponsePlugin: sinon.spy(),
workbox_expiration_ExpirationPlugin: sinon.spy(),
workbox_background_sync_Backgrou... | Validates the method calls for a given set of runtimeCachingOptions.
@private
@param {Array<Object>} runtimeCachingOptions
@param {Array<string>} convertedOptions | validate | javascript | GoogleChrome/workbox | test/workbox-build/node/lib/runtime-caching-converter.js | https://github.com/GoogleChrome/workbox/blob/master/test/workbox-build/node/lib/runtime-caching-converter.js | MIT |
messageSW = (data, done) => {
const messageChannel = new MessageChannel();
messageChannel.port1.onmessage = (evt) => done(evt.data);
navigator.serviceWorker.controller.postMessage(data, [
messageChannel.port2,
]);
} | Sends a mesage to the service worker via postMessage and invokes the
`done()` callback when the service worker responds, with any data value
passed to the event.
@param {Object} data An object to send to the service worker.
@param {Function} done The callback automatically passed via webdriver's
`executeAsyncScrip... | messageSW | javascript | GoogleChrome/workbox | test/workbox-google-analytics/integration/test-all.js | https://github.com/GoogleChrome/workbox/blob/master/test/workbox-google-analytics/integration/test-all.js | MIT |
messageSW = (data, done) => {
const messageChannel = new MessageChannel();
messageChannel.port1.onmessage = (evt) => done(evt.data);
navigator.serviceWorker.controller.postMessage(data, [
messageChannel.port2,
]);
} | Sends a mesage to the service worker via postMessage and invokes the
`done()` callback when the service worker responds, with any data value
passed to the event.
@param {Object} data An object to send to the service worker.
@param {Function} done The callback automatically passed via webdriver's
`executeAsyncScrip... | messageSW | javascript | GoogleChrome/workbox | test/workbox-google-analytics/integration/test-all.js | https://github.com/GoogleChrome/workbox/blob/master/test/workbox-google-analytics/integration/test-all.js | MIT |
async function resyncLink({ link }, response) {
if (!link) throw new Error('Invalid link provided');
try {
const { success, content = null } = await getLinkText(link);
if (!success) throw new Error(`Failed to sync link content. ${reason}`);
response.status(200).json({ success, content });
} catch (e) ... | Fetches the content of a raw link. Returns the content as a text string of the link in question.
@param {object} data - metadata from document (eg: link)
@param {import("../../middleware/setDataSigner").ResponseWithSigner} response | resyncLink | javascript | Mintplex-Labs/anything-llm | collector/extensions/resync/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/extensions/resync/index.js | MIT |
async function resyncYouTube({ link }, response) {
if (!link) throw new Error('Invalid link provided');
try {
const { fetchVideoTranscriptContent } = require("../../utils/extensions/YoutubeTranscript");
const { success, reason, content } = await fetchVideoTranscriptContent({ url: link });
if (!success) ... | Fetches the content of a YouTube link. Returns the content as a text string of the video in question.
We offer this as there may be some videos where a transcription could be manually edited after initial scraping
but in general - transcriptions often never change.
@param {object} data - metadata from document (eg: lin... | resyncYouTube | javascript | Mintplex-Labs/anything-llm | collector/extensions/resync/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/extensions/resync/index.js | MIT |
async function resyncConfluence({ chunkSource }, response) {
if (!chunkSource) throw new Error('Invalid source property provided');
try {
// Confluence data is `payload` encrypted. So we need to expand its
// encrypted payload back into query params so we can reFetch the page with same access token/params.
... | Fetches the content of a specific confluence page via its chunkSource.
Returns the content as a text string of the page in question and only that page.
@param {object} data - metadata from document (eg: chunkSource)
@param {import("../../middleware/setDataSigner").ResponseWithSigner} response | resyncConfluence | javascript | Mintplex-Labs/anything-llm | collector/extensions/resync/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/extensions/resync/index.js | MIT |
async function resyncGithub({ chunkSource }, response) {
if (!chunkSource) throw new Error('Invalid source property provided');
try {
// Github file data is `payload` encrypted (might contain PAT). So we need to expand its
// encrypted payload back into query params so we can reFetch the page with same acce... | Fetches the content of a specific confluence page via its chunkSource.
Returns the content as a text string of the page in question and only that page.
@param {object} data - metadata from document (eg: chunkSource)
@param {import("../../middleware/setDataSigner").ResponseWithSigner} response | resyncGithub | javascript | Mintplex-Labs/anything-llm | collector/extensions/resync/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/extensions/resync/index.js | MIT |
async function resyncDrupalWiki({ chunkSource }, response) {
if (!chunkSource) throw new Error('Invalid source property provided');
try {
// DrupalWiki data is `payload` encrypted. So we need to expand its
// encrypted payload back into query params so we can reFetch the page with same access token/params.
... | Fetches the content of a specific DrupalWiki page via its chunkSource.
Returns the content as a text string of the page in question and only that page.
@param {object} data - metadata from document (eg: chunkSource)
@param {import("../../middleware/setDataSigner").ResponseWithSigner} response | resyncDrupalWiki | javascript | Mintplex-Labs/anything-llm | collector/extensions/resync/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/extensions/resync/index.js | MIT |
function setDataSigner(request, response, next) {
const comKey = new CommunicationKey();
const encryptedPayloadSigner = request.header("X-Payload-Signer");
if (!encryptedPayloadSigner) console.log('Failed to find signed-payload to set encryption worker! Encryption calls will fail.');
const decryptedPayloadSign... | @param {import("express").Request} request
@param {import("express").Response} response
@param {import("express").NextFunction} next | setDataSigner | javascript | Mintplex-Labs/anything-llm | collector/middleware/setDataSigner.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/middleware/setDataSigner.js | MIT |
async function processLink(link, scraperHeaders = {}) {
if (!validURL(link)) return { success: false, reason: "Not a valid URL." };
return await scrapeGenericUrl({
link,
captureAs: "text",
processAsDocument: true,
scraperHeaders,
});
} | Process a link and return the text content. This util will save the link as a document
so it can be used for embedding later.
@param {string} link - The link to process
@param {{[key: string]: string}} scraperHeaders - Custom headers to apply when scraping the link
@returns {Promise<{success: boolean, content: string}>... | processLink | javascript | Mintplex-Labs/anything-llm | collector/processLink/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/processLink/index.js | MIT |
async function getLinkText(link, captureAs = "text") {
if (!validURL(link)) return { success: false, reason: "Not a valid URL." };
return await scrapeGenericUrl({
link,
captureAs,
processAsDocument: false,
});
} | Get the text content of a link - does not save the link as a document
Mostly used in agentic flows/tools calls to get the text content of a link
@param {string} link - The link to get the text content of
@param {('html' | 'text' | 'json')} captureAs - The format to capture the page content as
@returns {Promise<{success... | getLinkText | javascript | Mintplex-Labs/anything-llm | collector/processLink/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/processLink/index.js | MIT |
async function scrapeGenericUrl({
link,
captureAs = "text",
processAsDocument = true,
scraperHeaders = {},
}) {
console.log(`-- Working URL ${link} => (${captureAs}) --`);
const content = await getPageContent({
link,
captureAs,
headers: scraperHeaders,
});
if (!content.length) {
console... | Scrape a generic URL and return the content in the specified format
@param {Object} config - The configuration object
@param {string} config.link - The URL to scrape
@param {('html' | 'text')} config.captureAs - The format to capture the page content as. Default is 'text'
@param {boolean} config.processAsDocument - Whe... | scrapeGenericUrl | javascript | Mintplex-Labs/anything-llm | collector/processLink/convert/generic.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/processLink/convert/generic.js | MIT |
function validatedHeaders(headers = {}) {
try {
if (Object.keys(headers).length === 0) return {};
let validHeaders = {};
for (const key of Object.keys(headers)) {
if (!key?.trim()) continue;
if (typeof headers[key] !== "string" || !headers[key]?.trim()) continue;
validHeaders[key] = head... | Validate the headers object
- Keys & Values must be strings and not empty
- Assemble a new object with only the valid keys and values
@param {{[key: string]: string}} headers - The headers object to validate
@returns {{[key: string]: string}} - The validated headers object | validatedHeaders | javascript | Mintplex-Labs/anything-llm | collector/processLink/convert/generic.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/processLink/convert/generic.js | MIT |
async function getPageContent({ link, captureAs = "text", headers = {} }) {
try {
let pageContents = [];
const loader = new PuppeteerWebBaseLoader(link, {
launchOptions: {
headless: "new",
ignoreHTTPSErrors: true,
},
gotoOptions: {
waitUntil: "networkidle2",
},
... | Get the content of a page
@param {Object} config - The configuration object
@param {string} config.link - The URL to get the content of
@param {('html' | 'text')} config.captureAs - The format to capture the page content as. Default is 'text'
@param {{[key: string]: string}} config.headers - Custom headers to use when ... | getPageContent | javascript | Mintplex-Labs/anything-llm | collector/processLink/convert/generic.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/processLink/convert/generic.js | MIT |
async evaluate(page, browser) {
const result = await page.evaluate((captureAs) => {
if (captureAs === "text") return document.body.innerText;
if (captureAs === "html") return document.documentElement.innerHTML;
return document.body.innerText;
}, captureAs);
await br... | Get the content of a page
@param {Object} config - The configuration object
@param {string} config.link - The URL to get the content of
@param {('html' | 'text')} config.captureAs - The format to capture the page content as. Default is 'text'
@param {{[key: string]: string}} config.headers - Custom headers to use when ... | evaluate | javascript | Mintplex-Labs/anything-llm | collector/processLink/convert/generic.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/processLink/convert/generic.js | MIT |
expandPayload(chunkSource = "") {
try {
const url = new URL(chunkSource);
if (!url.searchParams.has("payload")) return url;
const decryptedPayload = this.decrypt(url.searchParams.get("payload"));
const encodedParams = JSON.parse(decryptedPayload);
url.searchParams.delete("payload"); /... | Give a chunk source, parse its payload query param and expand that object back into the URL
as additional query params
@param {string} chunkSource
@returns {URL} Javascript URL object with query params decrypted from payload query param. | expandPayload | javascript | Mintplex-Labs/anything-llm | collector/utils/EncryptionWorker/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/EncryptionWorker/index.js | MIT |
encrypt(plainTextString = null) {
try {
if (!plainTextString)
throw new Error("Empty string is not valid for this method.");
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(this.algorithm, this.key, iv);
const encrypted = cipher.update(plainTextString, "utf8",... | Give a chunk source, parse its payload query param and expand that object back into the URL
as additional query params
@param {string} chunkSource
@returns {URL} Javascript URL object with query params decrypted from payload query param. | encrypt | javascript | Mintplex-Labs/anything-llm | collector/utils/EncryptionWorker/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/EncryptionWorker/index.js | MIT |
decrypt(encryptedString) {
try {
const [encrypted, iv] = encryptedString.split(this.separator);
if (!iv) throw new Error("IV not found");
const decipher = crypto.createDecipheriv(
this.algorithm,
this.key,
Buffer.from(iv, "hex")
);
return decipher.update(encrypt... | Give a chunk source, parse its payload query param and expand that object back into the URL
as additional query params
@param {string} chunkSource
@returns {URL} Javascript URL object with query params decrypted from payload query param. | decrypt | javascript | Mintplex-Labs/anything-llm | collector/utils/EncryptionWorker/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/EncryptionWorker/index.js | MIT |
async function loadConfluence(
{
baseUrl = null,
spaceKey = null,
username = null,
accessToken = null,
cloud = true,
personalAccessToken = null,
},
response
) {
if (!personalAccessToken && (!username || !accessToken)) {
return {
success: false,
reason:
"You need e... | Load Confluence documents from a spaceID and Confluence credentials
@param {object} args - forwarded request body params
@param {import("../../../middleware/setDataSigner").ResponseWithSigner} response - Express response object with encryptionWorker
@returns | loadConfluence | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/Confluence/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/Confluence/index.js | MIT |
async function fetchConfluencePage({
pageUrl,
baseUrl,
spaceKey,
username,
accessToken,
cloud = true,
}) {
if (!pageUrl || !baseUrl || !spaceKey || !username || !accessToken) {
return {
success: false,
content: null,
reason:
"You need either a username and access token, or a ... | Gets the page content from a specific Confluence page, not all pages in a workspace.
@returns | fetchConfluencePage | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/Confluence/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/Confluence/index.js | MIT |
function validBaseUrl(baseUrl) {
try {
new URL(baseUrl);
return true;
} catch (e) {
return false;
}
} | Validates if the provided baseUrl is a valid URL at all.
@param {string} baseUrl
@returns {boolean} | validBaseUrl | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/Confluence/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/Confluence/index.js | MIT |
function generateChunkSource(
{ doc, baseUrl, spaceKey, accessToken, username, cloud },
encryptionWorker
) {
const payload = {
baseUrl,
spaceKey,
token: accessToken,
username,
cloud,
};
return `confluence://${doc.metadata.url}?payload=${encryptionWorker.encrypt(
JSON.stringify(payload)... | Generate the full chunkSource for a specific Confluence page so that we can resync it later.
This data is encrypted into a single `payload` query param so we can replay credentials later
since this was encrypted with the systems persistent password and salt.
@param {object} chunkSourceInformation
@param {import("../../... | generateChunkSource | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/Confluence/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/Confluence/index.js | MIT |
async function loadPage({ baseUrl, pageId, accessToken }) {
console.log(`-- Working Drupal Wiki Page ${pageId} of ${baseUrl} --`);
const drupalWiki = new DrupalWiki({ baseUrl, accessToken });
try {
const page = await drupalWiki.loadPage(pageId);
return {
success: true,
reason: null,
cont... | Gets the page content from a specific Confluence page, not all pages in a workspace.
@returns | loadPage | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/DrupalWiki/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/DrupalWiki/index.js | MIT |
constructor({ id, title, created, type, processedBody, url, spaceId }) {
this.id = id;
this.title = title;
this.url = url;
this.created = created;
this.type = type;
this.processedBody = processedBody;
this.spaceId = spaceId;
} | @param {number }id
@param {string }title
@param {string} created
@param {string} type
@param {string} processedBody
@param {string} url
@param {number} spaceId | constructor | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/DrupalWiki/DrupalWiki/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/DrupalWiki/DrupalWiki/index.js | MIT |
constructor({ baseUrl, accessToken }) {
this.baseUrl = baseUrl;
this.accessToken = accessToken;
this.storagePath = this.#prepareStoragePath(baseUrl);
} | @param baseUrl
@param spaceId
@param accessToken | constructor | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/DrupalWiki/DrupalWiki/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/DrupalWiki/DrupalWiki/index.js | MIT |
async loadAndStoreAllPagesForSpace(spaceId, encryptionWorker) {
const pageIndex = await this.#getPageIndexForSpace(spaceId);
for (const pageId of pageIndex) {
try {
const page = await this.loadPage(pageId);
// Pages with an empty body will lead to embedding issues / exceptions
if ... | Load all pages for the given space, fetching storing each page one by one
to minimize the memory usage
@param {number} spaceId
@param {import("../../EncryptionWorker").EncryptionWorker} encryptionWorker
@returns {Promise<void>} | loadAndStoreAllPagesForSpace | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/DrupalWiki/DrupalWiki/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/DrupalWiki/DrupalWiki/index.js | MIT |
async loadPage(pageId) {
return this.#fetchPage(pageId);
} | @param {number} pageId
@returns {Promise<Page>} | loadPage | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/DrupalWiki/DrupalWiki/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/DrupalWiki/DrupalWiki/index.js | MIT |
async _doFetch(url) {
const response = await fetch(url, {
headers: this.#getHeaders(),
});
if (!response.ok) {
throw new Error(`Failed to fetch ${url}: ${response.status}`);
}
return response.json();
} | Generate the full chunkSource for a specific Confluence page so that we can resync it later.
This data is encrypted into a single `payload` query param so we can replay credentials later
since this was encrypted with the systems persistent password and salt.
@param {number} pageId
@param {import("../../EncryptionWorker... | _doFetch | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/DrupalWiki/DrupalWiki/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/DrupalWiki/DrupalWiki/index.js | MIT |
function resolveRepoLoader(platform = "github") {
switch (platform) {
case "github":
console.log(`Loading GitHub RepoLoader...`);
return require("./GithubRepo/RepoLoader");
case "gitlab":
console.log(`Loading GitLab RepoLoader...`);
return require("./GitlabRepo/RepoLoader");
defaul... | Dynamically load the correct repository loader from a specific platform
by default will return GitHub.
@param {('github'|'gitlab')} platform
@returns {import("./GithubRepo/RepoLoader")|import("./GitlabRepo/RepoLoader")} the repo loader class for provider | resolveRepoLoader | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/index.js | MIT |
function resolveRepoLoaderFunction(platform = "github") {
switch (platform) {
case "github":
console.log(`Loading GitHub loader function...`);
return require("./GithubRepo").loadGithubRepo;
case "gitlab":
console.log(`Loading GitLab loader function...`);
return require("./GitlabRepo").... | Dynamically load the correct repository loader function from a specific platform
by default will return Github.
@param {('github'|'gitlab')} platform
@returns {import("./GithubRepo")['fetchGithubFile'] | import("./GitlabRepo")['fetchGitlabFile']} the repo loader class for provider | resolveRepoLoaderFunction | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/index.js | MIT |
async function loadGithubRepo(args, response) {
const repo = new RepoLoader(args);
await repo.init();
if (!repo.ready)
return {
success: false,
reason: "Could not prepare GitHub repo for loading! Check URL",
};
console.log(
`-- Working GitHub ${repo.author}/${repo.project}:${repo.branc... | Load in a GitHub Repo recursively or just the top level if no PAT is provided
@param {object} args - forwarded request body params
@param {import("../../../middleware/setDataSigner").ResponseWithSigner} response - Express response object with encryptionWorker
@returns | loadGithubRepo | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GithubRepo/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GithubRepo/index.js | MIT |
async function fetchGithubFile({
repoUrl,
branch,
accessToken = null,
sourceFilePath,
}) {
const repo = new RepoLoader({
repo: repoUrl,
branch,
accessToken,
});
await repo.init();
if (!repo.ready)
return {
success: false,
content: null,
reason: "Could not prepare GitHu... | Gets the page content from a specific source file in a give GitHub Repo, not all items in a repo.
@returns | fetchGithubFile | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GithubRepo/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GithubRepo/index.js | MIT |
function generateChunkSource(repo, doc, encryptionWorker) {
const payload = {
owner: repo.author,
project: repo.project,
branch: repo.branch,
path: doc.metadata.source,
pat: !!repo.accessToken ? repo.accessToken : null,
};
return `github://${repo.repo}?payload=${encryptionWorker.encrypt(
J... | Generate the full chunkSource for a specific file so that we can resync it later.
This data is encrypted into a single `payload` query param so we can replay credentials later
since this was encrypted with the systems persistent password and salt.
@param {RepoLoader} repo
@param {import("@langchain/core/documents").Doc... | generateChunkSource | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GithubRepo/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GithubRepo/index.js | MIT |
constructor(args = {}) {
this.ready = false;
this.repo = this.#processRepoUrl(args?.repo);
this.branch = args?.branch;
this.accessToken = args?.accessToken || null;
this.ignorePaths = args?.ignorePaths || [];
this.author = null;
this.project = null;
this.branches = [];
} | Creates an instance of RepoLoader.
@param {RepoLoaderArgs} [args] - The configuration options.
@returns {GitHubRepoLoader} | constructor | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GithubRepo/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GithubRepo/RepoLoader/index.js | MIT |
async init() {
if (!this.#validGithubUrl()) return;
await this.#validBranch();
await this.#validateAccessToken();
this.ready = true;
return this;
} | Initializes the RepoLoader instance.
@returns {Promise<RepoLoader>} The initialized RepoLoader instance. | init | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GithubRepo/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GithubRepo/RepoLoader/index.js | MIT |
async recursiveLoader() {
if (!this.ready) throw new Error("[GitHub Loader]: not in ready state!");
const {
GithubRepoLoader: LCGithubLoader,
} = require("@langchain/community/document_loaders/web/github");
if (this.accessToken)
console.log(
`[GitHub Loader]: Access token set! Recur... | Recursively loads the repository content.
@returns {Promise<Array<Object>>} An array of loaded documents.
@throws {Error} If the RepoLoader is not in a ready state. | recursiveLoader | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GithubRepo/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GithubRepo/RepoLoader/index.js | MIT |
async getRepoBranches() {
if (!this.#validGithubUrl() || !this.author || !this.project) return [];
await this.#validateAccessToken(); // Ensure API access token is valid for pre-flight
let page = 0;
let polling = true;
const branches = [];
while (polling) {
console.log(`Fetching page ${p... | Retrieves all branches for the repository.
@returns {Promise<string[]>} An array of branch names. | getRepoBranches | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GithubRepo/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GithubRepo/RepoLoader/index.js | MIT |
async fetchSingleFile(sourceFilePath) {
try {
return fetch(
`https://api.github.com/repos/${this.author}/${this.project}/contents/${sourceFilePath}?ref=${this.branch}`,
{
method: "GET",
headers: {
Accept: "application/vnd.github+json",
"X-GitHub-Api-... | Fetches the content of a single file from the repository.
@param {string} sourceFilePath - The path to the file in the repository.
@returns {Promise<string|null>} The content of the file, or null if fetching fails. | fetchSingleFile | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GithubRepo/RepoLoader/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GithubRepo/RepoLoader/index.js | MIT |
async function loadGitlabRepo(args, response) {
const repo = new RepoLoader(args);
await repo.init();
if (!repo.ready)
return {
success: false,
reason: "Could not prepare Gitlab repo for loading! Check URL",
};
console.log(
`-- Working GitLab ${repo.author}/${repo.project}:${repo.branc... | Load in a Gitlab Repo recursively or just the top level if no PAT is provided
@param {object} args - forwarded request body params
@param {import("../../../middleware/setDataSigner").ResponseWithSigner} response - Express response object with encryptionWorker
@returns | loadGitlabRepo | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GitlabRepo/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GitlabRepo/index.js | MIT |
async function fetchGitlabFile({
repoUrl,
branch,
accessToken = null,
sourceFilePath,
}) {
const repo = new RepoLoader({
repo: repoUrl,
branch,
accessToken,
});
await repo.init();
if (!repo.ready)
return {
success: false,
content: null,
reason: "Could not prepare GitLa... | Load in a Gitlab Repo recursively or just the top level if no PAT is provided
@param {object} args - forwarded request body params
@param {import("../../../middleware/setDataSigner").ResponseWithSigner} response - Express response object with encryptionWorker
@returns | fetchGitlabFile | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GitlabRepo/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GitlabRepo/index.js | MIT |
function generateChunkSource(repo, doc, encryptionWorker) {
const payload = {
projectId: decodeURIComponent(repo.projectId),
branch: repo.branch,
path: doc.metadata.source,
pat: !!repo.accessToken ? repo.accessToken : null,
};
return `gitlab://${repo.repo}?payload=${encryptionWorker.encrypt(
J... | Load in a Gitlab Repo recursively or just the top level if no PAT is provided
@param {object} args - forwarded request body params
@param {import("../../../middleware/setDataSigner").ResponseWithSigner} response - Express response object with encryptionWorker
@returns | generateChunkSource | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GitlabRepo/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GitlabRepo/index.js | MIT |
function issueToMarkdown(issue) {
const metadata = {};
const userFields = ["author", "assignees", "closed_by"];
const userToUsername = ({ username }) => username;
for (const userField of userFields) {
if (issue[userField]) {
if (Array.isArray(issue[userField])) {
metadata[userField] = issue[u... | Load in a Gitlab Repo recursively or just the top level if no PAT is provided
@param {object} args - forwarded request body params
@param {import("../../../middleware/setDataSigner").ResponseWithSigner} response - Express response object with encryptionWorker
@returns | issueToMarkdown | javascript | Mintplex-Labs/anything-llm | collector/utils/extensions/RepoLoader/GitlabRepo/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/collector/utils/extensions/RepoLoader/GitlabRepo/index.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.