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 gl.compileShader(shader); // Check the compile status const compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled) { // Something went wrong during compilation; get the error const lastError = gl.getShaderInfoLog(shader); errFn('*** Error compiling shader \'' + shader + '\':' + lastError + `\n` + shaderSource.split('\n').map((l,i) => `${i + 1}: ${l}`).join('\n')); gl.deleteShader(shader); return null; } return 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 the. A parallel array to opt_attribs letting you assign locations. @param {module:webgl-utils.ErrorCallback} opt_errorCallback callback for errors. By default it just prints an error to the console on error. If you want something else pass an callback. It's passed an error message. @memberOf module:webgl-utils
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_attribs.forEach(function(attrib, ndx) { gl.bindAttribLocation( program, opt_locations ? opt_locations[ndx] : ndx, attrib); }); } gl.linkProgram(program); // Check the link status const linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { // something went wrong with the link const lastError = gl.getProgramInfoLog(program); errFn('Error in program linking:' + lastError); gl.deleteProgram(program); return null; } return program; }
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} opt_errorCallback callback for errors. @return {WebGLShader} The created shader.
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); } shaderSource = shaderScript.text; if (!opt_shaderType) { if (shaderScript.type === 'x-shader/x-vertex') { shaderType = gl.VERTEX_SHADER; } else if (shaderScript.type === 'x-shader/x-fragment') { shaderType = gl.FRAGMENT_SHADER; } else if (shaderType !== gl.VERTEX_SHADER && shaderType !== gl.FRAGMENT_SHADER) { throw ('*** Error: unknown shader type'); } } return loadShader( gl, shaderSource, opt_shaderType ? opt_shaderType : shaderType, opt_errorCallback); }
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] An array of attribs names. Locations will be assigned by index if not passed in @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations. @param {module:webgl-utils.ErrorCallback} opt_errorCallback callback for errors. By default it just prints an error to the console on error. If you want something else pass an callback. It's passed an error message. @return {WebGLProgram} The created program. @memberOf module:webgl-utils
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_errorCallback)); } return createProgram(gl, shaders, opt_attribs, opt_locations, opt_errorCallback); }
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)); } return createProgram(gl, shaders, opt_attribs, opt_locations, 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 created setter. */ 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 === gl.FLOAT && isArray) { return function(v) { gl.uniform1fv(location, v); }; } if (type === gl.FLOAT) { return function(v) { gl.uniform1f(location, v); }; } if (type === gl.FLOAT_VEC2) { return function(v) { gl.uniform2fv(location, v); }; } if (type === gl.FLOAT_VEC3) { return function(v) { gl.uniform3fv(location, v); }; } if (type === gl.FLOAT_VEC4) { return function(v) { gl.uniform4fv(location, v); }; } if (type === gl.INT && isArray) { return function(v) { gl.uniform1iv(location, v); }; } if (type === gl.INT) { return function(v) { gl.uniform1i(location, v); }; } if (type === gl.INT_VEC2) { return function(v) { gl.uniform2iv(location, v); }; } if (type === gl.INT_VEC3) { return function(v) { gl.uniform3iv(location, v); }; } if (type === gl.INT_VEC4) { return function(v) { gl.uniform4iv(location, v); }; } if (type === gl.BOOL) { return function(v) { gl.uniform1iv(location, v); }; } if (type === gl.BOOL_VEC2) { return function(v) { gl.uniform2iv(location, v); }; } if (type === gl.BOOL_VEC3) { return function(v) { gl.uniform3iv(location, v); }; } if (type === gl.BOOL_VEC4) { return function(v) { gl.uniform4iv(location, v); }; } if (type === gl.FLOAT_MAT2) { return function(v) { gl.uniformMatrix2fv(location, false, v); }; } if (type === gl.FLOAT_MAT3) { return function(v) { gl.uniformMatrix3fv(location, false, v); }; } if (type === gl.FLOAT_MAT4) { return function(v) { gl.uniformMatrix4fv(location, false, v); }; } if ((type === gl.SAMPLER_2D || type === gl.SAMPLER_CUBE) && isArray) { const units = []; for (let ii = 0; ii < info.size; ++ii) { units.push(textureUnit++); } return function(bindPoint, units) { return function(textures) { gl.uniform1iv(location, units); textures.forEach(function(texture, index) { gl.activeTexture(gl.TEXTURE0 + units[index]); gl.bindTexture(bindPoint, texture); }); }; }(getBindPointForSamplerType(gl, type), units); } if (type === gl.SAMPLER_2D || type === gl.SAMPLER_CUBE) { return function(bindPoint, unit) { return function(texture) { gl.uniform1i(location, unit); gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(bindPoint, texture); }; }(getBindPointForSamplerType(gl, type), textureUnit++); } throw ('unknown type: 0x' + type.toString(16)); // we should never get here. } const uniformSetters = { }; const numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); for (let ii = 0; ii < numUniforms; ++ii) { const uniformInfo = gl.getActiveUniform(program, ii); if (!uniformInfo) { break; } let name = uniformInfo.name; // remove the array suffix. if (name.substr(-3) === '[0]') { name = name.substr(0, name.length - 3); } const setter = createUniformSetter(program, uniformInfo); uniformSetters[name] = setter; } return uniformSetters; }
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 === gl.FLOAT && isArray) { return function(v) { gl.uniform1fv(location, v); }; } if (type === gl.FLOAT) { return function(v) { gl.uniform1f(location, v); }; } if (type === gl.FLOAT_VEC2) { return function(v) { gl.uniform2fv(location, v); }; } if (type === gl.FLOAT_VEC3) { return function(v) { gl.uniform3fv(location, v); }; } if (type === gl.FLOAT_VEC4) { return function(v) { gl.uniform4fv(location, v); }; } if (type === gl.INT && isArray) { return function(v) { gl.uniform1iv(location, v); }; } if (type === gl.INT) { return function(v) { gl.uniform1i(location, v); }; } if (type === gl.INT_VEC2) { return function(v) { gl.uniform2iv(location, v); }; } if (type === gl.INT_VEC3) { return function(v) { gl.uniform3iv(location, v); }; } if (type === gl.INT_VEC4) { return function(v) { gl.uniform4iv(location, v); }; } if (type === gl.BOOL) { return function(v) { gl.uniform1iv(location, v); }; } if (type === gl.BOOL_VEC2) { return function(v) { gl.uniform2iv(location, v); }; } if (type === gl.BOOL_VEC3) { return function(v) { gl.uniform3iv(location, v); }; } if (type === gl.BOOL_VEC4) { return function(v) { gl.uniform4iv(location, v); }; } if (type === gl.FLOAT_MAT2) { return function(v) { gl.uniformMatrix2fv(location, false, v); }; } if (type === gl.FLOAT_MAT3) { return function(v) { gl.uniformMatrix3fv(location, false, v); }; } if (type === gl.FLOAT_MAT4) { return function(v) { gl.uniformMatrix4fv(location, false, v); }; } if ((type === gl.SAMPLER_2D || type === gl.SAMPLER_CUBE) && isArray) { const units = []; for (let ii = 0; ii < info.size; ++ii) { units.push(textureUnit++); } return function(bindPoint, units) { return function(textures) { gl.uniform1iv(location, units); textures.forEach(function(texture, index) { gl.activeTexture(gl.TEXTURE0 + units[index]); gl.bindTexture(bindPoint, texture); }); }; }(getBindPointForSamplerType(gl, type), units); } if (type === gl.SAMPLER_2D || type === gl.SAMPLER_CUBE) { return function(bindPoint, unit) { return function(texture) { gl.uniform1i(location, unit); gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(bindPoint, texture); }; }(getBindPointForSamplerType(gl, type), textureUnit++); } throw ('unknown type: 0x' + type.toString(16)); // we should never get here. }
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.<string, function>} an object with a setter for each attribute by name. @memberOf module:webgl-utils
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: gl.vertexAttrib4fv(index, b.value); break; case 3: gl.vertexAttrib3fv(index, b.value); break; case 2: gl.vertexAttrib2fv(index, b.value); break; case 1: gl.vertexAttrib1fv(index, b.value); break; default: throw new Error('the length of a float constant value must be between 1 and 4!'); } } else { gl.bindBuffer(gl.ARRAY_BUFFER, b.buffer); gl.enableVertexAttribArray(index); gl.vertexAttribPointer( index, b.numComponents || b.size, b.type || gl.FLOAT, b.normalize || false, b.stride || 0, b.offset || 0); } }; } const numAttribs = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); for (let ii = 0; ii < numAttribs; ++ii) { const attribInfo = gl.getActiveAttrib(program, ii); if (!attribInfo) { break; } const index = gl.getAttribLocation(program, attribInfo.name); attribSetters[attribInfo.name] = createAttribSetter(index); } return attribSetters; }
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.<string, function>} an object with a setter for each attribute by name. @memberOf module:webgl-utils
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: gl.vertexAttrib3fv(index, b.value); break; case 2: gl.vertexAttrib2fv(index, b.value); break; case 1: gl.vertexAttrib1fv(index, b.value); break; default: throw new Error('the length of a float constant value must be between 1 and 4!'); } } else { gl.bindBuffer(gl.ARRAY_BUFFER, b.buffer); gl.enableVertexAttribArray(index); gl.vertexAttribPointer( index, b.numComponents || b.size, b.type || gl.FLOAT, b.normalize || false, b.stride || 0, b.offset || 0); } }; }
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.<string, function>} an object with a setter for each attribute by name. @memberOf module:webgl-utils
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 @param {module:webgl-utils:BufferInfo} bufferInfo BufferInfo as returned from createBufferInfoFromArrays etc... @param {WebGLBuffer} [indices] an optional ELEMENT_ARRAY_BUFFER of indices
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 to ELEMENT_ARRAY_BUFFER // like when creating buffers for other stuff will mess up this VAO's binding gl.bindVertexArray(null); return vao; }
@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-utils
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 WebGLRenderingContext to use. @param {string[]} shaderSourcess Array of sources for the shaders or ids. The first is assumed to be the vertex shader, the second the fragment shader. @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 the. A parallel array to opt_attribs letting you assign locations. @param {module:webgl-utils.ErrorCallback} opt_errorCallback callback for errors. By default it just prints an error to the console on error. If you want something else pass an callback. It's passed an error message. @return {module:webgl-utils.ProgramInfo} The created program. @memberOf module:webgl-utils
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.createProgramFromSources(gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback); if (!program) { return null; } const uniformSetters = createUniformSetters(gl, program); const attribSetters = createAttributeSetters(gl, program); return { program: program, uniformSetters: uniformSetters, attribSetters: attribSetters, }; }
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 WebGLRenderingContext to use. @param {string[]} shaderSourcess Array of sources for the shaders or ids. The first is assumed to be the vertex shader, the second the fragment shader. @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 the. A parallel array to opt_attribs letting you assign locations. @param {module:webgl-utils.ErrorCallback} opt_errorCallback callback for errors. By default it just prints an error to the console on error. If you want something else pass an callback. It's passed an error message. @return {module:webgl-utils.ProgramInfo} The created program. @memberOf module:webgl-utils
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; canvas.height = height; return true; } return false; }
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)) { for (let jj = 0; jj < value.length; ++jj) { typedArray[cursor++] = value[jj]; } } else { typedArray[cursor++] = value; } } }; typedArray.reset = function(opt_index) { cursor = opt_index || 0; }; typedArray.numComponents = numComponents; Object.defineProperty(typedArray, 'numElements', { get: function() { return this.length / this.numComponents | 0; }, }); return typedArray; }
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 array.push(1, 2, 3); array.push([4, 5, 6]); // array now contains [1, 2, 3, 4, 5, 6] Also has `numComponents` and `numElements` properties. @param {number} numComponents number of components @param {number} numElements number of elements. The total size of the array will be `numComponents * numElements`. @param {constructor} opt_type A constructor for the type. Default = `Float32Array`. @return {ArrayBuffer} A typed array. @memberOf module:webgl-utils
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 array.push(1, 2, 3); array.push([4, 5, 6]); // array now contains [1, 2, 3, 4, 5, 6] Also has `numComponents` and `numElements` properties. @param {number} numComponents number of components @param {number} numElements number of elements. The total size of the array will be `numComponents * numElements`. @param {constructor} opt_type A constructor for the type. Default = `Float32Array`. @return {ArrayBuffer} A typed array. @memberOf module:webgl-utils
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 array.push(1, 2, 3); array.push([4, 5, 6]); // array now contains [1, 2, 3, 4, 5, 6] Also has `numComponents` and `numElements` properties. @param {number} numComponents number of components @param {number} numElements number of elements. The total size of the array will be `numComponents * numElements`. @param {constructor} opt_type A constructor for the type. Default = `Float32Array`. @return {ArrayBuffer} A typed array. @memberOf module:webgl-utils
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 array.push(1, 2, 3); array.push([4, 5, 6]); // array now contains [1, 2, 3, 4, 5, 6] Also has `numComponents` and `numElements` properties. @param {number} numComponents number of components @param {number} numElements number of elements. The total size of the array will be `numComponents * numElements`. @param {constructor} opt_type A constructor for the type. Default = `Float32Array`. @return {ArrayBuffer} A typed array. @memberOf module:webgl-utils
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 array.push(1, 2, 3); array.push([4, 5, 6]); // array now contains [1, 2, 3, 4, 5, 6] Also has `numComponents` and `numElements` properties. @param {number} numComponents number of components @param {number} numElements number of elements. The total size of the array will be `numComponents * numElements`. @param {constructor} opt_type A constructor for the type. Default = `Float32Array`. @return {ArrayBuffer} A typed array. @memberOf module:webgl-utils
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; } // eslint-disable-line if (typedArray instanceof Uint16Array) { return gl.UNSIGNED_SHORT; } // eslint-disable-line if (typedArray instanceof Int32Array) { return gl.INT; } // eslint-disable-line if (typedArray instanceof Uint32Array) { return gl.UNSIGNED_INT; } // eslint-disable-line if (typedArray instanceof Float32Array) { return gl.FLOAT; } // eslint-disable-line throw 'unsupported typed array type'; }
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 array.push(1, 2, 3); array.push([4, 5, 6]); // array now contains [1, 2, 3, 4, 5, 6] Also has `numComponents` and `numElements` properties. @param {number} numComponents number of components @param {number} numElements number of elements. The total size of the array will be `numComponents * numElements`. @param {constructor} opt_type A constructor for the type. Default = `Float32Array`. @return {ArrayBuffer} A typed array. @memberOf module:webgl-utils
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 array.push(1, 2, 3); array.push([4, 5, 6]); // array now contains [1, 2, 3, 4, 5, 6] Also has `numComponents` and `numElements` properties. @param {number} numComponents number of components @param {number} numElements number of elements. The total size of the array will be `numComponents * numElements`. @param {constructor} opt_type A constructor for the type. Default = `Float32Array`. @return {ArrayBuffer} A typed array. @memberOf module:webgl-utils
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 array.push(1, 2, 3); array.push([4, 5, 6]); // array now contains [1, 2, 3, 4, 5, 6] Also has `numComponents` and `numElements` properties. @param {number} numComponents number of components @param {number} numElements number of elements. The total size of the array will be `numComponents * numElements`. @param {constructor} opt_type A constructor for the type. Default = `Float32Array`. @return {ArrayBuffer} A typed array. @memberOf module:webgl-utils
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 (length % numComponents > 0) { throw 'can not guess numComponents. You should specify it.'; } return 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 array.push(1, 2, 3); array.push([4, 5, 6]); // array now contains [1, 2, 3, 4, 5, 6] Also has `numComponents` and `numElements` properties. @param {number} numComponents number of components @param {number} numElements number of elements. The total size of the array will be `numComponents * numElements`. @param {constructor} opt_type A constructor for the type. Default = `Float32Array`. @return {ArrayBuffer} A typed array. @memberOf module:webgl-utils
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.numComponents) { array.numComponents = guessNumComponentsFromName(name, array.length); } let type = array.type; if (!type) { if (name === 'indices') { type = Uint16Array; } } const typedArray = createAugmentedTypedArray(array.numComponents, array.data.length / array.numComponents | 0, type); typedArray.push(array.data); return typedArray; }
@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} [normalized] whether or not to normalize the data. Default = false @property {number} [offset] offset into buffer in bytes. Default = 0 @property {number} [stride] the stride in bytes per element. Default = 0 @property {WebGLBuffer} buffer the buffer that contains the data for this attribute @memberOf module:webgl-utils
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.value) { attribs[attribName] = { value: origArray.value, }; } else { const array = makeTypedArray(origArray, bufferName); attribs[attribName] = { buffer: createBufferFromTypedArray(gl, array), numComponents: origArray.numComponents || array.numComponents || guessNumComponentsFromName(bufferName), type: getGLTypeForTypedArray(gl, array), normalize: getNormalizationForTypedArray(array), }; } }); return attribs; }
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 % numComponents > 0) { throw new Error(`Can not guess numComponents for attribute '${name}'. Tried ${numComponents} but ${length} values is not evenly divisible by ${numComponents}. You should specify it.`); } return numComponents; }
@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 `setAttributes` @memberOf module:webgl-utils
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 `setAttributes` @memberOf module:webgl-utils
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 numComponents = getNumComponents(array, key); const numElements = length / numComponents; if (length % numComponents > 0) { throw new Error(`numComponents ${numComponents} not correct for length ${length}`); } return numElements; }
@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 `setAttributes` @memberOf module:webgl-utils
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 = createBufferFromTypedArray(gl, indices, gl.ELEMENT_ARRAY_BUFFER); bufferInfo.numElements = indices.length; } else { bufferInfo.numElements = getNumElementsFromNonIndexedArrays(arrays); } return bufferInfo; }
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_BUFFER. @param {WebGLRenderingContext} gl A WebGLRenderingContext. @param {Object<string, array|typedarray>} arrays @return {Object<string, WebGLBuffer>} returns an object with one WebGLBuffer per array @memberOf module:webgl-utils
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 : offset; if (indices) { gl.drawElements(primitiveType, numElements, gl.UNSIGNED_SHORT, offset); } else { gl.drawArrays(primitiveType, offset, numElements); } }
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 (programInfo !== lastUsedProgramInfo) { lastUsedProgramInfo = programInfo; gl.useProgram(programInfo.program); bindBuffers = true; } // Setup all the needed attributes. if (bindBuffers || bufferInfo !== lastUsedBufferInfo) { lastUsedBufferInfo = bufferInfo; setBuffersAndAttributes(gl, programInfo.attribSetters, bufferInfo); } // Set the uniforms. setUniforms(programInfo.uniformSetters, object.uniforms); // Draw drawBufferInfo(gl, bufferInfo); }); }
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', ...runOptions], {preferLocal: true}, ); console.log(stdout); }
/*.{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 = upath.join(dir, `${name}.mjs`); const mjsSource = `export * from './${name}.js';`; await fse.outputFile(mjsFile, mjsSource); } }
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 any other project, so kicking off a single, top-level compilation makes the most sense (and is faster when all the packages need to be compiled).
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 to determine package type. Please add workbox.packageType metadata to ${pathToPackageJson}`); } return typeFilter === 'all' || typeFilter === packageType; }); }
@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` binding needed by mocha. // eslint-disable-next-line no-invalid-this return func.call(this, variant); }); }); }
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 variations of the test you wish to generate. @param {VariantCallback} func This is the function that will be called, with a variant as the only argument. This function should perform the desired test.
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` binding needed by mocha. // eslint-disable-next-line no-invalid-this return func.call(this, variant); }); }); }
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 variations of the test you wish to generate. @param {VariantCallback} func This is the function that will be called, with a variant as the only argument. This function should perform the desired test.
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 { cb(); } }; try { if (document.readyState === 'complete') { loaded(); } else { addEventListener('load', () => loaded()); } } catch (error) { cb({error: error.stack}); } }); }
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 { cb(); } }; try { if (document.readyState === 'complete') { loaded(); } else { addEventListener('load', () => loaded()); } } catch (error) { cb({error: error.stack}); } }); }
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_BackgroundSyncPlugin: sinon.spy(), workbox_broadcast_update_BroadcastUpdatePlugin: sinon.spy(), workbox_precaching_PrecacheFallbackPlugin: sinon.spy(), workbox_range_requests_RangeRequestsPlugin: sinon.spy(), workbox_routing_registerRoute: sinon.spy(), workbox_strategies_CacheFirst: sinon.spy(), workbox_strategies_CacheOnly: sinon.spy(), workbox_strategies_NetworkFirst: sinon.spy(), workbox_strategies_NetworkOnly: sinon.spy(), workbox_strategies_StaleWhileRevalidate: sinon.spy(), }; // Make it easier to find the right spy given a handler name. const handlerMapping = { CacheFirst: globalScope.workbox_strategies_CacheFirst, CacheOnly: globalScope.workbox_strategies_CacheOnly, NetworkFirst: globalScope.workbox_strategies_NetworkFirst, NetworkOnly: globalScope.workbox_strategies_NetworkOnly, StaleWhileRevalidate: globalScope.workbox_strategies_StaleWhileRevalidate, }; const script = new vm.Script(convertedOptions.join('\n')); script.runInNewContext(globalScope); runtimeCachingOptions.forEach((runtimeCachingOption, i) => { const registerRouteCall = globalScope.workbox_routing_registerRoute.getCall(i); expect(registerRouteCall.args[0]).to.eql(runtimeCachingOption.urlPattern); if (runtimeCachingOption.method) { expect(registerRouteCall.args[2]).to.eql(runtimeCachingOption.method); } else { expect(registerRouteCall.args[2]).to.eql('GET'); } if (typeof runtimeCachingOption.handler === 'function') { // We can't make assumptions about what custom function handlers will do. return; } // This validation assumes that there's only going to be one call to each // named strategy per test. const strategiesCall = handlerMapping[runtimeCachingOption.handler].firstCall; const strategiesOptions = strategiesCall.args[0]; if (runtimeCachingOption.options) { const options = runtimeCachingOption.options; if (options.networkTimeoutSeconds) { expect(options.networkTimeoutSeconds).to.eql( strategiesOptions.networkTimeoutSeconds, ); } if (options.cacheName) { expect(options.cacheName).to.eql(strategiesOptions.cacheName); } if (options.fetchOptions) { expect(options.fetchOptions).to.deep.eql( strategiesOptions.fetchOptions, ); } if (options.matchOptions) { expect(options.matchOptions).to.deep.eql( strategiesOptions.matchOptions, ); } if (Object.keys(options.expiration).length > 0) { expect( globalScope.workbox_expiration_ExpirationPlugin.calledWith( options.expiration, ), ).to.be.true; } if (options.cacheableResponse) { expect( globalScope.workbox_cacheable_response_CacheableResponsePlugin.calledWith( options.cacheableResponse, ), ).to.be.true; } if (options.precacheFallback) { expect( globalScope.workbox_precaching_PrecacheFallbackPlugin.calledWith( options.precacheFallback, ), ).to.be.true; } if (options.rangeRequests) { expect( globalScope.workbox_range_requests_RangeRequestsPlugin.calledWith(), ).to.be.true; } if (options.backgroundSync) { if ('options' in options.backgroundSync) { expect( globalScope.workbox_background_sync_BackgroundSyncPlugin.calledWith( options.backgroundSync.name, options.backgroundSync.options, ), ).to.be.true; } else { expect( globalScope.workbox_background_sync_BackgroundSyncPlugin.calledWith( options.backgroundSync.name, ), ).to.be.true; } } if (options.broadcastUpdate) { if ('options' in options.broadcastUpdate) { const expectedOptions = Object.assign( {channelName: options.broadcastUpdate.channelName}, options.broadcastUpdate.options, ); expect( globalScope.workbox_broadcast_update_BroadcastUpdatePlugin.calledWith( expectedOptions, ), ).to.be.true; } else { expect( globalScope.workbox_broadcast_update_BroadcastUpdatePlugin.calledWith( {channelName: options.broadcastUpdate.channelName}, ), ).to.be.true; } } } }); }
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 `executeAsyncScript()` method.
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 `executeAsyncScript()` method.
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) { console.error(e); response.status(200).json({ success: false, content: null, }); } }
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) throw new Error(`Failed to sync YouTube video transcript. ${reason}`); response.status(200).json({ success, content }); } catch (e) { console.error(e); response.status(200).json({ success: false, content: null, }); } }
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: link) @param {import("../../middleware/setDataSigner").ResponseWithSigner} response
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. const source = response.locals.encryptionWorker.expandPayload(chunkSource); const { fetchConfluencePage } = require("../../utils/extensions/Confluence"); const { success, reason, content } = await fetchConfluencePage({ pageUrl: `https:${source.pathname}`, // need to add back the real protocol baseUrl: source.searchParams.get('baseUrl'), spaceKey: source.searchParams.get('spaceKey'), accessToken: source.searchParams.get('token'), username: source.searchParams.get('username'), }); if (!success) throw new Error(`Failed to sync Confluence page content. ${reason}`); response.status(200).json({ success, content }); } catch (e) { console.error(e); response.status(200).json({ success: false, content: null, }); } }
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 access token/params. const source = response.locals.encryptionWorker.expandPayload(chunkSource); const { fetchGithubFile } = require("../../utils/extensions/RepoLoader/GithubRepo"); const { success, reason, content } = await fetchGithubFile({ repoUrl: `https:${source.pathname}`, // need to add back the real protocol branch: source.searchParams.get('branch'), accessToken: source.searchParams.get('pat'), sourceFilePath: source.searchParams.get('path'), }); if (!success) throw new Error(`Failed to sync GitHub file content. ${reason}`); response.status(200).json({ success, content }); } catch (e) { console.error(e); response.status(200).json({ success: false, content: null, }); } }
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. const source = response.locals.encryptionWorker.expandPayload(chunkSource); const { loadPage } = require("../../utils/extensions/DrupalWiki"); const { success, reason, content } = await loadPage({ baseUrl: source.searchParams.get('baseUrl'), pageId: source.searchParams.get('pageId'), accessToken: source.searchParams.get('accessToken'), }); if (!success) { console.error(`Failed to sync DrupalWiki page content. ${reason}`); response.status(200).json({ success: false, content: null, }); } else { response.status(200).json({ success, content }); } } catch (e) { console.error(e); response.status(200).json({ success: false, content: null, }); } }
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 decryptedPayloadSignerKey = comKey.decrypt(encryptedPayloadSigner); const encryptionWorker = new EncryptionWorker(decryptedPayloadSignerKey); response.locals.encryptionWorker = encryptionWorker; next(); }
@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}>} - Response from collector
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: boolean, content: string}>} - Response from collector
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.error(`Resulting URL content was empty at ${link}.`); return { success: false, reason: `No URL content found at ${link}.`, documents: [], }; } if (!processAsDocument) { return { success: true, content, }; } const url = new URL(link); const decodedPathname = decodeURIComponent(url.pathname); const filename = `${url.hostname}${decodedPathname.replace(/\//g, "_")}`; const data = { id: v4(), url: "file://" + slugify(filename) + ".html", title: slugify(filename) + ".html", docAuthor: "no author found", description: "No description found.", docSource: "URL link uploaded by the user.", chunkSource: `link://${link}`, published: new Date().toLocaleString(), wordCount: content.split(" ").length, pageContent: content, token_count_estimate: tokenizeString(content), }; const document = writeToServerDocuments( data, `url-${slugify(filename)}-${data.id}` ); console.log(`[SUCCESS]: URL ${link} converted & ready for embedding.\n`); return { success: true, reason: null, documents: [document] }; }
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 - Whether to process the content as a document or return the content directly. Default is true @param {{[key: string]: string}} config.scraperHeaders - Custom headers to use when making the request @returns {Promise<Object>} - The content of the page
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] = headers[key].trim(); } return validHeaders; } catch (error) { console.error("Error validating headers", error); return {}; } }
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", }, 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 browser.close(); return result; }, }); // Override scrape method if headers are available let overrideHeaders = validatedHeaders(headers); if (Object.keys(overrideHeaders).length > 0) { loader.scrape = async function () { const { launch } = await PuppeteerWebBaseLoader.imports(); const browser = await launch({ headless: "new", defaultViewport: null, ignoreDefaultArgs: ["--disable-extensions"], ...this.options?.launchOptions, }); const page = await browser.newPage(); await page.setExtraHTTPHeaders(overrideHeaders); await page.goto(this.webPath, { timeout: 180000, waitUntil: "networkidle2", ...this.options?.gotoOptions, }); const bodyHTML = this.options?.evaluate ? await this.options.evaluate(page, browser) : await page.evaluate(() => document.body.innerHTML); await browser.close(); return bodyHTML; }; } const docs = await loader.load(); for (const doc of docs) pageContents.push(doc.pageContent); return pageContents.join(" "); } catch (error) { console.error( "getPageContent failed to be fetched by puppeteer - falling back to fetch!", error ); } try { const pageText = await fetch(link, { method: "GET", headers: { "Content-Type": "text/plain", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36,gzip(gfe)", ...validatedHeaders(headers), }, }).then((res) => res.text()); return pageText; } catch (error) { console.error("getPageContent failed to be fetched by any method.", error); } return null; }
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 making the request @returns {Promise<string>} - The content of the page
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 browser.close(); return result; }
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 making the request @returns {Promise<string>} - The content of the page
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"); // remove payload prop // Add all query params needed to replay as query params Object.entries(encodedParams).forEach(([key, value]) => url.searchParams.append(key, value) ); return url; } catch (e) { console.error(e); } return new URL(chunkSource); }
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", "hex"); return [ encrypted + cipher.final("hex"), Buffer.from(iv).toString("hex"), ].join(this.separator); } catch (e) { this.log(e); return null; } }
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(encrypted, "hex", "utf8") + decipher.final("utf8"); } catch (e) { this.log(e); return null; } }
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 either a personal access token (PAT), or a username and access token to use the Confluence connector.", }; } if (!baseUrl || !validBaseUrl(baseUrl)) { return { success: false, reason: "Provided base URL is not a valid URL.", }; } if (!spaceKey) { return { success: false, reason: "You need to provide a Confluence space key.", }; } const { origin, hostname } = new URL(baseUrl); console.log(`-- Working Confluence ${origin} --`); const loader = new ConfluencePagesLoader({ baseUrl: origin, // Use the origin to avoid issues with subdomains, ports, protocols, etc. spaceKey, username, accessToken, cloud, personalAccessToken, }); const { docs, error } = await loader .load() .then((docs) => { return { docs, error: null }; }) .catch((e) => { return { docs: [], error: e.message?.split("Error:")?.[1] || e.message, }; }); if (!docs.length || !!error) { return { success: false, reason: error ?? "No pages found for that Confluence space.", }; } const outFolder = slugify( `confluence-${hostname}-${v4().slice(0, 4)}` ).toLowerCase(); const outFolderPath = process.env.NODE_ENV === "development" ? path.resolve( __dirname, `../../../../server/storage/documents/${outFolder}` ) : path.resolve(process.env.STORAGE_DIR, `documents/${outFolder}`); if (!fs.existsSync(outFolderPath)) fs.mkdirSync(outFolderPath, { recursive: true }); docs.forEach((doc) => { if (!doc.pageContent) return; const data = { id: v4(), url: doc.metadata.url + ".page", title: doc.metadata.title || doc.metadata.source, docAuthor: origin, description: doc.metadata.title, docSource: `${origin} Confluence`, chunkSource: generateChunkSource( { doc, baseUrl: origin, spaceKey, accessToken, username, cloud }, response.locals.encryptionWorker ), published: new Date().toLocaleString(), wordCount: doc.pageContent.split(" ").length, pageContent: doc.pageContent, token_count_estimate: tokenizeString(doc.pageContent), }; console.log( `[Confluence Loader]: Saving ${doc.metadata.title} to ${outFolder}` ); const fileName = sanitizeFileName( `${slugify(doc.metadata.title)}-${data.id}` ); writeToServerDocuments(data, fileName, outFolderPath); }); return { success: true, reason: null, data: { spaceKey, destination: outFolder, }, }; }
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 personal access token (PAT), to use the Confluence connector.", }; } if (!validBaseUrl(baseUrl)) { return { success: false, content: null, reason: "Provided base URL is not a valid URL.", }; } if (!spaceKey) { return { success: false, content: null, reason: "You need to provide a Confluence space key.", }; } console.log(`-- Working Confluence Page ${pageUrl} --`); const loader = new ConfluencePagesLoader({ baseUrl, // Should be the origin of the baseUrl spaceKey, username, accessToken, cloud, }); const { docs, error } = await loader .load() .then((docs) => { return { docs, error: null }; }) .catch((e) => { return { docs: [], error: e.message?.split("Error:")?.[1] || e.message, }; }); if (!docs.length || !!error) { return { success: false, reason: error ?? "No pages found for that Confluence space.", content: null, }; } const targetDocument = docs.find( (doc) => doc.pageContent && doc.metadata.url === pageUrl ); if (!targetDocument) { return { success: false, reason: "Target page could not be found in Confluence space.", content: null, }; } return { success: true, reason: null, content: targetDocument.pageContent, }; }
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("../../EncryptionWorker").EncryptionWorker} encryptionWorker @returns {string}
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, content: page.processedBody, }; } catch (e) { return { success: false, reason: `Failed (re)-fetching DrupalWiki page ${pageId} form ${baseUrl}}`, content: null, }; } }
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 (page.processedBody.trim() !== "") { this.#storePage(page, encryptionWorker); await this.#downloadAndProcessAttachments(page.id); } else { console.log(`Skipping page (${page.id}) since it has no content`); } } catch (e) { console.error( `Could not process DrupalWiki page ${pageId} (skipping and continuing): ` ); console.error(e); } } }
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").EncryptionWorker} encryptionWorker @returns {string}
_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"); default: console.log(`Loading GitHub RepoLoader...`); return require("./GithubRepo/RepoLoader"); } }
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").loadGitlabRepo; default: console.log(`Loading GitHub loader function...`); return require("./GithubRepo").loadGithubRepo; } }
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.branch} --` ); const docs = await repo.recursiveLoader(); if (!docs.length) { return { success: false, reason: "No files were found for those settings.", }; } console.log(`[GitHub Loader]: Found ${docs.length} source files. Saving...`); const outFolder = slugify( `${repo.author}-${repo.project}-${repo.branch}-${v4().slice(0, 4)}` ).toLowerCase(); const outFolderPath = process.env.NODE_ENV === "development" ? path.resolve( __dirname, `../../../../../server/storage/documents/${outFolder}` ) : path.resolve(process.env.STORAGE_DIR, `documents/${outFolder}`); if (!fs.existsSync(outFolderPath)) fs.mkdirSync(outFolderPath, { recursive: true }); for (const doc of docs) { if (!doc.pageContent) continue; const data = { id: v4(), url: "github://" + doc.metadata.source, title: doc.metadata.source, docAuthor: repo.author, description: "No description found.", docSource: doc.metadata.source, chunkSource: generateChunkSource( repo, doc, response.locals.encryptionWorker ), published: new Date().toLocaleString(), wordCount: doc.pageContent.split(" ").length, pageContent: doc.pageContent, token_count_estimate: tokenizeString(doc.pageContent), }; console.log( `[GitHub Loader]: Saving ${doc.metadata.source} to ${outFolder}` ); writeToServerDocuments( data, `${slugify(doc.metadata.source)}-${data.id}`, outFolderPath ); } return { success: true, reason: null, data: { author: repo.author, repo: repo.project, branch: repo.branch, files: docs.length, destination: outFolder, }, }; }
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 GitHub repo for loading! Check URL or PAT.", }; console.log( `-- Working GitHub ${repo.author}/${repo.project}:${repo.branch} file:${sourceFilePath} --` ); const fileContent = await repo.fetchSingleFile(sourceFilePath); if (!fileContent) { return { success: false, reason: "Target file returned a null content response.", content: null, }; } return { success: true, reason: null, content: fileContent, }; }
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( JSON.stringify(payload) )}`; }
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").Document} doc @param {import("../../EncryptionWorker").EncryptionWorker} encryptionWorker @returns {string}
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! Recursive loading enabled!` ); const loader = new LCGithubLoader(this.repo, { branch: this.branch, recursive: !!this.accessToken, // Recursive will hit rate limits. maxConcurrency: 5, unknown: "warn", accessToken: this.accessToken, ignorePaths: this.ignorePaths, verbose: true, }); const docs = await loader.load(); return docs; }
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 ${page} of branches for ${this.project}`); await fetch( `https://api.github.com/repos/${this.author}/${this.project}/branches?per_page=100&page=${page}`, { method: "GET", headers: { ...(this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}), "X-GitHub-Api-Version": "2022-11-28", }, } ) .then((res) => { if (res.ok) return res.json(); throw new Error(`Invalid request to Github API: ${res.statusText}`); }) .then((branchObjects) => { polling = branchObjects.length > 0; branches.push(branchObjects.map((branch) => branch.name)); page++; }) .catch((err) => { polling = false; console.log(`RepoLoader.branches`, err); }); } this.branches = [...new Set(branches.flat())]; return this.#branchPrefSort(this.branches); }
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-Version": "2022-11-28", ...(!!this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}), }, } ) .then((res) => { if (res.ok) return res.json(); throw new Error(`Failed to fetch from Github API: ${res.statusText}`); }) .then((json) => { if (json.hasOwnProperty("status") || !json.hasOwnProperty("content")) throw new Error(json?.message || "missing content"); return atob(json.content); }); } catch (e) { console.error(`RepoLoader.fetchSingleFile`, e); return null; } }
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.branch} --` ); const docs = await repo.recursiveLoader(); if (!docs.length) { return { success: false, reason: "No files were found for those settings.", }; } console.log(`[GitLab Loader]: Found ${docs.length} source files. Saving...`); const outFolder = slugify( `${repo.author}-${repo.project}-${repo.branch}-${v4().slice(0, 4)}` ).toLowerCase(); const outFolderPath = process.env.NODE_ENV === "development" ? path.resolve( __dirname, `../../../../../server/storage/documents/${outFolder}` ) : path.resolve(process.env.STORAGE_DIR, `documents/${outFolder}`); if (!fs.existsSync(outFolderPath)) fs.mkdirSync(outFolderPath, { recursive: true }); for (const doc of docs) { if (!doc.metadata || (!doc.pageContent && !doc.issue && !doc.wiki)) continue; let pageContent = null; const data = { id: v4(), url: "gitlab://" + doc.metadata.source, docSource: doc.metadata.source, chunkSource: generateChunkSource( repo, doc, response.locals.encryptionWorker ), published: new Date().toLocaleString(), }; if (doc.pageContent) { pageContent = doc.pageContent; data.title = doc.metadata.source; data.docAuthor = repo.author; data.description = "No description found."; } else if (doc.issue) { pageContent = issueToMarkdown(doc.issue); data.title = `Issue ${doc.issue.iid}: ${doc.issue.title}`; data.docAuthor = doc.issue.author.username; data.description = doc.issue.description; } else if (doc.wiki) { pageContent = doc.wiki.content; data.title = doc.wiki.title; data.docAuthor = repo.author; data.description = doc.wiki.format === "markdown" ? "GitLab Wiki Page (Markdown)" : "GitLab Wiki Page"; } else { continue; } data.wordCount = pageContent.split(" ").length; data.token_count_estimate = tokenizeString(pageContent); data.pageContent = pageContent; console.log( `[GitLab Loader]: Saving ${doc.metadata.source} to ${outFolder}` ); writeToServerDocuments( data, sanitizeFileName(`${slugify(doc.metadata.source)}-${data.id}`), outFolderPath ); } return { success: true, reason: null, data: { author: repo.author, repo: repo.project, projectId: repo.projectId, branch: repo.branch, files: docs.length, destination: outFolder, }, }; }
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 GitLab repo for loading! Check URL or PAT.", }; console.log( `-- Working GitLab ${repo.author}/${repo.project}:${repo.branch} file:${sourceFilePath} --` ); const fileContent = await repo.fetchSingleFile(sourceFilePath); if (!fileContent) { return { success: false, reason: "Target file returned a null content response.", content: null, }; } return { success: true, reason: null, content: fileContent, }; }
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( JSON.stringify(payload) )}`; }
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[userField].map(userToUsername); } else { metadata[userField] = userToUsername(issue[userField]); } } } const singleValueFields = [ "web_url", "state", "created_at", "updated_at", "closed_at", "due_date", "type", "merge_request_count", "upvotes", "downvotes", "labels", "has_tasks", "task_status", "confidential", "severity", ]; for (const singleValueField of singleValueFields) { metadata[singleValueField] = issue[singleValueField]; } if (issue.milestone) { metadata.milestone = `${issue.milestone.title} (${issue.milestone.id})`; } if (issue.time_stats) { const timeFields = ["time_estimate", "total_time_spent"]; for (const timeField of timeFields) { const fieldName = `human_${timeField}`; if (issue?.time_stats[fieldName]) { metadata[timeField] = issue.time_stats[fieldName]; } } } const metadataString = Object.entries(metadata) .map(([name, value]) => { if (!value || value?.length < 1) { return null; } let result = `- ${name.replace("_", " ")}:`; if (!Array.isArray(value)) { result += ` ${value}`; } else { result += "\n" + value.map((s) => ` - ${s}`).join("\n"); } return result; }) .filter((item) => item != null) .join("\n"); let markdown = `# ${issue.title} (${issue.iid}) ${issue.description} ## Metadata ${metadataString}`; if (issue.discussions.length > 0) { markdown += ` ## Activity ${issue.discussions.join("\n\n")} `; } return markdown; }
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