code
stringlengths
28
313k
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
74
language
stringclasses
1 value
repo
stringlengths
5
60
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function onTag(tag, html, options) { // do nothing }
default onTag function @param {String} tag @param {String} html @param {Object} options @return {String}
onTag
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function onIgnoreTag(tag, html, options) { // do nothing }
default onIgnoreTag function @param {String} tag @param {String} html @param {Object} options @return {String}
onIgnoreTag
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function onTagAttr(tag, name, value) { // do nothing }
default onTagAttr function @param {String} tag @param {String} name @param {String} value @return {String}
onTagAttr
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function onIgnoreTagAttr(tag, name, value) { // do nothing }
default onIgnoreTagAttr function @param {String} tag @param {String} name @param {String} value @return {String}
onIgnoreTagAttr
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function escapeHtml(html) { return html.replace(REGEXP_LT, "<").replace(REGEXP_GT, ">"); }
default escapeHtml function @param {String} html
escapeHtml
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function safeAttrValue(tag, name, value, cssFilter) { // unescape attribute value firstly value = friendlyAttrValue(value); if (name === "href" || name === "src") { // filter `href` and `src` attribute // only allow the value that starts with `http://` | `https://` | `mailto:` | `/` | `#` value = _.trim(value); if (value === "#") return "#"; if ( !( value.substr(0, 7) === "http://" || value.substr(0, 8) === "https://" || value.substr(0, 7) === "mailto:" || value.substr(0, 4) === "tel:" || value.substr(0, 11) === "data:image/" || value.substr(0, 6) === "ftp://" || value.substr(0, 2) === "./" || value.substr(0, 3) === "../" || value[0] === "#" || value[0] === "/" ) ) { return ""; } } else if (name === "background") { // filter `background` attribute (maybe no use) // `javascript:` REGEXP_DEFAULT_ON_TAG_ATTR_4.lastIndex = 0; if (REGEXP_DEFAULT_ON_TAG_ATTR_4.test(value)) { return ""; } } else if (name === "style") { // `expression()` REGEXP_DEFAULT_ON_TAG_ATTR_7.lastIndex = 0; if (REGEXP_DEFAULT_ON_TAG_ATTR_7.test(value)) { return ""; } // `url()` REGEXP_DEFAULT_ON_TAG_ATTR_8.lastIndex = 0; if (REGEXP_DEFAULT_ON_TAG_ATTR_8.test(value)) { REGEXP_DEFAULT_ON_TAG_ATTR_4.lastIndex = 0; if (REGEXP_DEFAULT_ON_TAG_ATTR_4.test(value)) { return ""; } } if (cssFilter !== false) { cssFilter = cssFilter || defaultCSSFilter; value = cssFilter.process(value); } } // escape `<>"` before returns value = escapeAttrValue(value); return value; }
default safeAttrValue function @param {String} tag @param {String} name @param {String} value @param {Object} cssFilter @return {String}
safeAttrValue
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function escapeQuote(str) { return str.replace(REGEXP_QUOTE, "&quot;"); }
escape double quote @param {String} str @return {String} str
escapeQuote
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function unescapeQuote(str) { return str.replace(REGEXP_QUOTE_2, '"'); }
unescape double quote @param {String} str @return {String} str
unescapeQuote
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function escapeHtmlEntities(str) { return str.replace(REGEXP_ATTR_VALUE_1, function replaceUnicode(str, code) { return code[0] === "x" || code[0] === "X" ? String.fromCharCode(parseInt(code.substr(1), 16)) : String.fromCharCode(parseInt(code, 10)); }); }
escape html entities @param {String} str @return {String}
escapeHtmlEntities
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function escapeDangerHtml5Entities(str) { return str .replace(REGEXP_ATTR_VALUE_COLON, ":") .replace(REGEXP_ATTR_VALUE_NEWLINE, " "); }
escape html5 new danger entities @param {String} str @return {String}
escapeDangerHtml5Entities
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function clearNonPrintableCharacter(str) { var str2 = ""; for (var i = 0, len = str.length; i < len; i++) { str2 += str.charCodeAt(i) < 32 ? " " : str.charAt(i); } return _.trim(str2); }
clear nonprintable characters @param {String} str @return {String}
clearNonPrintableCharacter
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function friendlyAttrValue(str) { str = unescapeQuote(str); str = escapeHtmlEntities(str); str = escapeDangerHtml5Entities(str); str = clearNonPrintableCharacter(str); return str; }
get friendly attribute value @param {String} str @return {String}
friendlyAttrValue
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function escapeAttrValue(str) { str = escapeQuote(str); str = escapeHtml(str); return str; }
unescape attribute value @param {String} str @return {String}
escapeAttrValue
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function onIgnoreTagStripAll() { return ""; }
`onIgnoreTag` function for removing all the tags that are not in whitelist
onIgnoreTagStripAll
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function StripTagBody(tags, next) { if (typeof next !== "function") { next = function () {}; } var isRemoveAllTag = !Array.isArray(tags); function isRemoveTag(tag) { if (isRemoveAllTag) return true; return _.indexOf(tags, tag) !== -1; } var removeList = []; var posStart = false; return { onIgnoreTag: function (tag, html, options) { if (isRemoveTag(tag)) { if (options.isClosing) { var ret = "[/removed]"; var end = options.position + ret.length; removeList.push([ posStart !== false ? posStart : options.position, end, ]); posStart = false; return ret; } else { if (!posStart) { posStart = options.position; } return "[removed]"; } } else { return next(tag, html, options); } }, remove: function (html) { var rethtml = ""; var lastPos = 0; _.forEach(removeList, function (pos) { rethtml += html.slice(lastPos, pos[0]); lastPos = pos[1]; }); rethtml += html.slice(lastPos); return rethtml; }, }; }
remove tag body specify a `tags` list, if the tag is not in the `tags` list then process by the specify function (optional) @param {array} tags @param {function} next
StripTagBody
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function stripCommentTag(html) { var retHtml = ""; var lastPos = 0; while (lastPos < html.length) { var i = html.indexOf("<!--", lastPos); if (i === -1) { retHtml += html.slice(lastPos); break; } retHtml += html.slice(lastPos, i); var j = html.indexOf("-->", i); if (j === -1) { break; } lastPos = j + 3; } return retHtml; }
remove html comments @param {String} html @return {String}
stripCommentTag
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function stripBlankChar(html) { var chars = html.split(""); chars = chars.filter(function (char) { var c = char.charCodeAt(0); if (c === 127) return false; if (c <= 31) { if (c === 10 || c === 13) return true; return false; } return true; }); return chars.join(""); }
remove invisible characters @param {String} html @return {String}
stripBlankChar
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function filterXSS(html, options) { var xss = new FilterXSS(options); return xss.process(html); }
filter xss function @param {String} html @param {Object} options { whiteList, onTag, onTagAttr, onIgnoreTag, onIgnoreTagAttr, safeAttrValue, escapeHtml } @return {String}
filterXSS
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function getTagName(html) { var i = _.spaceIndex(html); var tagName; if (i === -1) { tagName = html.slice(1, -1); } else { tagName = html.slice(1, i + 1); } tagName = _.trim(tagName).toLowerCase(); if (tagName.slice(0, 1) === "/") tagName = tagName.slice(1); if (tagName.slice(-1) === "/") tagName = tagName.slice(0, -1); return tagName; }
get tag name @param {String} html e.g. '<a hef="#">' @return {String}
getTagName
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function parseTag(html, onTag, escapeHtml) { "use strict"; var rethtml = ""; var lastPos = 0; var tagStart = false; var quoteStart = false; var currentPos = 0; var len = html.length; var currentTagName = ""; var currentHtml = ""; chariterator: for (currentPos = 0; currentPos < len; currentPos++) { var c = html.charAt(currentPos); if (tagStart === false) { if (c === "<") { tagStart = currentPos; continue; } } else { if (quoteStart === false) { if (c === "<") { rethtml += escapeHtml(html.slice(lastPos, currentPos)); tagStart = currentPos; lastPos = currentPos; continue; } if (c === ">" || currentPos === len - 1) { rethtml += escapeHtml(html.slice(lastPos, tagStart)); currentHtml = html.slice(tagStart, currentPos + 1); currentTagName = getTagName(currentHtml); rethtml += onTag( tagStart, rethtml.length, currentTagName, currentHtml, isClosing(currentHtml) ); lastPos = currentPos + 1; tagStart = false; continue; } if (c === '"' || c === "'") { var i = 1; var ic = html.charAt(currentPos - i); while (ic.trim() === "" || ic === "=") { if (ic === "=") { quoteStart = c; continue chariterator; } ic = html.charAt(currentPos - ++i); } } } else { if (c === quoteStart) { quoteStart = false; continue; } } } } if (lastPos < len) { rethtml += escapeHtml(html.substr(lastPos)); } return rethtml; }
parse input html and returns processed html @param {String} html @param {Function} onTag e.g. function (sourcePosition, position, tag, html, isClosing) @param {Function} escapeHtml @return {String}
parseTag
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function addAttr(name, value) { name = _.trim(name); name = name.replace(REGEXP_ILLEGAL_ATTR_NAME, "").toLowerCase(); if (name.length < 1) return; var ret = onAttr(name, value || ""); if (ret) retAttrs.push(ret); }
parse input attributes and returns processed attributes @param {String} html e.g. `href="#" target="_blank"` @param {Function} onAttr e.g. `function (name, value)` @return {String}
addAttr
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function isNull(obj) { return obj === undefined || obj === null; }
returns `true` if the input value is `undefined` or `null` @param {Object} obj @return {Boolean}
isNull
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function getAttrs(html) { var i = _.spaceIndex(html); if (i === -1) { return { html: "", closing: html[html.length - 2] === "/", }; } html = _.trim(html.slice(i + 1, -1)); var isClosing = html[html.length - 1] === "/"; if (isClosing) html = _.trim(html.slice(0, -1)); return { html: html, closing: isClosing, }; }
get attributes for a tag @param {String} html @return {Object} - {String} html - {Boolean} closing
getAttrs
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function shallowCopyObject(obj) { var ret = {}; for (var i in obj) { ret[i] = obj[i]; } return ret; }
shallow copy @param {Object} obj @return {Object}
shallowCopyObject
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
function FilterXSS(options) { options = shallowCopyObject(options || {}); if (options.stripIgnoreTag) { if (options.onIgnoreTag) { console.error( 'Notes: cannot use these two options "stripIgnoreTag" and "onIgnoreTag" at the same time' ); } options.onIgnoreTag = DEFAULT.onIgnoreTagStripAll; } if (options.whiteList || options.allowList) { options.whiteList = keysToLowerCase(options.whiteList || options.allowList); } else { options.whiteList = DEFAULT.whiteList; } options.onTag = options.onTag || DEFAULT.onTag; options.onTagAttr = options.onTagAttr || DEFAULT.onTagAttr; options.onIgnoreTag = options.onIgnoreTag || DEFAULT.onIgnoreTag; options.onIgnoreTagAttr = options.onIgnoreTagAttr || DEFAULT.onIgnoreTagAttr; options.safeAttrValue = options.safeAttrValue || DEFAULT.safeAttrValue; options.escapeHtml = options.escapeHtml || DEFAULT.escapeHtml; this.options = options; if (options.css === false) { this.cssFilter = false; } else { options.css = options.css || {}; this.cssFilter = new FilterCSS(options.css); } }
FilterXSS class @param {Object} options whiteList (or allowList), onTag, onTagAttr, onIgnoreTag, onIgnoreTagAttr, safeAttrValue, escapeHtml stripIgnoreTagBody, allowCommentTag, stripBlankChar css{whiteList, onAttr, onIgnoreAttr} `css=false` means don't use `cssfilter`
FilterXSS
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT
_extend = function (dst){ var args = arguments, i = 1, _ext = function (val, key){ dst[key] = val; }; for( ; i < args.length; i++ ){ _each(args[i], _ext); } return dst; }
Merge the contents of two or more objects together into the first object
_extend
javascript
danialfarid/ng-file-upload
demo/src/main/webapp/js/FileAPI.js
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/FileAPI.js
MIT
function Image(file){ if( file instanceof Image ){ var img = new Image(file.file); api.extend(img.matrix, file.matrix); return img; } else if( !(this instanceof Image) ){ return new Image(file); } this.file = file; this.size = file.size || 100; this.matrix = { sx: 0, sy: 0, sw: 0, sh: 0, dx: 0, dy: 0, dw: 0, dh: 0, resize: 0, // min, max OR preview deg: 0, quality: 1, // jpeg quality filter: 0 }; }
Remove drag'n'drop @param {HTMLElement} el @param {Function} onHover @param {Function} onDrop
Image
javascript
danialfarid/ng-file-upload
demo/src/main/webapp/js/FileAPI.js
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/FileAPI.js
MIT
_complete = function (err){ _this._active = !err; clearTimeout(_failId); clearTimeout(_successId); // api.event.off(video, 'loadedmetadata', _complete); callback && callback(err, _this); }
Start camera streaming @param {Function} callback
_complete
javascript
danialfarid/ng-file-upload
demo/src/main/webapp/js/FileAPI.js
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/FileAPI.js
MIT
doneFn = function (err){ if( err ){ callback(err); } else { // Get camera var cam = Camera.get(el); if( options.start ){ cam.start(callback); } else { callback(null, cam); } } }
Publish camera element into container @static @param {HTMLElement} el @param {Object} options @param {Function} [callback]
doneFn
javascript
danialfarid/ng-file-upload
demo/src/main/webapp/js/FileAPI.js
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/FileAPI.js
MIT
function _px(val){ return val >= 0 ? val + 'px' : val; }
Add "px" postfix, if value is a number @private @param {*} val @return {String}
_px
javascript
danialfarid/ng-file-upload
demo/src/main/webapp/js/FileAPI.js
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/FileAPI.js
MIT
function _detectVideoSignal(video){ var canvas = document.createElement('canvas'), ctx, res = false; try { ctx = canvas.getContext('2d'); ctx.drawImage(video, 0, 0, 1, 1); res = ctx.getImageData(0, 0, 1, 1).data[4] != 255; } catch( e ){} return res; }
@private @param {HTMLVideoElement} video @return {Boolean}
_detectVideoSignal
javascript
danialfarid/ng-file-upload
demo/src/main/webapp/js/FileAPI.js
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/FileAPI.js
MIT
function _wrap(fn) { var id = fn.wid = api.uid(); api.Flash._fn[id] = fn; return 'FileAPI.Flash._fn.' + id; }
FileAPI fallback to Flash @flash-developer "Vladimir Demidov" <[email protected]>
_wrap
javascript
danialfarid/ng-file-upload
demo/src/main/webapp/js/FileAPI.js
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/FileAPI.js
MIT
function sendHttp(config) { config.method = config.method || 'POST'; config.headers = config.headers || {}; var deferred = config._deferred = config._deferred || $q.defer(); var promise = deferred.promise; function notifyProgress(e) { if (deferred.notify) { deferred.notify(e); } if (promise.progressFunc) { $timeout(function () { promise.progressFunc(e); }); } } function getNotifyEvent(n) { if (config._start != null && resumeSupported) { return { loaded: n.loaded + config._start, total: (config._file && config._file.size) || n.total, type: n.type, config: config, lengthComputable: true, target: n.target }; } else { return n; } } if (!config.disableProgress) { config.headers.__setXHR_ = function () { return function (xhr) { if (!xhr || !xhr.upload || !xhr.upload.addEventListener) return; config.__XHR = xhr; if (config.xhrFn) config.xhrFn(xhr); xhr.upload.addEventListener('progress', function (e) { e.config = config; notifyProgress(getNotifyEvent(e)); }, false); //fix for firefox not firing upload progress end, also IE8-9 xhr.upload.addEventListener('load', function (e) { if (e.lengthComputable) { e.config = config; notifyProgress(getNotifyEvent(e)); } }, false); }; }; } function uploadWithAngular() { $http(config).then(function (r) { if (resumeSupported && config._chunkSize && !config._finished && config._file) { var fileSize = config._file && config._file.size || 0; notifyProgress({ loaded: Math.min(config._end, fileSize), total: fileSize, config: config, type: 'progress' } ); upload.upload(config, true); } else { if (config._finished) delete config._finished; deferred.resolve(r); } }, function (e) { deferred.reject(e); }, function (n) { deferred.notify(n); } ); } if (!resumeSupported) { uploadWithAngular(); } else if (config._chunkSize && config._end && !config._finished) { config._start = config._end; config._end += config._chunkSize; uploadWithAngular(); } else if (config.resumeSizeUrl) { $http.get(config.resumeSizeUrl).then(function (resp) { if (config.resumeSizeResponseReader) { config._start = config.resumeSizeResponseReader(resp.data); } else { config._start = parseInt((resp.data.size == null ? resp.data : resp.data.size).toString()); } if (config._chunkSize) { config._end = config._start + config._chunkSize; } uploadWithAngular(); }, function (e) { throw e; }); } else if (config.resumeSize) { config.resumeSize().then(function (size) { config._start = size; if (config._chunkSize) { config._end = config._start + config._chunkSize; } uploadWithAngular(); }, function (e) { throw e; }); } else { if (config._chunkSize) { config._start = 0; config._end = config._start + config._chunkSize; } uploadWithAngular(); } promise.success = function (fn) { promise.then(function (response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.error = function (fn) { promise.then(null, function (response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.progress = function (fn) { promise.progressFunc = fn; promise.then(null, null, function (n) { fn(n); }); return promise; }; promise.abort = promise.pause = function () { if (config.__XHR) { $timeout(function () { config.__XHR.abort(); }); } return promise; }; promise.xhr = function (fn) { config.xhrFn = (function (origXhrFn) { return function () { if (origXhrFn) origXhrFn.apply(promise, arguments); fn.apply(promise, arguments); }; })(config.xhrFn); return promise; }; upload.promisesCount++; if (promise['finally'] && promise['finally'] instanceof Function) { promise['finally'](function () { upload.promisesCount--; }); } return promise; }
! AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort, progress, resize, thumbnail, preview, validation and CORS @author Danial <[email protected]> @version 12.2.13
sendHttp
javascript
danialfarid/ng-file-upload
demo/src/main/webapp/js/ng-file-upload-all.js
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
MIT
calculateAspectRatioFit = function (srcWidth, srcHeight, maxWidth, maxHeight, centerCrop) { var ratio = centerCrop ? Math.max(maxWidth / srcWidth, maxHeight / srcHeight) : Math.min(maxWidth / srcWidth, maxHeight / srcHeight); return { width: srcWidth * ratio, height: srcHeight * ratio, marginX: srcWidth * ratio - maxWidth, marginY: srcHeight * ratio - maxHeight }; }
Conserve aspect ratio of the original region. Useful when shrinking/enlarging images to fit into a certain area. Source: http://stackoverflow.com/a/14731922 @param {Number} srcWidth Source area width @param {Number} srcHeight Source area height @param {Number} maxWidth Nestable area maximum available width @param {Number} maxHeight Nestable area maximum available height @return {Object} { width, height }
calculateAspectRatioFit
javascript
danialfarid/ng-file-upload
demo/src/main/webapp/js/ng-file-upload-all.js
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
MIT
function addEvent(element, event, handler) { if (element.addEventListener) { element.addEventListener(event, handler, false); } else if (element.attachEvent) { element.attachEvent("on" + event, handler); } }
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
addEvent
javascript
danialfarid/ng-file-upload
demo/src/main/webapp/js/ng-img-crop.js
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
MIT
getChangedTouches=function(event){ if(angular.isDefined(event.changedTouches)){ return event.changedTouches; }else{ return event.originalEvent.changedTouches; } }
Returns event.changedTouches directly if event is a TouchEvent. If event is a jQuery event, return changedTouches of event.originalEvent
getChangedTouches
javascript
danialfarid/ng-file-upload
demo/src/main/webapp/js/ng-img-crop.js
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
MIT
function notifyProgress(e) { if (deferred.notify) { deferred.notify(e); } if (promise.progressFunc) { $timeout(function () { promise.progressFunc(e); }); } }
! AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort, progress, resize, thumbnail, preview, validation and CORS @author Danial <[email protected]> @version <%= pkg.version %>
notifyProgress
javascript
danialfarid/ng-file-upload
src/upload.js
https://github.com/danialfarid/ng-file-upload/blob/master/src/upload.js
MIT
static k_combinations(set, k) { var i, j, combs, head, tailcombs; if (k > set.length || k <= 0) { return []; } if (k === set.length) { return [set]; } if (k === 1) { combs = []; for (i = 0; i < set.length; i++) { combs.push([set[i]]); } return combs; } // Assert {1 < k < set.length} combs = []; for (i = 0; i < set.length - k + 1; i++) { head = set.slice(i, i+1); tailcombs = Combinations.k_combinations(set.slice(i + 1), k - 1); for (j = 0; j < tailcombs.length; j++) { combs.push(head.concat(tailcombs[j])); } } return combs; }
K-combinations Get k-sized combinations of elements in a set. Usage: k_combinations(set, k) Parameters: set: Array of objects of any type. They are treated as unique. k: size of combinations to search for. Return: Array of found combinations, size of a combination is k. Examples: k_combinations([1, 2, 3], 1) -> [[1], [2], [3]] k_combinations([1, 2, 3], 2) -> [[1,2], [1,3], [2, 3] k_combinations([1, 2, 3], 3) -> [[1, 2, 3]] k_combinations([1, 2, 3], 4) -> [] k_combinations([1, 2, 3], 0) -> [] k_combinations([1, 2, 3], -1) -> [] k_combinations([], 0) -> []
k_combinations
javascript
CharlieHess/slack-poker-bot
util/combinations.js
https://github.com/CharlieHess/slack-poker-bot/blob/master/util/combinations.js
MIT
static combinations(set) { var k, i, combs, k_combs; combs = []; // Calculate all non-empty k-combinations for (k = 1; k <= set.length; k++) { k_combs = Combinations.k_combinations(set, k); for (i = 0; i < k_combs.length; i++) { combs.push(k_combs[i]); } } return combs; }
Combinations Get all possible combinations of elements in a set. Usage: combinations(set) Examples: combinations([1, 2, 3]) -> [[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]] combinations([1]) -> [[1]]
combinations
javascript
CharlieHess/slack-poker-bot
util/combinations.js
https://github.com/CharlieHess/slack-poker-bot/blob/master/util/combinations.js
MIT
U = function (a, b) { if (!a) { return ''; } b = b || 'x'; var c = ''; var d = 0; var e; for (d; d < a.length; d += 1) a.charCodeAt(d) >= 55296 && a.charCodeAt(d) <= 56319 ? (e = (65536 + 1024 * (Number(a.charCodeAt(d)) - 55296) + Number(a.charCodeAt(d + 1)) - 56320).toString(16), d += 1) : e = a.charCodeAt(d).toString(16), c += b + e; return c.substr(b.length); }
@Keyboard.js @author zhangxinxu @version Created: 17-06-13
U
javascript
yued-fe/lulu
theme/edge/js/common/all.js
https://github.com/yued-fe/lulu/blob/master/theme/edge/js/common/all.js
MIT
static get observedAttributes () { return ['open']; }
@Pagination.js @author sunmeiye @version @Created: 20-06-07 @edit: 20-06-07
observedAttributes
javascript
yued-fe/lulu
theme/edge/js/common/all.js
https://github.com/yued-fe/lulu/blob/master/theme/edge/js/common/all.js
MIT
get reverse () { return this.getAttribute('reverse') !== null || this.classList.contains('reverse'); }
@LightTip.js @author popeyesailorman(yangfan) @version @Created: 20-05-15 @edit: 20-05-15
reverse
javascript
yued-fe/lulu
theme/edge/js/common/all.js
https://github.com/yued-fe/lulu/blob/master/theme/edge/js/common/all.js
MIT
remove () { if (this.parentElement) { this.parentElement.removeChild(this); } this.open = false; }
@Range.js @author xboxyan @version @created: 20-04-30
remove
javascript
yued-fe/lulu
theme/edge/js/common/all.js
https://github.com/yued-fe/lulu/blob/master/theme/edge/js/common/all.js
MIT
get () { return !!(this.classList.contains(CL) || this.matches(CL)); }
@Color.js @author zhangxinxu @version @created 16-06-03 @edited 20-07-16 @Gwokhov
get
javascript
yued-fe/lulu
theme/edge/js/common/all.js
https://github.com/yued-fe/lulu/blob/master/theme/edge/js/common/all.js
MIT
get () { return document.validate.getValidity(this); }
@Pagination.js @author XboxYan(yanwenbin) @version @Created: 20-04-22 @edit: 20-04-22
get
javascript
yued-fe/lulu
theme/edge/js/common/all.js
https://github.com/yued-fe/lulu/blob/master/theme/edge/js/common/all.js
MIT
static get observedAttributes () { return ['open', 'target']; }
@Drop.js @author zhangxinxu @version @created 15-06-30 @edited 20-07-08 edit by wanglei
observedAttributes
javascript
yued-fe/lulu
theme/edge/js/common/ui/Drop.js
https://github.com/yued-fe/lulu/blob/master/theme/edge/js/common/ui/Drop.js
MIT
static allHide (exclude) { ErrorTip.collectionErrorTip.forEach(obj => { if (exclude != obj) { obj.hide(); } }); }
@ErrorTip.js @author zhangxinxu @version @created: 15-07-01 @edited: 20-07-07 edit by peter.qiyuanhao
allHide
javascript
yued-fe/lulu
theme/edge/js/common/ui/ErrorTip.js
https://github.com/yued-fe/lulu/blob/master/theme/edge/js/common/ui/ErrorTip.js
MIT
static get observedAttributes () { return ['title', 'reverse', 'for', 'eventType', 'align']; }
@Tips.js @author zhangxinxu @version @Created: 15-06-25 @edit: 17-06-19 @edit: 20-06-09 edit by y2x @edit: 20-11-03 by zxx
observedAttributes
javascript
yued-fe/lulu
theme/edge/js/common/ui/Tips.js
https://github.com/yued-fe/lulu/blob/master/theme/edge/js/common/ui/Tips.js
MIT
notify = (callback, root, MO) => { const loop = (nodes, added, removed, connected, pass) => { for (let i = 0, {length} = nodes; i < length; i++) { const node = nodes[i]; if (pass || (QSA$1 in node)) { if (connected) { if (!added.has(node)) { added.add(node); removed.delete(node); callback(node, connected); } } else if (!removed.has(node)) { removed.add(node); added.delete(node); callback(node, connected); } if (!pass) loop(node[QSA$1]('*'), added, removed, connected, TRUE); } } }; const observer = new (MO || MutationObserver)(records => { for (let added = new Set, removed = new Set, i = 0, {length} = records; i < length; i++ ) { const {addedNodes, removedNodes} = records[i]; loop(removedNodes, added, removed, FALSE, FALSE); loop(addedNodes, added, removed, TRUE, FALSE); } }); observer.add = add; observer.add(root || document); return observer; }
Start observing a generic document or root element. @param {Function} callback triggered per each dis/connected node @param {Element?} root by default, the global document to observe @param {Function?} MO by default, the global MutationObserver @returns {MutationObserver}
notify
javascript
yued-fe/lulu
theme/hope/ui/safari-polyfill.js
https://github.com/yued-fe/lulu/blob/master/theme/hope/ui/safari-polyfill.js
MIT
static get defaults () { return { eventtype: 'click', position: '7-5' }; }
@Drop.js @author zhangxinxu @version @created 15-06-30 @edited 20-07-08 edit by wanglei @edited 22-06-16 edit by wanglei
defaults
javascript
yued-fe/lulu
theme/hope/ui/Drop/index.js
https://github.com/yued-fe/lulu/blob/master/theme/hope/ui/Drop/index.js
MIT
set (value) { if (this.validate) { this.validate.setCustomValidity(value); } }
/ if (!CSS.supports('overflow-anchor:auto') || !CSS.supports('offset:none')) { /*
set
javascript
yued-fe/lulu
theme/hope/ui/Form/index.js
https://github.com/yued-fe/lulu/blob/master/theme/hope/ui/Form/index.js
MIT
static get observedAttributes () { return ['rows', 'height', 'width', 'label', 'font', 'minLength', 'maxLength']; }
/import promiseInput from '../Input/index.js'; /*
observedAttributes
javascript
yued-fe/lulu
theme/hope/ui/Textarea/index.js
https://github.com/yued-fe/lulu/blob/master/theme/hope/ui/Textarea/index.js
MIT
LightTip = function() { this.el = {}; return this; }
@Range.js @author xunxuzhang @version Created: 15-07-20
LightTip
javascript
yued-fe/lulu
theme/modern/js/common/all.js
https://github.com/yued-fe/lulu/blob/master/theme/modern/js/common/all.js
MIT
checkIfIteratorIsSupported = function () { try { return !!Symbol.iterator; } catch (error) { return false; } }
Polyfill URLSearchParams Inspired from : https://github.com/WebReflection/url-search-params/blob/master/src/url-search-params.js
checkIfIteratorIsSupported
javascript
yued-fe/lulu
theme/pure/js/common/polyfill.js
https://github.com/yued-fe/lulu/blob/master/theme/pure/js/common/polyfill.js
MIT
serializeParam = function (value) { return encodeURIComponent(value).replace(/%20/g, '+'); }
Search param name and values should be encoded according to https://url.spec.whatwg.org/#urlencoded-serializing encodeURIComponent() produces the same result except encoding spaces as `%20` instead of `+`.
serializeParam
javascript
yued-fe/lulu
theme/pure/js/common/polyfill.js
https://github.com/yued-fe/lulu/blob/master/theme/pure/js/common/polyfill.js
MIT
checkIfURLIsSupported = function () { try { var u = new global.URL('b', 'http://a'); u.pathname = 'c%20d'; return (u.href === 'http://a/c%20d') && u.searchParams; } catch (e) { return false; } }
Polyfill URL Inspired from : https://github.com/arv/DOM-URL-Polyfill/blob/master/src/url.js
checkIfURLIsSupported
javascript
yued-fe/lulu
theme/pure/js/common/polyfill.js
https://github.com/yued-fe/lulu/blob/master/theme/pure/js/common/polyfill.js
MIT
function FormData (form) { var self = this; if (!(self instanceof FormData)) { return new FormData(form); } if (form && (!form.tagName || form.tagName !== 'FORM')) { // not a form return; } self._boundary = createBoundary(); self._data = {}; if (!form) { // nothing to parse, we're done here return; } parseContents.call(self, form.children); }
[FormData description] @contructor @param {?HTMLForm} form HTML <form> element to populate the object (optional)
FormData
javascript
yued-fe/lulu
theme/pure/js/common/polyfill.js
https://github.com/yued-fe/lulu/blob/master/theme/pure/js/common/polyfill.js
MIT
CustomEvent = function (event, params) { params = params || { bubbles: false, cancelable: false, detail: undefined }; var evt = document.createEvent('CustomEvent'); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); return evt; }
CustomEvent constructor polyfill for IE @return {[type]} [description]
CustomEvent
javascript
yued-fe/lulu
theme/pure/js/common/polyfill.js
https://github.com/yued-fe/lulu/blob/master/theme/pure/js/common/polyfill.js
MIT
function has (key) { return this._data.hasOwnProperty(key); }
@description placeholder polyfill for IE9 only support one line no consideration of settings placeholder attr @author zhangxinxu(.com) @created 2019-08-09
has
javascript
yued-fe/lulu
theme/pure/js/common/polyfill.js
https://github.com/yued-fe/lulu/blob/master/theme/pure/js/common/polyfill.js
MIT
function BufferList(context, bufferData, options) { this._context = Utils.isAudioContext(context) ? context : Utils.throw('BufferList: Invalid BaseAudioContext.'); this._options = { dataType: BufferDataType.BASE64, verbose: false, }; if (options) { if (options.dataType && Utils.isDefinedENUMEntry(BufferDataType, options.dataType)) { this._options.dataType = options.dataType; } if (options.verbose) { this._options.verbose = Boolean(options.verbose); } } this._bufferList = []; this._bufferData = this._options.dataType === BufferDataType.BASE64 ? bufferData : bufferData.slice(0); this._numberOfTasks = this._bufferData.length; this._resolveHandler = null; this._rejectHandler = new Function(); }
BufferList object mananges the async loading/decoding of multiple AudioBuffers from multiple URLs. @constructor @param {BaseAudioContext} context - Associated BaseAudioContext. @param {string[]} bufferData - An ordered list of URLs. @param {Object} options - Options @param {string} [options.dataType='base64'] - BufferDataType specifier. @param {Boolean} [options.verbose=false] - Log verbosity. |true| prints the individual message from each URL and AudioBuffer.
BufferList
javascript
GoogleChrome/omnitone
src/buffer-list.js
https://github.com/GoogleChrome/omnitone/blob/master/src/buffer-list.js
Apache-2.0
function FOAConvolver(context, hrirBufferList) { this._context = context; this._active = false; this._isBufferLoaded = false; this._buildAudioGraph(); if (hrirBufferList) { this.setHRIRBufferList(hrirBufferList); } this.enable(); }
FOAConvolver. A collection of 2 stereo convolvers for 4-channel FOA stream. @constructor @param {BaseAudioContext} context The associated AudioContext. @param {AudioBuffer[]} [hrirBufferList] - An ordered-list of stereo AudioBuffers for convolution. (i.e. 2 stereo AudioBuffers for FOA)
FOAConvolver
javascript
GoogleChrome/omnitone
src/foa-convolver.js
https://github.com/GoogleChrome/omnitone/blob/master/src/foa-convolver.js
Apache-2.0
function FOARenderer(context, config) { this._context = Utils.isAudioContext(context) ? context : Utils.throw('FOARenderer: Invalid BaseAudioContext.'); this._config = { channelMap: FOARouter.ChannelMap.DEFAULT, renderingMode: RenderingMode.AMBISONIC, }; if (config) { if (config.channelMap) { if (Array.isArray(config.channelMap) && config.channelMap.length === 4) { this._config.channelMap = config.channelMap; } else { Utils.throw( 'FOARenderer: Invalid channel map. (got ' + config.channelMap + ')'); } } if (config.hrirPathList) { if (Array.isArray(config.hrirPathList) && config.hrirPathList.length === 2) { this._config.pathList = config.hrirPathList; } else { Utils.throw( 'FOARenderer: Invalid HRIR URLs. It must be an array with ' + '2 URLs to HRIR files. (got ' + config.hrirPathList + ')'); } } if (config.renderingMode) { if (Object.values(RenderingMode).includes(config.renderingMode)) { this._config.renderingMode = config.renderingMode; } else { Utils.log( 'FOARenderer: Invalid rendering mode order. (got' + config.renderingMode + ') Fallbacks to the mode "ambisonic".'); } } } this._buildAudioGraph(); this._tempMatrix4 = new Float32Array(16); this._isRendererReady = false; }
Omnitone FOA renderer class. Uses the optimized convolution technique. @constructor @param {AudioContext} context - Associated AudioContext. @param {Object} config @param {Array} [config.channelMap] - Custom channel routing map. Useful for handling the inconsistency in browser's multichannel audio decoding. @param {Array} [config.hrirPathList] - A list of paths to HRIR files. It overrides the internal HRIR list if given. @param {RenderingMode} [config.renderingMode='ambisonic'] - Rendering mode.
FOARenderer
javascript
GoogleChrome/omnitone
src/foa-renderer.js
https://github.com/GoogleChrome/omnitone/blob/master/src/foa-renderer.js
Apache-2.0
function FOARotator(context) { this._context = context; this._splitter = this._context.createChannelSplitter(4); this._inY = this._context.createGain(); this._inZ = this._context.createGain(); this._inX = this._context.createGain(); this._m0 = this._context.createGain(); this._m1 = this._context.createGain(); this._m2 = this._context.createGain(); this._m3 = this._context.createGain(); this._m4 = this._context.createGain(); this._m5 = this._context.createGain(); this._m6 = this._context.createGain(); this._m7 = this._context.createGain(); this._m8 = this._context.createGain(); this._outY = this._context.createGain(); this._outZ = this._context.createGain(); this._outX = this._context.createGain(); this._merger = this._context.createChannelMerger(4); // ACN channel ordering: [1, 2, 3] => [-Y, Z, -X] // Y (from channel 1) this._splitter.connect(this._inY, 1); // Z (from channel 2) this._splitter.connect(this._inZ, 2); // X (from channel 3) this._splitter.connect(this._inX, 3); this._inY.gain.value = -1; this._inX.gain.value = -1; // Apply the rotation in the world space. // |Y| | m0 m3 m6 | | Y * m0 + Z * m3 + X * m6 | | Yr | // |Z| * | m1 m4 m7 | = | Y * m1 + Z * m4 + X * m7 | = | Zr | // |X| | m2 m5 m8 | | Y * m2 + Z * m5 + X * m8 | | Xr | this._inY.connect(this._m0); this._inY.connect(this._m1); this._inY.connect(this._m2); this._inZ.connect(this._m3); this._inZ.connect(this._m4); this._inZ.connect(this._m5); this._inX.connect(this._m6); this._inX.connect(this._m7); this._inX.connect(this._m8); this._m0.connect(this._outY); this._m1.connect(this._outZ); this._m2.connect(this._outX); this._m3.connect(this._outY); this._m4.connect(this._outZ); this._m5.connect(this._outX); this._m6.connect(this._outY); this._m7.connect(this._outZ); this._m8.connect(this._outX); // Transform 3: world space to audio space. // W -> W (to channel 0) this._splitter.connect(this._merger, 0, 0); // Y (to channel 1) this._outY.connect(this._merger, 0, 1); // Z (to channel 2) this._outZ.connect(this._merger, 0, 2); // X (to channel 3) this._outX.connect(this._merger, 0, 3); this._outY.gain.value = -1; this._outX.gain.value = -1; this.setRotationMatrix3(new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1])); // input/output proxy. this.input = this._splitter; this.output = this._merger; }
First-order-ambisonic decoder based on gain node network. @constructor @param {AudioContext} context - Associated AudioContext.
FOARotator
javascript
GoogleChrome/omnitone
src/foa-rotator.js
https://github.com/GoogleChrome/omnitone/blob/master/src/foa-rotator.js
Apache-2.0
function FOARouter(context, channelMap) { this._context = context; this._splitter = this._context.createChannelSplitter(4); this._merger = this._context.createChannelMerger(4); // input/output proxy. this.input = this._splitter; this.output = this._merger; this.setChannelMap(channelMap || ChannelMap.DEFAULT); }
Channel router for FOA stream. @constructor @param {AudioContext} context - Associated AudioContext. @param {Number[]} channelMap - Routing destination array.
FOARouter
javascript
GoogleChrome/omnitone
src/foa-router.js
https://github.com/GoogleChrome/omnitone/blob/master/src/foa-router.js
Apache-2.0
function HOAConvolver(context, ambisonicOrder, hrirBufferList) { this._context = context; this._active = false; this._isBufferLoaded = false; // The number of channels K based on the ambisonic order N where K = (N+1)^2. this._ambisonicOrder = ambisonicOrder; this._numberOfChannels = (this._ambisonicOrder + 1) * (this._ambisonicOrder + 1); this._buildAudioGraph(); if (hrirBufferList) { this.setHRIRBufferList(hrirBufferList); } this.enable(); }
A convolver network for N-channel HOA stream. @constructor @param {AudioContext} context - Associated AudioContext. @param {Number} ambisonicOrder - Ambisonic order. (2 or 3) @param {AudioBuffer[]} [hrirBufferList] - An ordered-list of stereo AudioBuffers for convolution. (SOA: 5 AudioBuffers, TOA: 8 AudioBuffers)
HOAConvolver
javascript
GoogleChrome/omnitone
src/hoa-convolver.js
https://github.com/GoogleChrome/omnitone/blob/master/src/hoa-convolver.js
Apache-2.0
function HOARenderer(context, config) { this._context = Utils.isAudioContext(context) ? context : Utils.throw('HOARenderer: Invalid BaseAudioContext.'); this._config = { ambisonicOrder: 3, renderingMode: RenderingMode.AMBISONIC, }; if (config && config.ambisonicOrder) { if (SupportedAmbisonicOrder.includes(config.ambisonicOrder)) { this._config.ambisonicOrder = config.ambisonicOrder; } else { Utils.log( 'HOARenderer: Invalid ambisonic order. (got ' + config.ambisonicOrder + ') Fallbacks to 3rd-order ambisonic.'); } } this._config.numberOfChannels = (this._config.ambisonicOrder + 1) * (this._config.ambisonicOrder + 1); this._config.numberOfStereoChannels = Math.ceil(this._config.numberOfChannels / 2); if (config && config.hrirPathList) { if (Array.isArray(config.hrirPathList) && config.hrirPathList.length === this._config.numberOfStereoChannels) { this._config.pathList = config.hrirPathList; } else { Utils.throw( 'HOARenderer: Invalid HRIR URLs. It must be an array with ' + this._config.numberOfStereoChannels + ' URLs to HRIR files.' + ' (got ' + config.hrirPathList + ')'); } } if (config && config.renderingMode) { if (Object.values(RenderingMode).includes(config.renderingMode)) { this._config.renderingMode = config.renderingMode; } else { Utils.log( 'HOARenderer: Invalid rendering mode. (got ' + config.renderingMode + ') Fallbacks to "ambisonic".'); } } this._buildAudioGraph(); this._isRendererReady = false; }
Omnitone HOA renderer class. Uses the optimized convolution technique. @constructor @param {AudioContext} context - Associated AudioContext. @param {Object} config @param {Number} [config.ambisonicOrder=3] - Ambisonic order. @param {Array} [config.hrirPathList] - A list of paths to HRIR files. It overrides the internal HRIR list if given. @param {RenderingMode} [config.renderingMode='ambisonic'] - Rendering mode.
HOARenderer
javascript
GoogleChrome/omnitone
src/hoa-renderer.js
https://github.com/GoogleChrome/omnitone/blob/master/src/hoa-renderer.js
Apache-2.0
function getKroneckerDelta(i, j) { return i === j ? 1 : 0; }
Kronecker Delta function. @param {Number} i @param {Number} j @return {Number}
getKroneckerDelta
javascript
GoogleChrome/omnitone
src/hoa-rotator.js
https://github.com/GoogleChrome/omnitone/blob/master/src/hoa-rotator.js
Apache-2.0
function setCenteredElement(matrix, l, i, j, gainValue) { const index = (j + l) * (2 * l + 1) + (i + l); // Row-wise indexing. matrix[l - 1][index].gain.value = gainValue; }
A helper function to allow us to access a matrix array in the same manner, assuming it is a (2l+1)x(2l+1) matrix. [2] uses an odd convention of referring to the rows and columns using centered indices, so the middle row and column are (0, 0) and the upper left would have negative coordinates. @param {Number[]} matrix - N matrices of gainNodes, each with (2n+1) x (2n+1) elements, where n=1,2,...,N. @param {Number} l @param {Number} i @param {Number} j @param {Number} gainValue
setCenteredElement
javascript
GoogleChrome/omnitone
src/hoa-rotator.js
https://github.com/GoogleChrome/omnitone/blob/master/src/hoa-rotator.js
Apache-2.0
function getCenteredElement(matrix, l, i, j) { // Row-wise indexing. const index = (j + l) * (2 * l + 1) + (i + l); return matrix[l - 1][index].gain.value; }
This is a helper function to allow us to access a matrix array in the same manner, assuming it is a (2l+1) x (2l+1) matrix. @param {Number[]} matrix - N matrices of gainNodes, each with (2n+1) x (2n+1) elements, where n=1,2,...,N. @param {Number} l @param {Number} i @param {Number} j @return {Number}
getCenteredElement
javascript
GoogleChrome/omnitone
src/hoa-rotator.js
https://github.com/GoogleChrome/omnitone/blob/master/src/hoa-rotator.js
Apache-2.0
function getP(matrix, i, a, b, l) { if (b === l) { return getCenteredElement(matrix, 1, i, 1) * getCenteredElement(matrix, l - 1, a, l - 1) - getCenteredElement(matrix, 1, i, -1) * getCenteredElement(matrix, l - 1, a, -l + 1); } else if (b === -l) { return getCenteredElement(matrix, 1, i, 1) * getCenteredElement(matrix, l - 1, a, -l + 1) + getCenteredElement(matrix, 1, i, -1) * getCenteredElement(matrix, l - 1, a, l - 1); } else { return getCenteredElement(matrix, 1, i, 0) * getCenteredElement(matrix, l - 1, a, b); } }
Helper function defined in [2] that is used by the functions U, V, W. This should not be called on its own, as U, V, and W (and their coefficients) select the appropriate matrix elements to access arguments |a| and |b|. @param {Number[]} matrix - N matrices of gainNodes, each with (2n+1) x (2n+1) elements, where n=1,2,...,N. @param {Number} i @param {Number} a @param {Number} b @param {Number} l @return {Number}
getP
javascript
GoogleChrome/omnitone
src/hoa-rotator.js
https://github.com/GoogleChrome/omnitone/blob/master/src/hoa-rotator.js
Apache-2.0
function getU(matrix, m, n, l) { // Although [1, 2] split U into three cases for m == 0, m < 0, m > 0 // the actual values are the same for all three cases. return getP(matrix, 0, m, n, l); }
The functions U, V, and W should only be called if the correspondingly named coefficient u, v, w from the function ComputeUVWCoeff() is non-zero. When the coefficient is 0, these would attempt to access matrix elements that are out of bounds. The vector of rotations, |r|, must have the |l - 1| previously completed band rotations. These functions are valid for |l >= 2|. @param {Number[]} matrix - N matrices of gainNodes, each with (2n+1) x (2n+1) elements, where n=1,2,...,N. @param {Number} m @param {Number} n @param {Number} l @return {Number}
getU
javascript
GoogleChrome/omnitone
src/hoa-rotator.js
https://github.com/GoogleChrome/omnitone/blob/master/src/hoa-rotator.js
Apache-2.0
function getW(matrix, m, n, l) { // Whenever this happens, w is also 0 so W can be anything. if (m === 0) { return 0; } return m > 0 ? getP(matrix, 1, m + 1, n, l) + getP(matrix, -1, -m - 1, n, l) : getP(matrix, 1, m - 1, n, l) - getP(matrix, -1, -m + 1, n, l); }
The functions U, V, and W should only be called if the correspondingly named coefficient u, v, w from the function ComputeUVWCoeff() is non-zero. When the coefficient is 0, these would attempt to access matrix elements that are out of bounds. The vector of rotations, |r|, must have the |l - 1| previously completed band rotations. These functions are valid for |l >= 2|. @param {Number[]} matrix N matrices of gainNodes, each with (2n+1) x (2n+1) elements, where n=1,2,...,N. @param {Number} m @param {Number} n @param {Number} l @return {Number}
getW
javascript
GoogleChrome/omnitone
src/hoa-rotator.js
https://github.com/GoogleChrome/omnitone/blob/master/src/hoa-rotator.js
Apache-2.0
function computeUVWCoeff(m, n, l) { const d = getKroneckerDelta(m, 0); const reciprocalDenominator = Math.abs(n) === l ? 1 / (2 * l * (2 * l - 1)) : 1 / ((l + n) * (l - n)); return [ Math.sqrt((l + m) * (l - m) * reciprocalDenominator), 0.5 * (1 - 2 * d) * Math.sqrt((1 + d) * (l + Math.abs(m) - 1) * (l + Math.abs(m)) * reciprocalDenominator), -0.5 * (1 - d) * Math.sqrt((l - Math.abs(m) - 1) * (l - Math.abs(m))) * reciprocalDenominator, ]; }
Calculates the coefficients applied to the U, V, and W functions. Because their equations share many common terms they are computed simultaneously. @param {Number} m @param {Number} n @param {Number} l @return {Array} 3 coefficients for U, V and W functions.
computeUVWCoeff
javascript
GoogleChrome/omnitone
src/hoa-rotator.js
https://github.com/GoogleChrome/omnitone/blob/master/src/hoa-rotator.js
Apache-2.0
function computeBandRotation(matrix, l) { // The lth band rotation matrix has rows and columns equal to the number of // coefficients within that band (-l <= m <= l implies 2l + 1 coefficients). for (let m = -l; m <= l; m++) { for (let n = -l; n <= l; n++) { const uvwCoefficients = computeUVWCoeff(m, n, l); // The functions U, V, W are only safe to call if the coefficients // u, v, w are not zero. if (Math.abs(uvwCoefficients[0]) > 0) { uvwCoefficients[0] *= getU(matrix, m, n, l); } if (Math.abs(uvwCoefficients[1]) > 0) { uvwCoefficients[1] *= getV(matrix, m, n, l); } if (Math.abs(uvwCoefficients[2]) > 0) { uvwCoefficients[2] *= getW(matrix, m, n, l); } setCenteredElement( matrix, l, m, n, uvwCoefficients[0] + uvwCoefficients[1] + uvwCoefficients[2]); } } }
Calculates the (2l+1) x (2l+1) rotation matrix for the band l. This uses the matrices computed for band 1 and band l-1 to compute the matrix for band l. |rotations| must contain the previously computed l-1 rotation matrices. This implementation comes from p. 5 (6346), Table 1 and 2 in [2] taking into account the corrections from [2b]. @param {Number[]} matrix - N matrices of gainNodes, each with where n=1,2,...,N. @param {Number} l
computeBandRotation
javascript
GoogleChrome/omnitone
src/hoa-rotator.js
https://github.com/GoogleChrome/omnitone/blob/master/src/hoa-rotator.js
Apache-2.0
function computeHOAMatrices(matrix) { // We start by computing the 2nd-order matrix from the 1st-order matrix. for (let i = 2; i <= matrix.length; i++) { computeBandRotation(matrix, i); } }
Compute the HOA rotation matrix after setting the transform matrix. @param {Array} matrix - N matrices of gainNodes, each with (2n+1) x (2n+1) elements, where n=1,2,...,N.
computeHOAMatrices
javascript
GoogleChrome/omnitone
src/hoa-rotator.js
https://github.com/GoogleChrome/omnitone/blob/master/src/hoa-rotator.js
Apache-2.0
function HOARotator(context, ambisonicOrder) { this._context = context; this._ambisonicOrder = ambisonicOrder; // We need to determine the number of channels K based on the ambisonic order // N where K = (N + 1)^2. const numberOfChannels = (ambisonicOrder + 1) * (ambisonicOrder + 1); this._splitter = this._context.createChannelSplitter(numberOfChannels); this._merger = this._context.createChannelMerger(numberOfChannels); // Create a set of per-order rotation matrices using gain nodes. this._gainNodeMatrix = []; let orderOffset; let rows; let inputIndex; let outputIndex; let matrixIndex; for (let i = 1; i <= ambisonicOrder; i++) { // Each ambisonic order requires a separate (2l + 1) x (2l + 1) rotation // matrix. We compute the offset value as the first channel index of the // current order where // k_last = l^2 + l + m, // and m = -l // k_last = l^2 orderOffset = i * i; // Uses row-major indexing. rows = (2 * i + 1); this._gainNodeMatrix[i - 1] = []; for (let j = 0; j < rows; j++) { inputIndex = orderOffset + j; for (let k = 0; k < rows; k++) { outputIndex = orderOffset + k; matrixIndex = j * rows + k; this._gainNodeMatrix[i - 1][matrixIndex] = this._context.createGain(); this._splitter.connect( this._gainNodeMatrix[i - 1][matrixIndex], inputIndex); this._gainNodeMatrix[i - 1][matrixIndex].connect( this._merger, 0, outputIndex); } } } // W-channel is not involved in rotation, skip straight to ouput. this._splitter.connect(this._merger, 0, 0); // Default Identity matrix. this.setRotationMatrix3(new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1])); // Input/Output proxy. this.input = this._splitter; this.output = this._merger; }
Higher-order-ambisonic decoder based on gain node network. We expect the order of the channels to conform to ACN ordering. Below are the helper methods to compute SH rotation using recursion. The code uses maths described in the following papers: [1] R. Green, "Spherical Harmonic Lighting: The Gritty Details", GDC 2003, http://www.research.scea.com/gdc2003/spherical-harmonic-lighting.pdf [2] J. Ivanic and K. Ruedenberg, "Rotation Matrices for Real Spherical Harmonics. Direct Determination by Recursion", J. Phys. Chem., vol. 100, no. 15, pp. 6342-6347, 1996. http://pubs.acs.org/doi/pdf/10.1021/jp953350u [2b] Corrections to initial publication: http://pubs.acs.org/doi/pdf/10.1021/jp9833350 @constructor @param {AudioContext} context - Associated AudioContext. @param {Number} ambisonicOrder - Ambisonic order.
HOARotator
javascript
GoogleChrome/omnitone
src/hoa-rotator.js
https://github.com/GoogleChrome/omnitone/blob/master/src/hoa-rotator.js
Apache-2.0
function generateExpectedBusFromFOAIRBuffer(buffer) { var generatedBus = new AudioBus(2, buffer.length, buffer.sampleRate); var W = buffer.getChannelData(0); var Y = buffer.getChannelData(1); var Z = buffer.getChannelData(2); var X = buffer.getChannelData(3); var L = generatedBus.getChannelData(0); var R = generatedBus.getChannelData(1); for (var i = 0; i < buffer.length; ++i) { L[i] = W[i] + Y[i] + Z[i] + X[i]; R[i] = W[i] - Y[i] + Z[i] + X[i]; } return generatedBus; }
Calculate the expected binaural rendering (based on SH-maxRE algorithm) result from the impulse input and generate an AudioBus instance. @param {AudioBuffer} buffer FOA SH-maxRE HRIR buffer. @return {AudioBus}
generateExpectedBusFromFOAIRBuffer
javascript
GoogleChrome/omnitone
test/test-foa-convolver.js
https://github.com/GoogleChrome/omnitone/blob/master/test/test-foa-convolver.js
Apache-2.0
function generateExpectedBusFromTOAIRBuffer(buffer) { // TOA IR set is 16 channels. expect(buffer.numberOfChannels).to.equal(16); // Derive ambisonic order from number of channels. var ambisonicOrder = Math.floor(Math.sqrt(buffer.numberOfChannels)) - 1; // Get pointers to each buffer. var acnChannelData = []; for (var i = 0; i < buffer.numberOfChannels; i++) acnChannelData[i] = buffer.getChannelData(i); var generatedBus = new AudioBus(2, buffer.length, buffer.sampleRate); var L = generatedBus.getChannelData(0); var R = generatedBus.getChannelData(1); // We wish to exploit front-axis symmetry, hence the left output will be // the sum of all spherical harmonics while the right output is the // difference between the positive-m spherical harmonics and the negative-m // spherical harmonics. for (var i = 0; i < buffer.length; ++i) { L[i] = 0; R[i] = 0; for (var l = 0; l <= ambisonicOrder; l++) { for (var m = -l; m <= l; m++) { var channelValue = acnChannelData[l * l + l + m]; L[i] += channelValue; R[i] += m >= 0 ? channelValue : -channelValue; } } } return generatedBus; }
Generate the expected binaural rendering (based on SH-maxRE algorithm) result from the impulse response and generate an AudioBus instance. @param {AudioBuffer} buffer TOA SH-maxRE HRIR buffer. @return {AudioBus}
generateExpectedBusFromTOAIRBuffer
javascript
GoogleChrome/omnitone
test/test-hoa-convolver.js
https://github.com/GoogleChrome/omnitone/blob/master/test/test-hoa-convolver.js
Apache-2.0
function crossProduct(a, b) { return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ]; }
Compute cross-product between two 3-element vectors. @param {Float32Array} a @param {Float32Array} b
crossProduct
javascript
GoogleChrome/omnitone
test/test-hoa-rotator.js
https://github.com/GoogleChrome/omnitone/blob/master/test/test-hoa-rotator.js
Apache-2.0
function generateRotationMatrix(azimuth, elevation) { var forward = [ -Math.sin(azimuth) * Math.cos(elevation), Math.sin(elevation), -Math.cos(azimuth) * Math.cos(elevation) ]; var right = normalize(crossProduct([0, 1, 0], forward)); var up = normalize(crossProduct(forward, right)); return right.concat(up.concat(forward)); }
Generate a col-major 3x3 Euler rotation matrix. @param {Number} azimuth @param {Number} elevation
generateRotationMatrix
javascript
GoogleChrome/omnitone
test/test-hoa-rotator.js
https://github.com/GoogleChrome/omnitone/blob/master/test/test-hoa-rotator.js
Apache-2.0
function computeRotationAndTest(index) { it('#setRotationMatrix: rotate the incoming stream using direction [' + sphericalDirections[index] + '].', function(done) { hoaRotator.setRotationMatrix3(generateRotationMatrix( sphericalDirections[index][0], sphericalDirections[index][1])); expectedValues = sphericalHarmonicsPerDirection[index]; context.startRendering().then(function(renderedBuffer) { var vectorNomal = 0; var numberOfChannels = renderedBuffer.numberOfChannels; for (var channel = 0; channel < numberOfChannels; ++channel) { var channelData = renderedBuffer.getChannelData(channel); for (var i = 0; i < channelData.length; ++i) vectorNomal += Math.abs(channelData[i] - expectedValues[channel]); } vectorNomal /= renderedBuffer.getChannelData(0).length * renderedBuffer.numberOfChannels * vectorMagnitude; expect(vectorNomal).to.be.below(THRESHOLD); done(); }); }); }
TODO: describe this test. @param {Function} done Test runner callback. @param {Number} index Direction idex.
computeRotationAndTest
javascript
GoogleChrome/omnitone
test/test-hoa-rotator.js
https://github.com/GoogleChrome/omnitone/blob/master/test/test-hoa-rotator.js
Apache-2.0
function createConstantBuffer(context, values, length) { var constantBuffer = context.createBuffer( values.length, length, context.sampleRate); for (var channel = 0; channel < constantBuffer.numberOfChannels; channel++) { var channelData = constantBuffer.getChannelData(channel); for (var index = 0; index < channelData.length; index++) channelData[index] = values[channel]; } return constantBuffer; }
Create a buffer for testing. Each channel contains a stream of single, user-defined value. @param {AudioContext} context AudioContext. @param {Array} values User-defined constant value for each channel. @param {Number} length Buffer length in samples. @return {AudioBuffer}
createConstantBuffer
javascript
GoogleChrome/omnitone
test/test-setup.js
https://github.com/GoogleChrome/omnitone/blob/master/test/test-setup.js
Apache-2.0
function createImpulseBuffer(context, numberOfChannels, length) { var impulseBuffer = context.createBuffer( numberOfChannels, length, context.sampleRate); for (var channel = 0; channel < impulseBuffer.numberOfChannels; channel++) { var channelData = impulseBuffer.getChannelData(channel); channelData[0] = 1.0; } return impulseBuffer; }
Create a impulse buffer for testing. Each channel contains a single unity value (1.0) at the beginning and the rest of content is all zero. @param {AudioContext} context AudioContext @param {Number} numberOfChannels Channel count. @param {Number} length Buffer length in samples. @return {AudioBuffer}
createImpulseBuffer
javascript
GoogleChrome/omnitone
test/test-setup.js
https://github.com/GoogleChrome/omnitone/blob/master/test/test-setup.js
Apache-2.0
function isConstantValueOf(channelData, value) { var mismatches = {}; for (var i = 0; i < channelData.length; i++) { if (channelData[i] !== value) mismatches[i] = channelData[i]; } return Object.keys(mismatches).length === 0; }
Check if the array is filled with the specified value only. @param {Float32Array} channelData The target array for testing. @param {Number} value A value for the testing. @return {Boolean}
isConstantValueOf
javascript
GoogleChrome/omnitone
test/test-setup.js
https://github.com/GoogleChrome/omnitone/blob/master/test/test-setup.js
Apache-2.0
function getDualBandFilterCoefs(crossoverFrequency, sampleRate) { var k = Math.tan(Math.PI * crossoverFrequency / sampleRate), k2 = k * k, denominator = k2 + 2 * k + 1; return { lowpassA: [1, 2 * (k2 - 1) / denominator, (k2 - 2 * k + 1) / denominator], lowpassB: [k2 / denominator, 2 * k2 / denominator, k2 / denominator], hipassA: [1, 2 * (k2 - 1) / denominator, (k2 - 2 * k + 1) / denominator], hipassB: [1 / denominator, -2 * 1 / denominator, 1 / denominator] }; }
Generate the filter coefficients for the phase matched dual band filter. @param {NUmber} crossoverFrequency Filter crossover frequency. @param {NUmber} sampleRate Operating sample rate. @return {Object} Filter coefficients. { lowpassA, lowpassB, hipassA, hipassB } (where B is feedforward, A is feedback.)
getDualBandFilterCoefs
javascript
GoogleChrome/omnitone
test/test-setup.js
https://github.com/GoogleChrome/omnitone/blob/master/test/test-setup.js
Apache-2.0
function kernel_IIRFIlter (channelData, feedforward, feedback) { var paddingSize = Math.max(feedforward.length, feedback.length); var workSize = channelData.length + paddingSize; var x = new Float32Array(workSize); var y = new Float64Array(workSize); x.set(channelData, paddingSize); for (var index = paddingSize; index < workSize; ++index) { var yn = 0; for (k = 0; k < feedforward.length; ++k) yn += feedforward[k] * x[index - k]; for (k = 0; k < feedback.length; ++k) yn -= feedback[k] * y[index - k]; y[index] = yn; } channelData.set(y.slice(paddingSize).map(Math.fround)); }
Kernel processor for IIR filter. (in-place processing) @param {Float32Array} channelData A channel data. @param {Float32Array} feedforward Feedforward coefficients. @param {Float32Array} feedback Feedback coefficients.
kernel_IIRFIlter
javascript
GoogleChrome/omnitone
test/test-setup.js
https://github.com/GoogleChrome/omnitone/blob/master/test/test-setup.js
Apache-2.0
function AudioBus (numberOfChannels, length, sampleRate) { this.numberOfChannels = numberOfChannels; this.sampleRate = sampleRate; this.length = length; this.duration = this.length / this.sampleRate; this._channelData = []; for (var i = 0; i < this.numberOfChannels; ++i) { this._channelData[i] = new Float32Array(length); } }
A collection of Float32Array as AudioBus abstraction. @param {Number} numberOfChannels Number of channels. @param {Number} length Buffer length in samples. @param {Number} sampleRate Operating sample rate.
AudioBus
javascript
GoogleChrome/omnitone
test/test-setup.js
https://github.com/GoogleChrome/omnitone/blob/master/test/test-setup.js
Apache-2.0
mockTrace = () => ({ traceAsyncFn: (fn) => fn(mockTrace()), traceFn: (fn) => fn(mockTrace()), traceChild: () => mockTrace(), })
@typedef {{ file: string, excludedCases: string[] }} TestFile
mockTrace
javascript
vercel/next.js
run-tests.js
https://github.com/vercel/next.js/blob/master/run-tests.js
MIT
async open (cacheName) { webidl.brandCheck(this, CacheStorage) webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' }) cacheName = webidl.converters.DOMString(cacheName) // 2.1 if (this.#caches.has(cacheName)) { // await caches.open('v1') !== await caches.open('v1') // 2.1.1 const cache = this.#caches.get(cacheName) // 2.1.1.1 return new Cache(kConstruct, cache) } // 2.2 const cache = [] // 2.3 this.#caches.set(cacheName, cache) // 2.4 return new Cache(kConstruct, cache) }
@see https://w3c.github.io/ServiceWorker/#cache-storage-keys @returns {string[]}
open
javascript
vercel/next.js
.github/actions/next-integration-stat/dist/index.js
https://github.com/vercel/next.js/blob/master/.github/actions/next-integration-stat/dist/index.js
MIT
function mixinBody (prototype) { Object.assign(prototype.prototype, bodyMixinMethods(prototype)) }
@see https://fetch.spec.whatwg.org/#concept-body-consume-body @param {Response|Request} object @param {(value: unknown) => unknown} convertBytesToJSValue @param {Response|Request} instance
mixinBody
javascript
vercel/next.js
.github/actions/next-integration-stat/dist/index.js
https://github.com/vercel/next.js/blob/master/.github/actions/next-integration-stat/dist/index.js
MIT
get lengthComputable () { webidl.brandCheck(this, ProgressEvent) return this[kState].lengthComputable }
@see https://w3c.github.io/FileAPI/#readOperation @param {import('./filereader').FileReader} fr @param {import('buffer').Blob} blob @param {string} type @param {string?} encodingName
lengthComputable
javascript
vercel/next.js
.github/actions/next-integration-stat/dist/index.js
https://github.com/vercel/next.js/blob/master/.github/actions/next-integration-stat/dist/index.js
MIT
async linkPackages({ repoDir, nextSwcVersion: nextSwcVersionSpecified, parentSpan, }) { if (!parentSpan) { // Not all callers provide a parent span parentSpan = mockSpan() } /** @type {Map<string, string>} */ const pkgPaths = new Map() /** @type {Map<string, { packageJsonPath: string, packagePath: string, packageJson: any, packedPackageTarPath: string }>} */ const pkgDatas = new Map() let packageFolders try { packageFolders = await parentSpan .traceChild('read-packages-folder') .traceAsyncFn(() => fs.promises.readdir(path.join(repoDir, 'packages')) ) } catch (err) { if (err.code === 'ENOENT') { require('console').log('no packages to link') return pkgPaths } throw err } parentSpan.traceChild('get-pkgdatas').traceFn(() => { for (const packageFolder of packageFolders) { const packagePath = path.join(repoDir, 'packages', packageFolder) const packedPackageTarPath = path.join( packagePath, `${packageFolder}-packed.tgz` ) const packageJsonPath = path.join(packagePath, 'package.json') if (!existsSync(packageJsonPath)) { require('console').log(`Skipping ${packageFolder}, no package.json`) continue } const packageJson = JSON.parse(fs.readFileSync(packageJsonPath)) const { name: packageName } = packageJson pkgDatas.set(packageName, { packageJsonPath, packagePath, packageJson, packedPackageTarPath, }) pkgPaths.set(packageName, packedPackageTarPath) } }) const nextSwcVersion = nextSwcVersionSpecified ?? pkgDatas.get('@next/swc')?.packedPackageTarPath ?? null await parentSpan .traceChild('write-packagejson') .traceAsyncFn(async () => { for (const [ packageName, { packageJsonPath, packagePath, packageJson }, ] of pkgDatas.entries()) { // This loops through all items to get the packagedPkgPath of each item and add it to pkgData.dependencies for (const [ packageName, { packedPackageTarPath }, ] of pkgDatas.entries()) { if ( !packageJson.dependencies || !packageJson.dependencies[packageName] ) continue // Edit the pkgData of the current item to point to the packed tgz packageJson.dependencies[packageName] = packedPackageTarPath } // make sure native binaries are included in local linking if (packageName === '@next/swc') { packageJson.files ||= [] packageJson.files.push('native') try { const swcBinariesDirContents = ( await fs.promises.readdir(path.join(packagePath, 'native')) ).filter( (file) => file !== '.gitignore' && file !== 'index.d.ts' ) require('console').log( 'using swc binaries: ', swcBinariesDirContents.join(', ') ) } catch (err) { if (err.code === 'ENOENT') { require('console').log('swc binaries dir is missing!') } throw err } } else if (packageName === 'next') { const nextSwcPkg = pkgDatas.get('@next/swc') console.log('using swc dep', { nextSwcVersion, nextSwcPkg, }) if (nextSwcVersion) { Object.assign(packageJson.dependencies, { // CI '@next/swc-linux-x64-gnu': nextSwcVersion, // Vercel issued laptops '@next/swc-darwin-arm64': nextSwcVersion, }) } } await fs.promises.writeFile( packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf8' ) } }) await parentSpan .traceChild('pnpm-packing') .traceAsyncFn(async (packingSpan) => { // wait to pack packages until after dependency paths have been updated // to the correct versions await Promise.all( Array.from(pkgDatas.entries()).map( async ([ packageName, { packagePath: pkgPath, packedPackageTarPath: packedPkgPath }, ]) => { return packingSpan .traceChild('handle-package', { packageName }) .traceAsyncFn(async (handlePackageSpan) => { /** @type {null | () => Promise<void>} */ let cleanup = null if (packageName === '@next/swc') { // next-swc uses a gitignore to prevent the committing of native builds but it doesn't // use files in package.json because it publishes to individual packages based on architecture. // When we used yarn to pack these packages the gitignore was ignored so the native builds were packed // however npm does respect gitignore when packing so we need to remove it in this specific case // to ensure the native builds are packed for use in gh actions and related scripts const nativeGitignorePath = path.join( pkgPath, 'native/.gitignore' ) const renamedGitignorePath = path.join( pkgPath, 'disabled-native-gitignore' ) await handlePackageSpan .traceChild('rename-gitignore') .traceAsyncFn(() => fs.promises.rename( nativeGitignorePath, renamedGitignorePath ) ) cleanup = async () => { await fs.promises.rename( renamedGitignorePath, nativeGitignorePath ) } } const options = { cwd: pkgPath, env: { ...process.env, COREPACK_ENABLE_STRICT: '0', }, } let execResult try { execResult = await handlePackageSpan .traceChild('pnpm-pack-try-1') .traceAsyncFn(() => execa('pnpm', ['pack'], options)) } catch { execResult = await handlePackageSpan .traceChild('pnpm-pack-try-2') .traceAsyncFn(() => execa('pnpm', ['pack'], options)) } const { stdout } = execResult const packedFileName = stdout.trim() await handlePackageSpan .traceChild('rename-packed-tar-and-cleanup') .traceAsyncFn(() => Promise.all([ fs.promises.rename( path.join(pkgPath, packedFileName), packedPkgPath ), cleanup?.(), ]) ) }) } ) ) }) return pkgPaths }
Runs `pnpm pack` on each package in the `packages` folder of the provided `repoDir` @param {{ repoDir: string, nextSwcVersion: null | string }} options Required options @returns {Promise<Map<string, string>>} List packages key is the package name, value is the path to the packed tar file.'
linkPackages
javascript
vercel/next.js
.github/actions/next-stats-action/src/prepare/repo-setup.js
https://github.com/vercel/next.js/blob/master/.github/actions/next-stats-action/src/prepare/repo-setup.js
MIT
constructor(command, opts) { this.serialize = defaultSerializer; this.deserialize = opts?.automaticDeserialization === void 0 || opts.automaticDeserialization ? opts?.deserialize ?? parseResponse : (x) => x; this.command = command.map((c) => this.serialize(c)); if (opts?.latencyLogging) { const originalExec = this.exec.bind(this); this.exec = async (client) => { const start = performance.now(); const result = await originalExec(client); const end = performance.now(); const loggerResult = (end - start).toFixed(2); console.log( `Latency for \x1B[38;2;19;185;39m${this.command[0].toString().toUpperCase()}\x1B[0m: \x1B[38;2;0;255;255m${loggerResult} ms\x1B[0m` ); return result; }; } }
Create a new command instance. You can define a custom `deserialize` function. By default we try to deserialize as json.
constructor
javascript
vercel/next.js
.github/actions/upload-turboyet-data/dist/index.js
https://github.com/vercel/next.js/blob/master/.github/actions/upload-turboyet-data/dist/index.js
MIT
length() { return this.commands.length; }
Returns the length of pipeline before the execution
length
javascript
vercel/next.js
.github/actions/upload-turboyet-data/dist/index.js
https://github.com/vercel/next.js/blob/master/.github/actions/upload-turboyet-data/dist/index.js
MIT
chain(command) { this.commands.push(command); return this; }
Pushes a command into the pipeline and returns a chainable instance of the pipeline
chain
javascript
vercel/next.js
.github/actions/upload-turboyet-data/dist/index.js
https://github.com/vercel/next.js/blob/master/.github/actions/upload-turboyet-data/dist/index.js
MIT
get json() { return { /** * @see https://redis.io/commands/json.arrappend */ arrappend: (...args) => this.chain(new JsonArrAppendCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.arrindex */ arrindex: (...args) => this.chain(new JsonArrIndexCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.arrinsert */ arrinsert: (...args) => this.chain(new JsonArrInsertCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.arrlen */ arrlen: (...args) => this.chain(new JsonArrLenCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.arrpop */ arrpop: (...args) => this.chain(new JsonArrPopCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.arrtrim */ arrtrim: (...args) => this.chain(new JsonArrTrimCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.clear */ clear: (...args) => this.chain(new JsonClearCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.del */ del: (...args) => this.chain(new JsonDelCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.forget */ forget: (...args) => this.chain(new JsonForgetCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.get */ get: (...args) => this.chain(new JsonGetCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.mget */ mget: (...args) => this.chain(new JsonMGetCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.mset */ mset: (...args) => this.chain(new JsonMSetCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.numincrby */ numincrby: (...args) => this.chain(new JsonNumIncrByCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.nummultby */ nummultby: (...args) => this.chain(new JsonNumMultByCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.objkeys */ objkeys: (...args) => this.chain(new JsonObjKeysCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.objlen */ objlen: (...args) => this.chain(new JsonObjLenCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.resp */ resp: (...args) => this.chain(new JsonRespCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.set */ set: (...args) => this.chain(new JsonSetCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.strappend */ strappend: (...args) => this.chain(new JsonStrAppendCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.strlen */ strlen: (...args) => this.chain(new JsonStrLenCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.toggle */ toggle: (...args) => this.chain(new JsonToggleCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.type */ type: (...args) => this.chain(new JsonTypeCommand(args, this.commandOptions)) }; }
@see https://redis.io/commands/?group=json
json
javascript
vercel/next.js
.github/actions/upload-turboyet-data/dist/index.js
https://github.com/vercel/next.js/blob/master/.github/actions/upload-turboyet-data/dist/index.js
MIT
constructor(redis, script) { this.redis = redis; this.sha1 = this.digest(script); this.script = script; }
@see https://redis.io/commands/json.type
constructor
javascript
vercel/next.js
.github/actions/upload-turboyet-data/dist/index.js
https://github.com/vercel/next.js/blob/master/.github/actions/upload-turboyet-data/dist/index.js
MIT
async eval(keys, args) { return await this.redis.eval(this.script, keys, args); }
Send an `EVAL` command to redis.
eval
javascript
vercel/next.js
.github/actions/upload-turboyet-data/dist/index.js
https://github.com/vercel/next.js/blob/master/.github/actions/upload-turboyet-data/dist/index.js
MIT
async evalsha(keys, args) { return await this.redis.evalsha(this.sha1, keys, args); }
Calculates the sha1 hash of the script and then calls `EVALSHA`.
evalsha
javascript
vercel/next.js
.github/actions/upload-turboyet-data/dist/index.js
https://github.com/vercel/next.js/blob/master/.github/actions/upload-turboyet-data/dist/index.js
MIT
async exec(keys, args) { const res = await this.redis.evalsha(this.sha1, keys, args).catch(async (error) => { if (error instanceof Error && error.message.toLowerCase().includes("noscript")) { return await this.redis.eval(this.script, keys, args); } throw error; }); return res; }
Optimistically try to run `EVALSHA` first. If the script is not loaded in redis, it will fall back and try again with `EVAL`. Following calls will be able to use the cached script
exec
javascript
vercel/next.js
.github/actions/upload-turboyet-data/dist/index.js
https://github.com/vercel/next.js/blob/master/.github/actions/upload-turboyet-data/dist/index.js
MIT