docs: 仓库链接指向本镜像仓库
Dev Build / cleanup (push) Canceled after 0s
Dev Build / typecheck (push) Canceled after 0s
Dev Build / build (linux-arm64, ubuntu-24.04-arm, linux-arm64) (push) Canceled after 0s
Dev Build / build (linux-x64, ubuntu-latest, linux-x64) (push) Canceled after 0s
Dev Build / build (win-x64, windows-latest, win32-x64) (push) Canceled after 0s
Dev Build / dispatch-dev-docker (push) Skipped

This commit is contained in:
TanTan committed 2026-11-13 09:27:07 +08:00
1 parent fa9c73363d
commit 2a69b23b47
18210 files changed
+5101211 -16

No files matched your search

@@ -0,0 +1,141 @@
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Qs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";var replace=String.prototype.replace,percentTwenties=/%20/g,Format={RFC1738:"RFC1738",RFC3986:"RFC3986"};module.exports={default:Format.RFC3986,formatters:{RFC1738:function(e){return replace.call(e,percentTwenties,"+")},RFC3986:function(e){return String(e)}},RFC1738:Format.RFC1738,RFC3986:Format.RFC3986};
},{}],2:[function(require,module,exports){
"use strict";var stringify=require(4),parse=require(3),formats=require(1);module.exports={formats:formats,parse:parse,stringify:stringify};
},{"1":1,"3":3,"4":4}],3:[function(require,module,exports){
"use strict";var getSideChannel=require(46),utils=require(5),has=Object.prototype.hasOwnProperty,isArray=Array.isArray,getPrototypeOf=Object.getPrototypeOf,isPlainContainer=function isPlainContainer(e){if(!e||"object"!=typeof e)return!1;if(isArray(e))return!0;var t=getPrototypeOf(e);return t===Object.prototype||null===t},emptyCopyOf=function emptyCopyOf(e){if(isArray(e)){var t=[];return t.length=e.length,t}return null===getPrototypeOf(e)?{__proto__:null}:{}},copyInput=function copyInput(e){for(var t=getSideChannel(),r={},i=[{source:e,target:r}],a=0;a<i.length;++a)for(var o=i[a].source,n=i[a].target,l=Object.keys(o),s=0;s<l.length;++s){var c=o[l[s]];if(isPlainContainer(c)){if(!t.has(c)){var p=emptyCopyOf(c);t.set(c,p),i[i.length]={source:c,target:p}}n[l[s]]=t.get(c)}else n[l[s]]=c}return r},defaults={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:utils.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictMerge:!0,strictNullHandling:!1,throwOnLimitExceeded:!1},interpretNumericEntities=function(e){return e.replace(/&#(\d+);/g,function(e,t){return String.fromCharCode(parseInt(t,10))})},parseArrayValue=function(e,t,r){if(e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1){if(t.throwOnLimitExceeded)for(var i=0,a=e.indexOf(",");a>-1;){if((i+=1)>=t.arrayLimit)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(1===t.arrayLimit?"":"s")+" allowed in an array.");a=e.indexOf(",",a+1)}return e.split(",")}if(t.throwOnLimitExceeded&&r>=t.arrayLimit)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(1===t.arrayLimit?"":"s")+" allowed in an array.");return e},isoSentinel="utf8=%26%2310003%3B",charsetSentinel="utf8=%E2%9C%93",parseValues=function parseQueryStringValues(e,t){var r={__proto__:null},i=t.ignoreQueryPrefix?e.replace(/^\?/,""):e;i=i.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var a=t.parameterLimit===1/0?void 0:t.parameterLimit,o=i.split(t.delimiter,t.throwOnLimitExceeded&&void 0!==a?a+1:a);if(t.throwOnLimitExceeded&&void 0!==a&&o.length>a)throw new RangeError("Parameter limit exceeded. Only "+a+" parameter"+(1===a?"":"s")+" allowed.");var n,l=-1,s=t.charset;if(t.charsetSentinel)for(n=0;n<o.length;++n)0===o[n].indexOf("utf8=")&&(o[n]===charsetSentinel?s="utf-8":o[n]===isoSentinel&&(s="iso-8859-1"),l=n,n=o.length);for(n=0;n<o.length;++n)if(n!==l){var c,p,d=o[n],u=d.indexOf("]="),y=-1===u?d.indexOf("="):u+1,f=y>1&&"[]"===d.slice(y-2,y);if(-1===y?(c=t.decoder(d,defaults.decoder,s,"key"),p=t.strictNullHandling?null:""):null!==(c=t.decoder(d.slice(0,y),defaults.decoder,s,"key"))&&(p=utils.maybeMap(parseArrayValue(d.slice(y+1),t,isArray(r[c])?r[c].length:0),function(e){return t.decoder(e,defaults.decoder,s,"value")})),p&&t.interpretNumericEntities&&"iso-8859-1"===s&&(p=interpretNumericEntities(String(p))),f&&(p=isArray(p)?[p]:p),t.comma&&isArray(p)&&p.length>t.arrayLimit&&(p=utils.combine([],p,t.arrayLimit,t.plainObjects,t.throwOnLimitExceeded)),null!==c){var m=has.call(r,c);m&&("combine"===t.duplicates||f)?r[c]=utils.combine(r[c],p,t.arrayLimit,t.plainObjects,t.throwOnLimitExceeded):m&&"last"!==t.duplicates||(r[c]=p)}}return r},parseObject=function(e,t,r,i){var a=0;if(e.length>0&&"[]"===e[e.length-1]){var o=e.slice(0,-1).join("");a=Array.isArray(t)&&t[o]?t[o].length:0}for(var n=i?t:parseArrayValue(t,r,a),l=e.length-1;l>=0;--l){var s,c=e[l];if("[]"===c&&r.parseArrays)s=utils.isOverflow(n)?n:r.allowEmptyArrays&&(""===n||r.strictNullHandling&&null===n)?[]:utils.combine([],n,r.arrayLimit,r.plainObjects,r.throwOnLimitExceeded);else{s=r.plainObjects?{__proto__:null}:{};var p="["===c.charAt(0)&&"]"===c.charAt(c.length-1)?c.slice(1,-1):c,d=r.decodeDotInKeys?p.replace(/%2E/g,"."):p,u=parseInt(d,10),y=!isNaN(u)&&c!==d&&String(u)===d&&u>=0&&r.parseArrays;if(r.parseArrays||""!==d)if(y&&u<r.arrayLimit)(s=[])[u]=n;else{if(y&&r.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+r.arrayLimit+" element"+(1===r.arrayLimit?"":"s")+" allowed in an array.");y?(s[u]=n,utils.markOverflow(s,u)):"__proto__"!==d&&(s[d]=n)}else s={0:n}}n=s}return n},topLevelDotsToBrackets=function topLevelDotsToBrackets(e){for(var t="",r=0,i=0;i<e.length;i+=1){var a=e.charCodeAt(i);if(91===a)r+=1,t+="[";else if(93===a)r>0&&(r-=1),t+="]";else if(46===a&&0===r&&i+1<e.length&&46!==e.charCodeAt(i+1)&&91!==e.charCodeAt(i+1)){for(var o=i+1,n=o;n<e.length&&46!==e.charCodeAt(n)&&91!==e.charCodeAt(n);)n+=1;t+="["+e.slice(o,n)+"]",i=n-1}else t+=e.charAt(i)}return t},splitKeyIntoSegments=function splitKeyIntoSegments(e,t){var r=t.allowDots?topLevelDotsToBrackets(e):e;if(t.depth<=0){if(!t.plainObjects&&has.call(Object.prototype,r)&&!t.allowPrototypes)return;return[r]}var i=[],a=r.indexOf("["),o=a>=0?r.slice(0,a):r;if(o){if(!t.plainObjects&&has.call(Object.prototype,o)&&!t.allowPrototypes)rLine truncated
},{"46":46,"5":5}],4:[function(require,module,exports){
"use strict";var getSideChannel=require(46),utils=require(5),formats=require(1),has=Object.prototype.hasOwnProperty,arrayPrefixGenerators={brackets:function brackets(e){return e+"[]"},comma:"comma",indices:function indices(e,r){return e+"["+r+"]"},repeat:function repeat(e){return e}},isArray=Array.isArray,push=Array.prototype.push,pushToArray=function(e,r){push.apply(e,isArray(r)?r:[r])},toISO=Date.prototype.toISOString,defaultFormat=formats.default,defaults={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,commaRoundTrip:!1,delimiter:"&",depth:1/0,encode:!0,encodeDotInKeys:!1,encoder:utils.encode,encodeValuesOnly:!1,filter:void 0,format:defaultFormat,formatter:formats.formatters[defaultFormat],indices:!1,serializeDate:function serializeDate(e){return toISO.call(e)},skipNulls:!1,strictNullHandling:!1},isNonNullishPrimitive=function isNonNullishPrimitive(e){return"string"==typeof e||"number"==typeof e||"boolean"==typeof e||"symbol"==typeof e||"bigint"==typeof e},sentinel={},stringify=function stringify(e,r,t,o,n,a,i,l,s,f,u,d,c,y,p,m,h,v,g,b){var w=e;if(b>g)throw new RangeError("Input depth exceeded depth option of "+g);for(var D=v,A=0,S=!1;void 0!==(D=D.get(sentinel))&&!S;){var E=D.get(e);if(A+=1,void 0!==E){if(E===A)throw new RangeError("Cyclic object value");S=!0}void 0===D.get(sentinel)&&(A=0)}if((w="function"==typeof f?f(r,w):w)instanceof Date?w=c(w):"comma"===t&&isArray(w)&&(w=utils.maybeMap(w,function(e){return e instanceof Date?c(e):e})),null===w){if(a)return p(s&&!m?s(r,defaults.encoder,h,"key",y):r);w=""}if(isNonNullishPrimitive(w)||utils.isBuffer(w))return s?[p(m?r:s(r,defaults.encoder,h,"key",y))+"="+p(s(w,defaults.encoder,h,"value",y))]:[p(r)+"="+p(String(w))];var N,O=[];if(void 0===w)return O;if("comma"===t&&isArray(w))m&&s&&(w=utils.maybeMap(w,function(e){return null==e?e:s(e,defaults.encoder,h,"value",y)})),N=[{value:w.length>0?utils.toCoercible(w).join(",")||null:void 0}];else if(isArray(f))N=f;else{var T=Object.keys(w);N=u?T.sort(u):T}var k=String(r),I=o&&isArray(w)&&1===w.length?k+"[]":k;if(n&&isArray(w)&&0===w.length&&0===Object.keys(w).length)return I+"[]";for(var P=0;P<N.length;++P){var x=N[P],K="object"==typeof x&&x&&void 0!==x.value?x.value:w[x];if(!i||null!==K){var z=d&&l?String(x).replace(/\./g,"%2E"):String(x),j=isArray(w)?"function"==typeof t?t(I,z):I:I+(d?"."+z:"["+z+"]");v.set(e,A);var F=getSideChannel();F.set(sentinel,v),pushToArray(O,stringify(K,j,t,o,n,a,i,l,"comma"===t&&m&&isArray(w)?null:s,f,u,d,c,y,p,m,h,F,g,b+1))}}return O},normalizeStringifyOptions=function normalizeStringifyOptions(e){if(!e)return defaults;if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var r=e.charset||defaults.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=formats.default;if(void 0!==e.format){if(!has.call(formats.formatters,e.format))throw new TypeError("Unknown format option provided.");t=e.format}var o,n=formats.formatters[t],a=defaults.filter;if(("function"==typeof e.filter||isArray(e.filter))&&(a=e.filter),o=has.call(arrayPrefixGenerators,e.arrayFormat)?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":defaults.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var i=void 0===e.allowDots?!0===e.encodeDotInKeys||defaults.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:defaults.addQueryPrefix,allowDots:i,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:defaults.allowEmptyArrays,arrayFormat:o,charset:r,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:defaults.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?defaults.delimiter:e.delimiter,depth:"number"==typeof e.depth?e.depth:defaults.depth,encode:"boolean"==typeof e.encode?e.encode:defaults.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:defaults.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:defaults.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:defaults.encodeValuesOnly,filter:a,format:t,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:defaults.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:defaults.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:deLine truncated
},{"1":1,"46":46,"5":5}],5:[function(require,module,exports){
"use strict";var formats=require(1),getSideChannel=require(46),defineProperty=require(14),has=Object.prototype.hasOwnProperty,isArray=Array.isArray,overflowChannel=getSideChannel(),markOverflow=function markOverflow(e,r){return overflowChannel.set(e,r),e},isOverflow=function isOverflow(e){return overflowChannel.has(e)},getMaxIndex=function getMaxIndex(e){return overflowChannel.get(e)},setMaxIndex=function setMaxIndex(e,r){overflowChannel.set(e,r)},conflictChannel=getSideChannel(),markConflict=function markConflict(e,r){return conflictChannel.set(e,r),e},isConflict=function isConflict(e){return conflictChannel.has(e)},getConflictIndex=function getConflictIndex(e){return conflictChannel.get(e)},hexTable=function(){for(var e=[],r=0;r<256;++r)e[e.length]="%"+((r<16?"0":"")+r.toString(16)).toUpperCase();return e}(),compactQueue=function compactQueue(e){for(;e.length>1;){var r=e.pop(),t=r.obj[r.prop];if(isArray(t)){for(var n=[],i=0;i<t.length;++i)void 0!==t[i]&&(n[n.length]=t[i]);r.obj[r.prop]=n}}},arrayToObject=function arrayToObject(e,r){for(var t=r&&r.plainObjects?{__proto__:null}:{},n=0;n<e.length;++n)void 0!==e[n]&&(t[n]=e[n]);return t},setProperty=function setProperty(e,r,t){"__proto__"===r&&defineProperty?defineProperty(e,r,{configurable:!0,enumerable:!0,value:t,writable:!0}):e[r]=t},maxNumericIndex=function maxNumericIndex(e,r){for(var t=r,n=Object.keys(e),i=0;i<n.length;++i){var o=parseInt(n[i],10);String(o)===n[i]&&o>t&&(t=o)}return t},limitedPair=function limitedPair(e,r,t){var n=[e,r];if(t&&"number"==typeof t.arrayLimit&&n.length>t.arrayLimit){if(t.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(1===t.arrayLimit?"":"s")+" allowed in an array.");return markOverflow(arrayToObject(n,t),1)}return n},merge=function merge(e,r,t){if(!r)return e;if("object"!=typeof r&&"function"!=typeof r){if(isArray(e)){var n=e.length;if(t&&"number"==typeof t.arrayLimit&&n>=t.arrayLimit){if(t.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(1===t.arrayLimit?"":"s")+" allowed in an array.");return markOverflow(arrayToObject(e.concat(r),t),n)}e[n]=r}else{if(!e||"object"!=typeof e)return limitedPair(e,r,t);if(isOverflow(e)){var i=getMaxIndex(e)+1;e[i]=r,setMaxIndex(e,i)}else if(t&&t.strictMerge&&isConflict(e)){var o=getConflictIndex(e)+1;if(t.throwOnLimitExceeded&&"number"==typeof t.arrayLimit&&o>=t.arrayLimit)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(1===t.arrayLimit?"":"s")+" allowed in an array.");e[o]=r,markConflict(e,o)}else{if(t&&t.strictMerge){var a=limitedPair(e,r,t);return isArray(a)?markConflict(a,1):a}(t&&(t.plainObjects||t.allowPrototypes)||!has.call(Object.prototype,r))&&(e[r]=!0)}}return e}if(!e||"object"!=typeof e){if(isOverflow(r)){for(var l=Object.keys(r),f=t&&t.plainObjects?{__proto__:null,0:e}:{0:e},c=0;c<l.length;c++)f[parseInt(l[c],10)+1]=r[l[c]];return markOverflow(f,getMaxIndex(r)+1)}var y=[e].concat(r);if(t&&"number"==typeof t.arrayLimit&&y.length>t.arrayLimit){if(t.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(1===t.arrayLimit?"":"s")+" allowed in an array.");return markOverflow(arrayToObject(y,t),y.length-1)}return y}var u=e;if(isArray(e)&&!isArray(r)&&(u=arrayToObject(e,t),isConflict(e)&&markConflict(u,e.length-1)),isArray(e)&&isArray(r)){if(r.forEach(function(r,n){if(has.call(e,n)){var i=e[n];i&&"object"==typeof i&&r&&"object"==typeof r?e[n]=merge(i,r,t):e[e.length]=r}else e[n]=r}),t&&"number"==typeof t.arrayLimit&&e.length>t.arrayLimit){if(t.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(1===t.arrayLimit?"":"s")+" allowed in an array.");return markOverflow(arrayToObject(e,t),e.length-1)}return e}return Object.keys(r).reduce(function(e,n){var i=r[n];if(has.call(e,n)?setProperty(e,n,merge(e[n],i,t)):setProperty(e,n,i),isOverflow(r)&&!isOverflow(e)&&markOverflow(e,maxNumericIndex(e,getMaxIndex(r))),isOverflow(e)){var o=parseInt(n,10);String(o)===n&&o>=0&&o>getMaxIndex(e)&&setMaxIndex(e,o)}if(isConflict(e)){var a=parseInt(n,10);String(a)===n&&a>getConflictIndex(e)&&markConflict(e,a)}return e},u)},assign=function assignSingleSource(e,r){return Object.keys(r).reduce(function(e,t){return setProperty(e,t,r[t]),e},e)},decode=function(e,r,t){if("string"==typeof e&&-1===e.indexOf("%"))return-1===e.indexOf("+")?e:e.replace(/\+/g," ");var n=e.replace(/\+/g," ");if("iso-8859-1"===t)return n.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(n)}catch(e){return n}},hasToPrimitive="function"==typeof Symbol&&"symbol"==typeof Symbol.toPrimitive,arrayJoin=Array.prototype.join,arrayToString=Array.prototype.toString,objectToString=Object.prototype.toString,toCoercible=function toCoercible(e,r){if(!e||"object"!=typeof e&&"function"!=typeof e)return e;if(hasToPrimitive&&null!=e[Symbol.toPrimitive])return e;if(isArray(e)&&e.toString===arrayToString&&e.join===arrayJoin){var t,n=r||gLine truncated
},{"1":1,"14":14,"46":46}],46:[function(require,module,exports){
"use strict";var $TypeError=require(20),inspect=require(42),getSideChannelList=require(43),getSideChannelMap=require(44),getSideChannelWeakMap=require(45),makeChannel=getSideChannelWeakMap||getSideChannelMap||getSideChannelList;module.exports=function getSideChannel(){var e,n={assert:function(e){if(!n.has(e)){var t=e&&Object(e)===e?"the given object key":inspect(e);throw new $TypeError("Side channel does not contain "+t)}},delete:function(n){return!!e&&e.delete(n)},get:function(n){return e&&e.get(n)},has:function(n){return!!e&&e.has(n)},set:function(n,t){e||(e=makeChannel()),e.set(n,t)}};return n};
},{"20":20,"42":42,"43":43,"44":44,"45":45}],14:[function(require,module,exports){
"use strict";var $defineProperty=Object.defineProperty||!1;if($defineProperty)try{$defineProperty({},"a",{value:1})}catch(e){$defineProperty=!1}module.exports=$defineProperty;
},{}],6:[function(require,module,exports){
},{}],7:[function(require,module,exports){
"use strict";var bind=require(24),$apply=require(8),$call=require(9),$reflectApply=require(11);module.exports=$reflectApply||bind.call($call,$apply);
},{"11":11,"24":24,"8":8,"9":9}],8:[function(require,module,exports){
"use strict";module.exports=Function.prototype.apply;
},{}],9:[function(require,module,exports){
"use strict";module.exports=Function.prototype.call;
},{}],24:[function(require,module,exports){
"use strict";var implementation=require(23);module.exports=Function.prototype.bind||implementation;
},{"23":23}],11:[function(require,module,exports){
"use strict";module.exports="undefined"!=typeof Reflect&&Reflect&&Reflect.apply;
},{}],10:[function(require,module,exports){
"use strict";var bind=require(24),$TypeError=require(20),$call=require(9),$actualApply=require(7);module.exports=function callBindBasic(r){if(r.length<1||"function"!=typeof r[0])throw new $TypeError("a function is required");return $actualApply(bind,$call,r)};
},{"20":20,"24":24,"7":7,"9":9}],20:[function(require,module,exports){
"use strict";module.exports=TypeError;
},{}],12:[function(require,module,exports){
"use strict";var GetIntrinsic=require(25),callBindBasic=require(10),$indexOf=callBindBasic([GetIntrinsic("%String.prototype.indexOf%")]);module.exports=function callBoundIntrinsic(i,n){var t=GetIntrinsic(i,!!n);return"function"==typeof t&&$indexOf(i,".prototype.")>-1?callBindBasic([t]):t};
},{"10":10,"25":25}],25:[function(require,module,exports){
"use strict";var undefined,$Object=require(22),$Error=require(16),$EvalError=require(15),$RangeError=require(17),$ReferenceError=require(18),$SyntaxError=require(19),$TypeError=require(20),$URIError=require(21),abs=require(34),floor=require(35),max=require(37),min=require(38),pow=require(39),round=require(40),sign=require(41),$Function=Function,getEvalledConstructor=function(r){try{return $Function('"use strict"; return ('+r+").constructor;")()}catch(r){}},$gOPD=require(30),$defineProperty=require(14),throwTypeError=function(){throw new $TypeError},ThrowTypeError=$gOPD?function(){try{return throwTypeError}catch(r){try{return $gOPD(arguments,"callee").get}catch(r){return throwTypeError}}}():throwTypeError,hasSymbols=require(31)(),getProto=require(28),$ObjectGPO=require(26),$ReflectGPO=require(27),$apply=require(8),$call=require(9),needsEval={},TypedArray="undefined"!=typeof Uint8Array&&getProto?getProto(Uint8Array):undefined,INTRINSICS={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":hasSymbols&&getProto?getProto([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":needsEval,"%AsyncGenerator%":needsEval,"%AsyncGeneratorFunction%":needsEval,"%AsyncIteratorPrototype%":needsEval,"%Atomics%":"undefined"==typeof Atomics?undefined:Atomics,"%BigInt%":"undefined"==typeof BigInt?undefined:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?undefined:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?undefined:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?undefined:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":$Error,"%eval%":eval,"%EvalError%":$EvalError,"%Float16Array%":"undefined"==typeof Float16Array?undefined:Float16Array,"%Float32Array%":"undefined"==typeof Float32Array?undefined:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?undefined:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?undefined:FinalizationRegistry,"%Function%":$Function,"%GeneratorFunction%":needsEval,"%Int8Array%":"undefined"==typeof Int8Array?undefined:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?undefined:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":hasSymbols&&getProto?getProto(getProto([][Symbol.iterator]())):undefined,"%JSON%":"object"==typeof JSON?JSON:undefined,"%Map%":"undefined"==typeof Map?undefined:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&hasSymbols&&getProto?getProto((new Map)[Symbol.iterator]()):undefined,"%Math%":Math,"%Number%":Number,"%Object%":$Object,"%Object.getOwnPropertyDescriptor%":$gOPD,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?undefined:Promise,"%Proxy%":"undefined"==typeof Proxy?undefined:Proxy,"%RangeError%":$RangeError,"%ReferenceError%":$ReferenceError,"%Reflect%":"undefined"==typeof Reflect?undefined:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?undefined:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&hasSymbols&&getProto?getProto((new Set)[Symbol.iterator]()):undefined,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":hasSymbols&&getProto?getProto(""[Symbol.iterator]()):undefined,"%Symbol%":hasSymbols?Symbol:undefined,"%SyntaxError%":$SyntaxError,"%ThrowTypeError%":ThrowTypeError,"%TypedArray%":TypedArray,"%TypeError%":$TypeError,"%Uint8Array%":"undefined"==typeof Uint8Array?undefined:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?undefined:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?undefined:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?undefined:Uint32Array,"%URIError%":$URIError,"%WeakMap%":"undefined"==typeof WeakMap?undefined:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?undefined:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?undefined:WeakSet,"%Function.prototype.call%":$call,"%Function.prototype.apply%":$apply,"%Object.defineProperty%":$defineProperty,"%Object.getPrototypeOf%":$ObjectGPO,"%Math.abs%":abs,"%Math.floor%":floor,"%Math.max%":max,"%Math.min%":min,"%Math.pow%":pow,"%Math.round%":round,"%Math.sign%":sign,"%Reflect.getPrototypeOf%":$ReflectGPO};if(getProto)try{null.error}catch(r){var errorProto=getProto(getProto(r));INTRINSICS["%Error.prototype%"]=errorProto}var doEval=function doEval(r){var e;if("%AsyncFunction%"===r)e=getEvalledConstructor("async function () {}");else if("%GeneratorFunction%"===r)e=getEvalledConstructor("function* () {}");else if("%AsyncGeneratorFunction%"===r)e=getEvalledConstructor("async function* () {}");else if("%AsyncGenerator%"===r){vLine truncated
},{"14":14,"15":15,"16":16,"17":17,"18":18,"19":19,"20":20,"21":21,"22":22,"24":24,"26":26,"27":27,"28":28,"30":30,"31":31,"33":33,"34":34,"35":35,"37":37,"38":38,"39":39,"40":40,"41":41,"8":8,"9":9}],13:[function(require,module,exports){
"use strict";var hasProtoAccessor,callBind=require(10),gOPD=require(30);try{hasProtoAccessor=[].__proto__===Array.prototype}catch(t){if(!t||"object"!=typeof t||!("code"in t)||"ERR_PROTO_ACCESS"!==t.code)throw t}var desc=!!hasProtoAccessor&&gOPD&&gOPD(Object.prototype,"__proto__"),$Object=Object,$getPrototypeOf=$Object.getPrototypeOf;module.exports=desc&&"function"==typeof desc.get?callBind([desc.get]):"function"==typeof $getPrototypeOf&&function getDunder(t){return $getPrototypeOf(null==t?t:$Object(t))};
},{"10":10,"30":30}],30:[function(require,module,exports){
"use strict";var $gOPD=require(29);if($gOPD)try{$gOPD([],"length")}catch(g){$gOPD=null}module.exports=$gOPD;
},{"29":29}],15:[function(require,module,exports){
"use strict";module.exports=EvalError;
},{}],16:[function(require,module,exports){
"use strict";module.exports=Error;
},{}],17:[function(require,module,exports){
"use strict";module.exports=RangeError;
},{}],18:[function(require,module,exports){
"use strict";module.exports=ReferenceError;
},{}],19:[function(require,module,exports){
"use strict";module.exports=SyntaxError;
},{}],21:[function(require,module,exports){
"use strict";module.exports=URIError;
},{}],22:[function(require,module,exports){
"use strict";module.exports=Object;
},{}],23:[function(require,module,exports){
"use strict";var ERROR_MESSAGE="Function.prototype.bind called on incompatible ",toStr=Object.prototype.toString,max=Math.max,funcType="[object Function]",concatty=function concatty(t,n){for(var r=[],o=0;o<t.length;o+=1)r[o]=t[o];for(var e=0;e<n.length;e+=1)r[e+t.length]=n[e];return r},slicy=function slicy(t,n){for(var r=[],o=n||0,e=0;o<t.length;o+=1,e+=1)r[e]=t[o];return r},joiny=function(t,n){for(var r="",o=0;o<t.length;o+=1)r+=t[o],o+1<t.length&&(r+=n);return r};module.exports=function bind(t){var n=this;if("function"!=typeof n||toStr.apply(n)!==funcType)throw new TypeError(ERROR_MESSAGE+n);for(var r,o=slicy(arguments,1),e=max(0,n.length-o.length),i=[],c=0;c<e;c++)i[c]="$"+c;if(r=Function("binder","return function ("+joiny(i,",")+"){ return binder.apply(this,arguments); }")(function(){if(this instanceof r){var e=n.apply(this,concatty(o,arguments));return Object(e)===e?e:this}return n.apply(t,concatty(o,arguments))}),n.prototype){var p=function Empty(){};p.prototype=n.prototype,r.prototype=new p,p.prototype=null}return r};
},{}],39:[function(require,module,exports){
"use strict";module.exports=Math.pow;
},{}],35:[function(require,module,exports){
"use strict";module.exports=Math.floor;
},{}],38:[function(require,module,exports){
"use strict";module.exports=Math.min;
},{}],34:[function(require,module,exports){
"use strict";module.exports=Math.abs;
},{}],40:[function(require,module,exports){
"use strict";module.exports=Math.round;
},{}],37:[function(require,module,exports){
"use strict";module.exports=Math.max;
},{}],27:[function(require,module,exports){
"use strict";module.exports="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null;
},{}],41:[function(require,module,exports){
"use strict";var $isNaN=require(36);module.exports=function sign(i){return $isNaN(i)||0===i?i:i<0?-1:1};
},{"36":36}],26:[function(require,module,exports){
"use strict";var $Object=require(22);module.exports=$Object.getPrototypeOf||null;
},{"22":22}],31:[function(require,module,exports){
"use strict";var origSymbol="undefined"!=typeof Symbol&&Symbol,hasSymbolSham=require(32);module.exports=function hasNativeSymbols(){return"function"==typeof origSymbol&&"function"==typeof Symbol&&"symbol"==typeof origSymbol("foo")&&"symbol"==typeof Symbol("bar")&&hasSymbolSham()};
},{"32":32}],33:[function(require,module,exports){
"use strict";var call=Function.prototype.call,$hasOwn=Object.prototype.hasOwnProperty,bind=require(24);module.exports=bind.call(call,$hasOwn);
},{"24":24}],28:[function(require,module,exports){
"use strict";var reflectGetProto=require(27),originalGetProto=require(26),getDunderProto=require(13);module.exports=reflectGetProto?function getProto(t){return reflectGetProto(t)}:originalGetProto?function getProto(t){if(!t||"object"!=typeof t&&"function"!=typeof t)throw new TypeError("getProto: not an object");return originalGetProto(t)}:getDunderProto?function getProto(t){return getDunderProto(t)}:null;
},{"13":13,"26":26,"27":27}],29:[function(require,module,exports){
"use strict";module.exports=Object.getOwnPropertyDescriptor;
},{}],32:[function(require,module,exports){
"use strict";module.exports=function hasSymbols(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var t={},e=Symbol("test"),r=Object(e);if("string"==typeof e)return!1;if("[object Symbol]"!==Object.prototype.toString.call(e))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(var o in t[e]=42,t)return!1;if("function"==typeof Object.keys&&0!==Object.keys(t).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(t).length)return!1;var n=Object.getOwnPropertySymbols(t);if(1!==n.length||n[0]!==e)return!1;if(!Object.prototype.propertyIsEnumerable.call(t,e))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var y=Object.getOwnPropertyDescriptor(t,e);if(42!==y.value||!0!==y.enumerable)return!1}return!0};
},{}],36:[function(require,module,exports){
"use strict";module.exports=Number.isNaN||function isNaN(e){return e!=e};
},{}],42:[function(require,module,exports){
(function (global){(function (){
var hasMap="function"==typeof Map&&Map.prototype,mapSizeDescriptor=Object.getOwnPropertyDescriptor&&hasMap?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,mapSize=hasMap&&mapSizeDescriptor&&"function"==typeof mapSizeDescriptor.get?mapSizeDescriptor.get:null,mapForEach=hasMap&&Map.prototype.forEach,hasSet="function"==typeof Set&&Set.prototype,setSizeDescriptor=Object.getOwnPropertyDescriptor&&hasSet?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,setSize=hasSet&&setSizeDescriptor&&"function"==typeof setSizeDescriptor.get?setSizeDescriptor.get:null,setForEach=hasSet&&Set.prototype.forEach,hasWeakMap="function"==typeof WeakMap&&WeakMap.prototype,weakMapHas=hasWeakMap?WeakMap.prototype.has:null,hasWeakSet="function"==typeof WeakSet&&WeakSet.prototype,weakSetHas=hasWeakSet?WeakSet.prototype.has:null,hasWeakRef="function"==typeof WeakRef&&WeakRef.prototype,weakRefDeref=hasWeakRef?WeakRef.prototype.deref:null,booleanValueOf=Boolean.prototype.valueOf,objectToString=Object.prototype.toString,functionToString=Function.prototype.toString,$match=String.prototype.match,$slice=String.prototype.slice,$replace=String.prototype.replace,$toUpperCase=String.prototype.toUpperCase,$toLowerCase=String.prototype.toLowerCase,$test=RegExp.prototype.test,$concat=Array.prototype.concat,$join=Array.prototype.join,$arrSlice=Array.prototype.slice,$floor=Math.floor,bigIntValueOf="function"==typeof BigInt?BigInt.prototype.valueOf:null,gOPS=Object.getOwnPropertySymbols,symToString="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,hasShammedSymbols="function"==typeof Symbol&&"object"==typeof Symbol.iterator,toStringTag="function"==typeof Symbol&&Symbol.toStringTag&&(Symbol.toStringTag,1)?Symbol.toStringTag:null,isEnumerable=Object.prototype.propertyIsEnumerable,gPO=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(t){return t.__proto__}:null);function addNumericSeparator(t,e){if(t===1/0||t===-1/0||t!=t||t&&t>-1e3&&t<1e3||$test.call(/e/,e))return e;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof t){var n=t<0?-$floor(-t):$floor(t);if(n!==t){var o=String(n),i=$slice.call(e,o.length+1);return $replace.call(o,r,"$&_")+"."+$replace.call($replace.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return $replace.call(e,r,"$&_")}var utilInspect=require(6),inspectCustom=utilInspect.custom,inspectSymbol=isSymbol(inspectCustom)?inspectCustom:null,quotes={__proto__:null,double:'"',single:"'"},quoteREs={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};function wrapQuotes(t,e,r){var n=r.quoteStyle||e,o=quotes[n];return o+t+o}function quote(t){return $replace.call(String(t),/"/g,"&quot;")}function canTrustToString(t){return!toStringTag||!("object"==typeof t&&(toStringTag in t||void 0!==t[toStringTag]))}function isArray(t){return"[object Array]"===toStr(t)&&canTrustToString(t)}function isDate(t){return"[object Date]"===toStr(t)&&canTrustToString(t)}function isRegExp(t){return"[object RegExp]"===toStr(t)&&canTrustToString(t)}function isError(t){return"[object Error]"===toStr(t)&&canTrustToString(t)}function isString(t){return"[object String]"===toStr(t)&&canTrustToString(t)}function isNumber(t){return"[object Number]"===toStr(t)&&canTrustToString(t)}function isBoolean(t){return"[object Boolean]"===toStr(t)&&canTrustToString(t)}function isSymbol(t){if(hasShammedSymbols)return t&&"object"==typeof t&&t instanceof Symbol;if("symbol"==typeof t)return!0;if(!t||"object"!=typeof t||!symToString)return!1;try{return symToString.call(t),!0}catch(t){}return!1}function isBigInt(t){if(!t||"object"!=typeof t||!bigIntValueOf)return!1;try{return bigIntValueOf.call(t),!0}catch(t){}return!1}module.exports=function inspect_(t,e,r,n){var o=e||{};if(has(o,"quoteStyle")&&!has(quotes,o.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(has(o,"maxStringLength")&&("number"==typeof o.maxStringLength?o.maxStringLength<0&&o.maxStringLength!==1/0:null!==o.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var i=!has(o,"customInspect")||o.customInspect;if("boolean"!=typeof i&&"symbol"!==i)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(has(o,"indent")&&null!==o.indent&&"\t"!==o.indent&&!(parseInt(o.indent,10)===o.indent&&o.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(has(o,"numericSeparator")&&"boolean"!=typeof o.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var a=o.numericSeparator;if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return inspectString(t,o);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var c=String(t);return a?addNumericSeparator(t,c):c}if("bigint"==typeof t){var l=String(t)+"n";returnLine truncated
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"6":6}],43:[function(require,module,exports){
"use strict";var inspect=require(42),$TypeError=require(20),listGetNode=function(e,t,n){for(var i,r=e;null!=(i=r.next);r=i)if(i.key===t)return r.next=i.next,n||(i.next=e.next,e.next=i),i},listGet=function(e,t){if(e){var n=listGetNode(e,t);return n&&n.value}},listSet=function(e,t,n){var i=listGetNode(e,t);i?i.value=n:e.next={key:t,next:e.next,value:n}},listHas=function(e,t){return!!e&&!!listGetNode(e,t)},listDelete=function(e,t){if(e)return listGetNode(e,t,!0)};module.exports=function getSideChannelList(){var e,t={assert:function(e){if(!t.has(e))throw new $TypeError("Side channel does not contain "+inspect(e))},delete:function(t){var n=listDelete(e,t);return n&&e&&!e.next&&(e=void 0),!!n},get:function(t){return listGet(e,t)},has:function(t){return listHas(e,t)},set:function(t,n){e||(e={next:void 0}),listSet(e,t,n)}};return t};
},{"20":20,"42":42}],44:[function(require,module,exports){
"use strict";var GetIntrinsic=require(25),callBound=require(12),inspect=require(42),$TypeError=require(20),$Map=GetIntrinsic("%Map%",!0),$mapGet=callBound("Map.prototype.get",!0),$mapSet=callBound("Map.prototype.set",!0),$mapHas=callBound("Map.prototype.has",!0),$mapDelete=callBound("Map.prototype.delete",!0),$mapSize=callBound("Map.prototype.size",!0);module.exports=!!$Map&&function getSideChannelMap(){var e,t={assert:function(e){if(!t.has(e))throw new $TypeError("Side channel does not contain "+inspect(e))},delete:function(t){if(e){var n=$mapDelete(e,t);return 0===$mapSize(e)&&(e=void 0),n}return!1},get:function(t){if(e)return $mapGet(e,t)},has:function(t){return!!e&&$mapHas(e,t)},set:function(t,n){e||(e=new $Map),$mapSet(e,t,n)}};return t};
},{"12":12,"20":20,"25":25,"42":42}],45:[function(require,module,exports){
"use strict";var GetIntrinsic=require(25),callBound=require(12),inspect=require(42),getSideChannelMap=require(44),$TypeError=require(20),$WeakMap=GetIntrinsic("%WeakMap%",!0),$weakMapGet=callBound("WeakMap.prototype.get",!0),$weakMapSet=callBound("WeakMap.prototype.set",!0),$weakMapHas=callBound("WeakMap.prototype.has",!0),$weakMapDelete=callBound("WeakMap.prototype.delete",!0);module.exports=$WeakMap?function getSideChannelWeakMap(){var e,t,a={assert:function(e){if(!a.has(e))throw new $TypeError("Side channel does not contain "+inspect(e))},delete:function(a){if($WeakMap&&a&&("object"==typeof a||"function"==typeof a)){if(e)return $weakMapDelete(e,a)}else if(getSideChannelMap&&t)return t.delete(a);return!1},get:function(a){return $WeakMap&&a&&("object"==typeof a||"function"==typeof a)&&e?$weakMapGet(e,a):t&&t.get(a)},has:function(a){return $WeakMap&&a&&("object"==typeof a||"function"==typeof a)&&e?$weakMapHas(e,a):!!t&&t.has(a)},set:function(a,n){$WeakMap&&a&&("object"==typeof a||"function"==typeof a)?(e||(e=new $WeakMap),$weakMapSet(e,a,n)):getSideChannelMap&&(t||(t=getSideChannelMap()),t.set(a,n))}};return a}:getSideChannelMap;
},{"12":12,"20":20,"25":25,"42":42,"44":44}]},{},[2])(2)
});
@@ -0,0 +1,21 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const Bandage = createLucideIcon("Bandage", [
["path", { d: "M10 10.01h.01", key: "1e9xi7" }],
["path", { d: "M10 14.01h.01", key: "ac23bv" }],
["path", { d: "M14 10.01h.01", key: "2wfrvf" }],
["path", { d: "M14 14.01h.01", key: "8tw8yn" }],
["path", { d: "M18 6v11.5", key: "dkbidh" }],
["path", { d: "M6 6v12", key: "vkc79e" }],
["rect", { x: "2", y: "6", width: "20", height: "12", rx: "2", key: "1wpnh2" }]
]);
export { Bandage as default };
//# sourceMappingURL=bandage.js.map
@@ -0,0 +1,7 @@
import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint';
/**
* Enables each the rules provided as a part of typescript-eslint. Note that many rules are not applicable in all codebases, or are meant to be configured.
* @see {@link https://typescript-eslint.io/users/configs#all}
*/
declare const _default: (plugin: FlatConfig.Plugin, parser: FlatConfig.Parser) => FlatConfig.ConfigArray;
export default _default;
@@ -0,0 +1 @@
{"version":3,"file":"apply-generator.mjs","sources":["../../../../../src/animation/waapi/utils/apply-generator.ts"],"sourcesContent":["import { ValueTransition } from \"../../../animation/types\"\nimport { supportsLinearEasing } from \"../../../utils/supports/linear-easing\"\nimport { isGenerator } from \"../../generators/utils/is-generator\"\n\nexport function applyGeneratorOptions({\n type,\n ...options\n}: ValueTransition): ValueTransition {\n if (isGenerator(type) && supportsLinearEasing()) {\n return type.applyToOptions!(options)\n } else {\n options.duration ??= 300\n options.ease ??= \"easeOut\"\n }\n\n return options\n}\n"],"names":[],"mappings":";;;AAIM,SAAU,qBAAqB,CAAC,EAClC,IAAI,EACJ,GAAG,OAAO,EACI,EAAA;IACd,IAAI,WAAW,CAAC,IAAI,CAAC,IAAI,oBAAoB,EAAE,EAAE;AAC7C,QAAA,OAAO,IAAI,CAAC,cAAe,CAAC,OAAO,CAAC;IACxC;SAAO;QACH,OAAO,CAAC,QAAQ,KAAhB,OAAO,CAAC,QAAQ,GAAK,GAAG,CAAA;QACxB,OAAO,CAAC,IAAI,KAAZ,OAAO,CAAC,IAAI,GAAK,SAAS,CAAA;IAC9B;AAEA,IAAA,OAAO,OAAO;AAClB;;;;"}
@@ -0,0 +1,70 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.JSONSchema = exports.JSONSchemaGenerator = exports.toJSONSchema = exports.locales = exports.regexes = exports.toZod = exports.util = void 0;
__exportStar(require("./core.cjs"), exports);
__exportStar(require("./parse.cjs"), exports);
__exportStar(require("./errors.cjs"), exports);
__exportStar(require("./schemas.cjs"), exports);
__exportStar(require("./memoizer.cjs"), exports);
__exportStar(require("./checks.cjs"), exports);
__exportStar(require("./versions.cjs"), exports);
exports.util = __importStar(require("./util.cjs"));
var util_js_1 = require("./util.cjs");
Object.defineProperty(exports, "toZod", { enumerable: true, get: function () { return util_js_1.toZod; } });
exports.regexes = __importStar(require("./regexes.cjs"));
exports.locales = __importStar(require("../locales/index.cjs"));
__exportStar(require("./registries.cjs"), exports);
__exportStar(require("./doc.cjs"), exports);
__exportStar(require("./compile.cjs"), exports);
__exportStar(require("./api.cjs"), exports);
__exportStar(require("./to-json-schema.cjs"), exports);
var json_schema_processors_js_1 = require("./json-schema-processors.cjs");
Object.defineProperty(exports, "toJSONSchema", { enumerable: true, get: function () { return json_schema_processors_js_1.toJSONSchema; } });
var json_schema_generator_js_1 = require("./json-schema-generator.cjs");
Object.defineProperty(exports, "JSONSchemaGenerator", { enumerable: true, get: function () { return json_schema_generator_js_1.JSONSchemaGenerator; } });
exports.JSONSchema = __importStar(require("./json-schema.cjs"));
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"_E"},B:{"1":"_ZE","2":"_5B"},C:{"1":"_pF","2":"_WR"},D:{"1":"_KK","2":"_SO","16":"_kN","388":"_TC _SE"},E:{"1":"_YE","2":"_qB","516":"_7Q"},F:{"1":"_SI","2":"_HM"},G:{"1":"_AB","2":"_XB"},H:{"2":"1D"},I:{"1":"I","2":"_n","16":"_nJ"},J:{"1":"A","2":"D"},K:{"1":"_ZB","16":"_cB"},L:{"1":"I"},M:{"1":"YC"},N:{"2":"_A"},O:{"1":"bC"},P:{"1":"_U","129":"J"},Q:{"1":"JE"},R:{"1":"KE"},S:{"1":"ME","2":"LE"}},B:6,C:"FLAC audio format",D:true};
@@ -0,0 +1,55 @@
import { DOM_RENDERER, DOM_STASH } from "../constants.js";
import { Context as Context$1 } from "../context.js";
import { Child, FC, JSXNode, Props } from "../base.js";
//#region src/jsx/dom/render.d.ts
export type HasRenderToDom = FC<any> & {
[DOM_RENDERER]: FC<any>;
};
export type ErrorHandler = (error: any, retry: () => void) => Child | undefined;
type Container = HTMLElement | DocumentFragment;
type LocalJSXContexts = [Context$1<unknown>, unknown][] | undefined;
type SupportedElement = HTMLElement | SVGElement | MathMLElement;
export type PreserveNodeType = 1 | 2;
export type NodeObject = {
pP: Props | undefined;
nN: Node | undefined;
vC: Node[];
pC?: Node[];
vR: Node[];
n?: string;
f?: boolean;
s?: boolean;
c: Container | undefined;
e: SupportedElement | Text | undefined;
p?: PreserveNodeType;
a?: boolean;
o?: NodeObject;
[DOM_STASH]: [number, any[][], LocalJSXContexts, [Context, Function, NodeObject]] | [number, any[][]];
} & JSXNode;
type NodeString = {
t: string;
d: boolean;
s?: boolean;
} & {
e?: Text;
vC: undefined;
nN: undefined;
p?: true;
key: undefined;
tag: undefined;
};
export type Node = NodeString | NodeObject;
export type PendingType = 0 | 1 | 2;
export type UpdateHook = (context: Context, node: Node, cb: (context: Context) => void) => Promise<void>;
export type Context = [PendingType, boolean, UpdateHook, boolean, boolean, [Context, Function, NodeObject][]] | [PendingType, boolean, UpdateHook, boolean] | [PendingType, boolean, UpdateHook] | [PendingType, boolean] | [PendingType] | [];
export declare const buildDataStack: [Context, Node][];
export declare const getNameSpaceContext: () => Context$1<string> | undefined;
export declare const build: (context: Context, node: NodeObject, children?: Child[]) => void;
export declare const buildNode: (node: Child) => Node | undefined;
export declare const update: (context: Context, node: NodeObject) => Promise<NodeObject | undefined>;
export declare const renderNode: (node: NodeObject, container: Container) => void;
export declare const render: (jsxNode: Child, container: Container) => void;
export declare const flushSync: (callback: () => void) => void;
export declare const createPortal: (children: Child, container: HTMLElement, key?: string) => Child;
//#endregion
export {};
@@ -0,0 +1,22 @@
"use strict";
const addMonths = require("./addMonths.js");
function monthDiff(a, b) {
const aTime = +a;
const bTime = +b;
if (aTime < bTime) {
return -monthDiff(b, a);
}
const wholeMonthDiff = (b.getFullYear() - a.getFullYear()) * 12 + (b.getMonth() - a.getMonth());
const anchor = +addMonths(new Date(aTime), wholeMonthDiff);
let anchor2;
let adjust;
if (bTime < anchor) {
anchor2 = +addMonths(new Date(aTime), wholeMonthDiff - 1);
adjust = (bTime - anchor) / (anchor - anchor2);
} else {
anchor2 = +addMonths(new Date(aTime), wholeMonthDiff + 1);
adjust = (bTime - anchor) / (anchor2 - anchor);
}
return -(wholeMonthDiff + adjust) || 0;
}
exports.monthDiff = monthDiff;
@@ -0,0 +1,34 @@
//#region ../core-internal/src/validators/dialects.ts
/**
* Canonical `$schema` URIs per supported dialect (http + https variants, trailing-`#` stripped).
*/
const DRAFT_2020_12_URIS = new Set(["https://json-schema.org/draft/2020-12/schema", "http://json-schema.org/draft/2020-12/schema"]);
const DRAFT_2019_09_URIS = new Set(["https://json-schema.org/draft/2019-09/schema", "http://json-schema.org/draft/2019-09/schema"]);
const DRAFT_07_URIS = new Set(["https://json-schema.org/draft-07/schema", "http://json-schema.org/draft-07/schema"]);
const DRAFT_06_URIS = new Set(["https://json-schema.org/draft-06/schema", "http://json-schema.org/draft-06/schema"]);
/**
* Whether a `$schema` value declares the 2019-09 dialect — the only supported dialect with
* `$recursiveRef`/`$recursiveAnchor`. Non-throwing (unlike {@linkcode declaredDialect}) so
* wire-layer callers can consult it for documents whose dialect may be unsupported.
*/
function declares2019Dialect($schema) {
return typeof $schema === "string" && DRAFT_2019_09_URIS.has($schema.replace(/#$/, ""));
}
/**
* Classify a schema's declared `$schema` dialect. No `$schema` (or a non-string one) means
* 2020-12. Any other dialect throws a plain `Error` with a clear message rather than letting the
* engine crash on an opaque internal error or silently mis-validate; `remedy` names the calling
* provider's escape hatch in that message.
*/
function declaredDialect(schema, remedy) {
if (!("$schema" in schema) || typeof schema.$schema !== "string") return "2020-12";
const declared = schema.$schema.replace(/#$/, "");
if (DRAFT_2020_12_URIS.has(declared)) return "2020-12";
if (DRAFT_2019_09_URIS.has(declared)) return "2019-09";
if (DRAFT_07_URIS.has(declared) || DRAFT_06_URIS.has(declared)) return "draft-7";
throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema.$schema.slice(0, 200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`);
}
//#endregion
export { declares2019Dialect as n, declaredDialect as t };
//# sourceMappingURL=dialects-DoSzNhcb.mjs.map
@@ -0,0 +1,17 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const AlignVerticalJustifyStart = createLucideIcon("AlignVerticalJustifyStart", [
["rect", { width: "14", height: "6", x: "5", y: "16", rx: "2", key: "1i8z2d" }],
["rect", { width: "10", height: "6", x: "7", y: "6", rx: "2", key: "13squh" }],
["path", { d: "M2 2h20", key: "1ennik" }]
]);
export { AlignVerticalJustifyStart as default };
//# sourceMappingURL=align-vertical-justify-start.js.map
@@ -0,0 +1 @@
{"version":3,"file":"code.js","sourceRoot":"","sources":["../../../lib/compile/codegen/code.ts"],"names":[],"mappings":";;;AAAA,kEAAkE;AAClE,MAAsB,WAAW;CAKhC;AALD,kCAKC;AAEY,QAAA,UAAU,GAAG,uBAAuB,CAAA;AAEjD,MAAa,IAAK,SAAQ,WAAW;IAEnC,YAAY,CAAS;QACnB,KAAK,EAAE,CAAA;QACP,IAAI,CAAC,kBAAU,CAAC,IAAI,CAAC,CAAC,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAA;QACpF,IAAI,CAAC,GAAG,GAAG,CAAC,CAAA;IACd,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,GAAG,CAAA;IACjB,CAAC;IAED,QAAQ;QACN,OAAO,KAAK,CAAA;IACd,CAAC;IAED,IAAI,KAAK;QACP,OAAO,EAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,EAAC,CAAA;IACxB,CAAC;CACF;AAnBD,oBAmBC;AAED,MAAa,KAAM,SAAQ,WAAW;IAKpC,YAAY,IAAkC;QAC5C,KAAK,EAAE,CAAA;QACP,IAAI,CAAC,MAAM,GAAG,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACxD,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,GAAG,CAAA;IACjB,CAAC;IAED,QAAQ;QACN,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC;YAAE,OAAO,KAAK,CAAA;QACxC,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAA;QAC3B,OAAO,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,IAAI,CAAA;IACrC,CAAC;IAED,IAAI,GAAG;;QACL,OAAO,OAAC,IAAI,CAAC,IAAI,oCAAT,IAAI,CAAC,IAAI,GAAK,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAS,EAAE,CAAW,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,EAAC,CAAA;IACvF,CAAC;IAED,IAAI,KAAK;;QACP,OAAO,OAAC,IAAI,CAAC,MAAM,oCAAX,IAAI,CAAC,MAAM,GAAK,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,KAAgB,EAAE,CAAC,EAAE,EAAE;YACjE,IAAI,CAAC,YAAY,IAAI;gBAAE,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAA;YAC7D,OAAO,KAAK,CAAA;QACd,CAAC,EAAE,EAAE,CAAC,EAAC,CAAA;IACT,CAAC;CACF;AA9BD,sBA8BC;AAUY,QAAA,GAAG,GAAG,IAAI,KAAK,CAAC,EAAE,CAAC,CAAA;AAIhC,SAAgB,CAAC,CAAC,IAA0B,EAAE,GAAG,IAAe;IAC9D,MAAM,IAAI,GAAe,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAA;IAClC,IAAI,CAAC,GAAG,CAAC,CAAA;IACT,OAAO,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QACvB,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAA;QACzB,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;IACtB,CAAC;IACD,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC,CAAA;AACxB,CAAC;AARD,cAQC;AAED,MAAM,IAAI,GAAG,IAAI,KAAK,CAAC,GAAG,CAAC,CAAA;AAE3B,SAAgB,GAAG,CAAC,IAA0B,EAAE,GAAG,IAA4B;IAC7E,MAAM,IAAI,GAAe,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IACjD,IAAI,CAAC,GAAG,CAAC,CAAA;IACT,OAAO,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QACvB,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QACf,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAA;QACzB,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;IAC3C,CAAC;IACD,QAAQ,CAAC,IAAI,CAAC,CAAA;IACd,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC,CAAA;AACxB,CAAC;AAVD,kBAUC;AAED,SAAgB,UAAU,CAAC,IAAgB,EAAE,GAAuB;IAClE,IAAI,GAAG,YAAY,KAAK;QAAE,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,MAAM,CAAC,CAAA;SAC7C,IAAI,GAAG,YAAY,IAAI;QAAE,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;;QACvC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAA;AAClC,CAAC;AAJD,gCAIC;AAED,SAAS,QAAQ,CAAC,IAAgB;IAChC,IAAI,CAAC,GAAG,CAAC,CAAA;IACT,OAAO,CAAC,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC3B,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;YACrB,MAAM,GAAG,GAAG,cAAc,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;YACpD,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;gBACtB,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAA;gBAC1B,SAAQ;YACV,CAAC;YACD,IAAI,CAAC,CAAC,EAAE,CAAC,GAAG,GAAG,CAAA;QACjB,CAAC;QACD,CAAC,EAAE,CAAA;IACL,CAAC;AACH,CAAC;AAED,SAAS,cAAc,CAAC,CAAW,EAAE,CAAW;IAC9C,IAAI,CAAC,KAAK,IAAI;QAAE,OAAO,CAAC,CAAA;IACxB,IAAI,CAAC,KAAK,IAAI;QAAE,OAAO,CAAC,CAAA;IACxB,IAAI,OAAO,CAAC,IAAI,QAAQ,EAAE,CAAC;QACzB,IAAI,CAAC,YAAY,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;YAAE,OAAM;QACxD,IAAI,OAAO,CAAC,IAAI,QAAQ;YAAE,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAA;QACzD,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG;YAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;QACpD,OAAM;IACR,CAAC;IACD,IAAI,OAAO,CAAC,IAAI,QAAQ,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC,CAAC,YAAY,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAA;IAC7F,OAAM;AACR,CAAC;AAED,SAAgB,SAAS,CAAC,EAAQ,EAAE,EAAQ;IAC1C,OAAO,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAA,GAAG,EAAE,GAAG,EAAE,EAAE,CAAA;AAClE,CAAC;AAFD,8BAEC;AAED,gCAAgC;AAChC,SAAS,WAAW,CAAC,CAA+C;IAClE,OAAO,OAAO,CAAC,IAAI,QAAQ,IAAI,OAAO,CAAC,IAAI,SAAS,IAAI,CAAC,KAAK,IAAI;QAChE,CAAC,CAAC,CAAC;QACH,CAAC,CAAC,aAAa,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;AACvD,CAAC;AAED,SAAgB,SAAS,CAAC,CAAU;IAClC,OAAO,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAA;AACpC,CAAC;AAFD,8BAEC;AAED,SAAgB,aAAa,CAAC,CAAU;IACtC,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;SACrB,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC;SAC7B,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;AAClC,CAAC;AAJD,sCAIC;AAED,SAAgB,WAAW,CAAC,GAA2B;IACrD,OAAO,OAAO,GAAG,IAAI,QAAQ,IAAI,kBAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA,IAAI,GAAG,GAAG,CAAA;AAC5F,CAAC;AAFD,kCAEC;AAED,8CAA8C;AAC9C,SAAgB,gBAAgB,CAAC,GAA2B;IAC1D,IAAILine truncated
@@ -0,0 +1,78 @@
/**
* @fileoverview enforce default parameters to be last
* @author Chiawen Chen
*/
"use strict";
/**
* Checks if node is required: i.e. does not have a default value or ? optional indicator.
* @param {ASTNode} node the node to be evaluated
* @returns {boolean} true if the node is required, false if not.
*/
function isRequiredParameter(node) {
return !(
node.type === "AssignmentPattern" ||
node.type === "RestElement" ||
node.optional
);
}
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
dialects: ["javascript", "typescript"],
language: "javascript",
type: "suggestion",
docs: {
description: "Enforce default parameters to be last",
recommended: false,
frozen: true,
url: "https://eslint.org/docs/latest/rules/default-param-last",
},
schema: [],
messages: {
shouldBeLast: "Default parameters should be last.",
},
},
create(context) {
/**
* Handler for function contexts.
* @param {ASTNode} node function node
* @returns {void}
*/
function handleFunction(node) {
let hasSeenRequiredParameter = false;
for (let i = node.params.length - 1; i >= 0; i -= 1) {
const current = node.params[i];
const param =
current.type === "TSParameterProperty"
? current.parameter
: current;
if (isRequiredParameter(param)) {
hasSeenRequiredParameter = true;
continue;
}
if (hasSeenRequiredParameter) {
context.report({
node: current,
messageId: "shouldBeLast",
});
}
}
}
return {
FunctionDeclaration: handleFunction,
FunctionExpression: handleFunction,
ArrowFunctionExpression: handleFunction,
};
},
};
@@ -0,0 +1 @@
{"version":3,"file":"circle-off.js","sources":["../../../src/icons/circle-off.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name CircleOff\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJtMiAyIDIwIDIwIiAvPgogIDxwYXRoIGQ9Ik04LjM1IDIuNjlBMTAgMTAgMCAwIDEgMjEuMyAxNS42NSIgLz4KICA8cGF0aCBkPSJNMTkuMDggMTkuMDhBMTAgMTAgMCAxIDEgNC45MiA0LjkyIiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/circle-off\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst CircleOff = createLucideIcon('CircleOff', [\n ['path', { d: 'm2 2 20 20', key: '1ooewy' }],\n ['path', { d: 'M8.35 2.69A10 10 0 0 1 21.3 15.65', key: '1pfsoa' }],\n ['path', { d: 'M19.08 19.08A10 10 0 1 1 4.92 4.92', key: '1ablyi' }],\n]);\n\nexport default CircleOff;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAY,iBAAiB,WAAa,CAAA,CAAA,CAAA;AAAA,CAAA,CAC9C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAc,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC3C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAqC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAClE,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAsC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AACrE,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,4 @@
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"regExpExecOverStringMatch", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
name: string;
};
export default _default;
@@ -0,0 +1,9 @@
import { SignatureAlgorithm } from "./jwa.js";
//#region src/utils/jwt/jws.d.ts
export interface HonoJsonWebKey extends JsonWebKey {
kid?: string;
}
export type SignatureKey = string | HonoJsonWebKey | CryptoKey;
export declare function signing(privateKey: SignatureKey, alg: SignatureAlgorithm, data: BufferSource): Promise<ArrayBuffer>;
export declare function verifying(publicKey: SignatureKey, alg: SignatureAlgorithm, signature: BufferSource, data: BufferSource): Promise<boolean>;
//#endregion
@@ -0,0 +1,24 @@
/**
* dd-draggable.ts 12.6.0
* Copyright (c) 2021-2025 Alain Dumesny - see GridStack root license
*/
import { DDBaseImplement, HTMLElementExtendOpt } from './dd-base-impl';
import { GridItemHTMLElement, DDDragOpt } from './types';
type DDDragEvent = 'drag' | 'dragstart' | 'dragstop';
export declare class DDDraggable extends DDBaseImplement implements HTMLElementExtendOpt<DDDragOpt> {
el: GridItemHTMLElement;
option: DDDragOpt;
helper: HTMLElement;
protected _autoScrollContainer?: HTMLElement;
protected _autoScrollMaxSpeed?: number;
constructor(el: GridItemHTMLElement, option?: DDDragOpt);
/** return all handles omitting other nested `.grid-stack-item` children (in case node.subGrid isn't set for some reason) */
protected getAllHandles(): HTMLElement[];
on(event: DDDragEvent, callback: (event: DragEvent) => void): void;
off(event: DDDragEvent): void;
enable(): void;
disable(forDestroy?: boolean): void;
destroy(): void;
updateOption(opts: DDDragOpt): DDDraggable;
}
export {};
@@ -0,0 +1,563 @@
# noble-hashes
Audited & minimal JS implementation of hash functions, MACs and KDFs.
- 🔒 [**Audited**](#security) by an independent security firm
- 🔻 Tree-shakeable: unused code is excluded from your builds
- 🏎 Fast: hand-optimized for caveats of JS engines
- 🔍 Reliable: chained / sliding window / DoS / ACVP tests and fuzzing
- 🔁 No unrolled loops: makes it easier to verify and reduces source code size up to 5x
- 🦘 Includes SHA, RIPEMD, BLAKE, HMAC, HKDF, PBKDF, Scrypt, Argon2
- 🥈 Optional, friendly wrapper over native WebCrypto
- 🪶 22KB (gzipped) for everything, 2.4KB for single-hash build
Use [awasm-noble](https://github.com/paulmillr/awasm-noble) if you need an even faster (WASM) alternative.
Check out [Upgrading](#upgrading) for information about upgrading from previous versions.
Take a glance at [GitHub Discussions](https://github.com/paulmillr/noble-hashes/discussions) for questions and support.
The library's initial development was funded by [Ethereum Foundation](https://ethereum.org/).
### This library belongs to _noble_ cryptography
> **noble cryptography** — high-security, easily auditable set of contained cryptographic libraries and tools.
- Zero or minimal dependencies
- Highly readable TypeScript / JS code
- PGP-signed releases and transparent NPM builds
- All libraries:
[ciphers](https://github.com/paulmillr/noble-ciphers),
[curves](https://github.com/paulmillr/noble-curves),
[hashes](https://github.com/paulmillr/noble-hashes),
[post-quantum](https://github.com/paulmillr/noble-post-quantum),
5kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) /
[ed25519](https://github.com/paulmillr/noble-ed25519)
- [Check out the homepage](https://paulmillr.com/noble/)
for reading resources, documentation, and apps built with noble
## Usage
> `npm install @noble/hashes`
> `deno add jsr:@noble/hashes`
We support all major platforms and runtimes.
For React Native, you may need a [polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values).
A standalone file [noble-hashes.js](https://github.com/paulmillr/noble-hashes/releases) is also available.
```js
// import * from '@noble/hashes'; // Error: use sub-imports, to ensure small app size
import { sha256 as noble_sha256 } from '@noble/hashes/sha2.js';
const hash = noble_sha256(Uint8Array.from([0xca, 0xfe, 0x01, 0x23]));
// Available modules
import { sha256, sha384, sha512, sha224, sha512_224, sha512_256 } from '@noble/hashes/sha2.js';
import {
sha3_256, sha3_512,
keccak_256, keccak_512,
shake128, shake256,
} from '@noble/hashes/sha3.js';
import {
cshake256, turboshake256, kmac256, tuplehash256,
kt128, kt256, keccakprg,
} from '@noble/hashes/sha3-addons.js';
import { blake3 } from '@noble/hashes/blake3.js';
import { blake2b, blake2s } from '@noble/hashes/blake2.js';
import { blake256, blake512 } from '@noble/hashes/blake1.js';
import { sha1, md5, ripemd160 } from '@noble/hashes/legacy.js';
import { hmac } from '@noble/hashes/hmac.js';
import { hkdf } from '@noble/hashes/hkdf.js';
import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';
import { scrypt, scryptAsync } from '@noble/hashes/scrypt.js';
import { argon2d, argon2i, argon2id } from '@noble/hashes/argon2.js';
import * as webcrypto from '@noble/hashes/webcrypto.js';
// const { sha256, sha384, sha512, hmac, hkdf, pbkdf2 } = webcrypto;
import * as utils from '@noble/hashes/utils.js';
const { bytesToHex, concatBytes, equalBytes, hexToBytes } = utils;
```
- [sha2: sha256, sha384, sha512](#sha2-sha256-sha384-sha512-and-others)
- [sha3: FIPS, SHAKE, Keccak](#sha3-fips-shake-keccak)
- [sha3-addons: cSHAKE, KMAC, KT128, TurboSHAKE](#sha3-addons-cshake-kmac-kt128-turboshake)
- [blake1, blake2, blake3](#blake1-blake2-blake3)
- [legacy: sha1, md5, ripemd160](#legacy-sha1-md5-ripemd160)
- MACs: [hmac](#hmac) | [kmac](#sha3-addons-cshake-kmac-kt128-turboshake) | [blake3 key mode](#blake1-blake2-blake3)
- KDFs: [hkdf](#hkdf) | [pbkdf2](#pbkdf2) | [scrypt](#scrypt) | [argon2](#argon2)
- [webcrypto: friendly wrapper](#webcrypto-friendly-wrapper)
- [utils](#utils)
- [Security](#security) | [Speed](#speed) | [Contributing & testing](#contributing--testing) | [License](#license)
### Implementations
Hash functions:
- `sha256()`: receive & return `Uint8Array`
- `sha256.create().update(a).update(b).digest()`: support partial updates
- `blake3.create({ context: 'e', dkLen: 32 })`: can have options
- support little-endian architecture; also experimentally big-endian
- can hash up to 4GB per chunk, with any amount of chunks
#### sha2: sha256, sha384, sha512 and others
```typescript
import { sha224, sha256, sha384, sha512, sha512_224, sha512_256 } from '@noble/hashes/sha2.js';
const res = sha256(Uint8Array.from([0xbc])); // basic
for (let hash of [sha256, sha384, sha512, sha224, sha512_224, sha512_256]) {
const arr = Uint8Array.from([0x10, 0x20, 0x30]);
const a = hash(arr);
const b = hash.create().update(arr).digest();
}
```
Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
[the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).
#### sha3: FIPS, SHAKE, Keccak
```typescript
import {
sha3_224, sha3_256, sha3_384, sha3_512,
keccak_224, keccak_256, keccak_384, keccak_512,
shake128, shake256,
} from '@noble/hashes/sha3.js';
for (let hash of [
sha3_224, sha3_256, sha3_384, sha3_512,
keccak_224, keccak_256, keccak_384, keccak_512,
]) {
const arr = Uint8Array.from([0x10, 0x20, 0x30]);
const a = hash(arr);
const b = hash.create().update(arr).digest();
}
const shka = shake128(Uint8Array.from([0x10]), { dkLen: 512 });
const shkb = shake256(Uint8Array.from([0x30]), { dkLen: 512 });
```
Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
[Website](https://keccak.team/keccak.html).
Check out [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub)
#### sha3-addons: cSHAKE, KMAC, K12, TurboSHAKE
```typescript
import {
cshake128, cshake256, kt128, kt256,
keccakprg, kmac128, kmac256,
parallelhash256, tuplehash256,
turboshake128, turboshake256,
} from '@noble/hashes/sha3-addons.js';
const data = Uint8Array.from([0x10, 0x20, 0x30]);
const personalization = new TextEncoder().encode('def');
const ec1 = cshake128(data, { personalization });
const ec2 = cshake256(data, { personalization });
const et1 = turboshake128(data);
const et2 = turboshake256(data, { D: 0x05 });
// tuplehash(['ab', 'c']) !== tuplehash(['a', 'bc']) !== tuplehash([data])
const et3 = tuplehash256([new TextEncoder().encode('ab'), new TextEncoder().encode('c')]);
// Not parallel in JS (similar to blake3 / kt128), added for compat
const ep1 = parallelhash256(data, { blockLen: 8 });
const kk = Uint8Array.from([0xca]);
const ek10 = kmac128(kk, data);
const ek11 = kmac256(kk, data);
const ek12 = kt128(data); // kangarootwelve 128-bit
const ek13 = kt256(data); // kangarootwelve 256-bit
// pseudo-random generator, first argument is capacity. XKCP recommends 254 bits capacity for 128-bit security strength.
// * with a capacity of 254 bits.
const p = keccakprg(254);
p.addEntropy(Uint8Array.from([1, 2, 3]));
const rand1b = p.randomBytes(32);
```
- cSHAKE, KMAC, TupleHash, ParallelHash + XOF are available, matching
[NIST SP 800-185](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf)
- Reduced-round Keccak KT128 (KangarooTwelve 🦘, K12) and TurboSHAKE are available, matching
[RFC 9861](https://datatracker.ietf.org/doc/rfc9861/).
- [KeccakPRG](https://keccak.team/files/CSF-0.1.pdf): pseudo-random generator based on Keccak
#### blake1, blake2, blake3
```typescript
import { blake224, blake256, blake384, blake512 } from '@noble/hashes/blake1.js';
import { blake2b, blake2s } from '@noble/hashes/blake2.js';
import { blake3 } from '@noble/hashes/blake3.js';
for (let hash of [blake224, blake256, blake384, blake512, blake2b, blake2s, blake3]) {
const arr = Uint8Array.from([0x10, 0x20, 0x30]);
const a = hash(arr);
const b = hash.create().update(arr).digest();
}
// blake2 advanced usage
const ab = Uint8Array.from([0x01]);
const txt = new TextEncoder();
blake2s(ab);
blake2s(ab, { key: new Uint8Array(32) });
blake2s(ab, { personalization: txt.encode('pers1234') });
blake2s(ab, { salt: txt.encode('salt1234') });
blake2b(ab);
blake2b(ab, { key: new Uint8Array(64) });
blake2b(ab, { personalization: txt.encode('pers1234pers1234') });
blake2b(ab, { salt: txt.encode('salt1234salt1234') });
// blake3 advanced usage
blake3(ab);
blake3(ab, { dkLen: 256 });
blake3(ab, { key: new Uint8Array(32) });
blake3(ab, { context: txt.encode('application-name') });
```
- Blake1 is legacy hash, one of SHA3 proposals. It is rarely used anywhere. See [pdf](https://www.aumasson.jp/blake/blake.pdf).
- Blake2 is popular fast hash. blake2b focuses on 64-bit platforms while blake2s is for 8-bit to 32-bit ones. See [RFC 7693](https://datatracker.ietf.org/doc/html/rfc7693), [Website](https://www.blake2.net)
- Blake3 is faster, reduced-round blake2. See [Website & specs](https://blake3.io)
#### legacy: sha1, md5, ripemd160
SHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.
Don't use them in a new protocol. What "weak" means:
- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.
- No practical pre-image attacks (only theoretical, 2^123.4)
- HMAC seems kinda ok: https://datatracker.ietf.org/doc/html/rfc6151
```typescript
import { md5, ripemd160, sha1 } from '@noble/hashes/legacy.js';
for (let hash of [md5, ripemd160, sha1]) {
const arr = Uint8Array.from([0x10, 0x20, 0x30]);
const a = hash(arr);
const b = hash.create().update(arr).digest();
}
```
#### hmac
```typescript
import { hmac } from '@noble/hashes/hmac.js';
import { sha256 } from '@noble/hashes/sha2.js';
const key = new Uint8Array(32).fill(1);
const msg = new Uint8Array(32).fill(2);
const mac1 = hmac(sha256, key, msg);
const mac2 = hmac.create(sha256, key).update(msg).digest();
```
Conforms to [RFC 2104](https://datatracker.ietf.org/doc/html/rfc2104).
#### hkdf
```typescript
import { hkdf } from '@noble/hashes/hkdf.js';
import { randomBytes } from '@noble/hashes/utils.js';
import { sha256 } from '@noble/hashes/sha2.js';
const inputKey = randomBytes(32);
const salt = randomBytes(32);
const info = new TextEncoder().encode('application-key');
const hk1 = hkdf(sha256, inputKey, salt, info, 32);
// == same as
import { extract, expand } from '@noble/hashes/hkdf.js';
const prk = extract(sha256, inputKey, salt);
const hk2 = expand(sha256, prk, info, 32);
```
Conforms to [RFC 5869](https://datatracker.ietf.org/doc/html/rfc5869).
#### pbkdf2
```typescript
import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';
import { sha256 } from '@noble/hashes/sha2.js';
const pbkey1 = pbkdf2(sha256, 'password', 'salt', { c: 524288, dkLen: 32 });
const pbkey2 = await pbkdf2Async(sha256, 'password', 'salt', { c: 524288, dkLen: 32 });
const pbkey3 = await pbkdf2Async(sha256, Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), {
c: 524288,
dkLen: 32,
});
```
Conforms to [RFC 2898](https://datatracker.ietf.org/doc/html/rfc2898).
#### scrypt
```typescript
import { scrypt, scryptAsync } from '@noble/hashes/scrypt.js';
const scr1 = scrypt('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 });
const scr2 = await scryptAsync('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 });
const scr3 = await scryptAsync(Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), {
N: 2 ** 17,
r: 8,
p: 1,
dkLen: 32,
onProgress(percentage) {
console.log('progress', percentage);
},
maxmem: 2 ** 32 + 128 * 8 * 1, // N * r * p * 128 + (128*r*p)
});
```
Conforms to [RFC 7914](https://datatracker.ietf.org/doc/html/rfc7914),
[Website](https://www.tarsnap.com/scrypt.html)
- `N, r, p` are work factors. It is common to only adjust N, while keeping `r: 8, p: 1`.
See [the blog post](https://blog.filippo.io/the-scrypt-parameters/).
JS doesn't support parallelization, making increasing `p` meaningless.
- `dkLen` is the length of output bytes e.g. `32` or `64`
- `onProgress` can be used with async version of the function to report progress to a user.
- `maxmem` prevents DoS and is limited to `1GB + 1KB` (`2**30 + 2**10`), but can be adjusted using formula: `N * r * p * 128 + (128 * r * p)`
Time it takes to derive Scrypt key under different values of N (2\*\*N) on Apple M4 (mobile phones can be 1x-4x slower):
| N pow | Time | RAM |
| ----- | ---- | ----- |
| 16 | 0.1s | 64MB |
| 17 | 0.2s | 128MB |
| 18 | 0.4s | 256MB |
| 19 | 0.8s | 512MB |
| 20 | 1.5s | 1GB |
| 21 | 3.1s | 2GB |
| 22 | 6.2s | 4GB |
| 23 | 13s | 8GB |
| 24 | 27s | 16GB |
> [!NOTE]
> We support N larger than `2**20` where available, however,
> not all JS engines support >= 2GB ArrayBuffer-s.
> When using such N, you'll need to manually adjust `maxmem`, using formula above.
> Other JS implementations don't support large N-s.
#### argon2
```ts
import { argon2d, argon2i, argon2id } from '@noble/hashes/argon2.js';
const arg1 = argon2id('password', 'saltsalt', { t: 2, m: 65536, p: 1, maxmem: 2 ** 32 - 1 });
```
Argon2 [RFC 9106](https://datatracker.ietf.org/doc/html/rfc9106) implementation.
> [!WARNING]
> Argon2 can't be fast in JS, because there is no fast Uint64Array.
> It is suggested to use [Scrypt](#scrypt) instead.
> Being 5x slower than native code means brute-forcing attackers have bigger advantage.
#### webcrypto: friendly wrapper
```js
import { sha256, sha384, sha512, hmac, hkdf, pbkdf2 } from '@noble/hashes/webcrypto.js';
import { randomBytes } from '@noble/hashes/utils.js';
const whash = await sha256(Uint8Array.from([0xca, 0xfe, 0x01, 0x23]));
const key = new Uint8Array(32).fill(1);
const msg = new Uint8Array(32).fill(2);
const wmac = await hmac(sha256, key, msg);
const inputKey = randomBytes(32);
const salt = randomBytes(32);
const info = new TextEncoder().encode('application-key');
const hk1 = await hkdf(sha256, inputKey, salt, info, 32);
const pbkey1 = await pbkdf2(sha256, 'password', 'salt', { c: 524288, dkLen: 32 });
```
Sometimes people want to use built-in `crypto.subtle` instead of pure JS implementation.
However, it has terrible API.
We simplify access to built-ins with API which mirrors noble-hashes.
The overhead is minimal - just 30+ lines of code, which verify input correctness.
> [!NOTE]
> Webcrypto methods are always async.
#### utils
```typescript
import { bytesToHex as toHex, randomBytes } from '@noble/hashes/utils.js';
console.log(toHex(randomBytes(32)));
```
- `bytesToHex` will convert `Uint8Array` to a hex string
- `randomBytes(bytes)` will produce cryptographically secure random `Uint8Array` of length `bytes`
## Security
The library has been audited:
- at version 2.2.0, in Apr 2026, by ourselves (self-audited)
- Scope: everything
- [Changes since audit](https://github.com/paulmillr/noble-hashes/compare/2.2.0..main)
- at version 1.0.0, in Jan 2022, independently, by [Cure53](https://cure53.de)
- PDFs: [website](https://cure53.de/pentest-report_hashing-libs.pdf), [in-repo](./audit/2022-01-05-cure53-audit-nbl2.pdf)
- Scope: everything, besides `blake3`, `sha3-addons`, `sha1` and `argon2`, which have not been audited
- The audit has been funded by [Ethereum Foundation](https://ethereum.org/en/) with help of [Nomic Labs](https://nomiclabs.io)
It is tested against property-based, cross-library and Wycheproof vectors,
and is being fuzzed in [the separate repo](https://github.com/paulmillr/fuzzing).
If you see anything unusual: investigate and report.
### Constant-timeness
We're targetting algorithmic constant time. _JIT-compiler_ and _Garbage Collector_ make "constant time"
extremely hard to achieve [timing attack](https://en.wikipedia.org/wiki/Timing_attack) resistance
in a scripting language. Which means _any other JS library can't have
constant-timeness_. Even statically typed Rust, a language without GC,
[makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security)
for some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones.
Use low-level libraries & languages.
### Memory dumping
The library shares state buffers between hash
function calls. The buffers are zeroed-out after each call. However, if an attacker
can read application memory, you are doomed in any case:
- At some point, input will be a string and strings are immutable in JS:
there is no way to overwrite them with zeros. For example: deriving
key from `scrypt(password, salt)` where password and salt are strings
- Input from a file will stay in file buffers
- Input / output will be re-used multiple times in application which means it could stay in memory
- `await anything()` will always write all internal variables (including numbers)
to memory. With async functions / Promises there are no guarantees when the code
chunk would be executed. Which means attacker can have plenty of time to read data from memory
- There is no way to guarantee anything about zeroing sensitive data without
complex tests-suite which will dump process memory and verify that there is
no sensitive data left. For JS it means testing all browsers (incl. mobile),
which is complex. And of course it will be useless without using the same
test-suite in the actual application that consumes the library
### Supply chain security
- **Commits** are signed with PGP keys to prevent forgery. Be sure to verify the commit signatures
- **Releases** are made transparently through token-less GitHub CI and Trusted Publishing. Be sure to verify the [provenance logs](https://docs.npmjs.com/generating-provenance-statements) for authenticity.
- **Rare releasing** is practiced to minimize the need for re-audits by end-users.
- **Dependencies** are minimized and strictly pinned to reduce supply-chain risk.
- We use as few dependencies as possible.
- Version ranges are locked, and changes are checked with npm-diff.
- **Dev dependencies** are excluded from end-user installs; they’re only used for development and build steps.
For this package, there are 0 dependencies; and a few dev dependencies:
- jsbt contains helpers for building, benchmarking & testing secure JS apps. It is developed by the same author
- prettier, fast-check and typescript are used for code quality / test generation / ts compilation
### Randomness
We rely on the built-in
[`crypto.getRandomValues`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues),
which is considered a cryptographically secure PRNG.
Browsers have had weaknesses in the past - and could again - but implementing a userspace CSPRNG is even worse, as there’s no reliable userspace source of high-quality entropy.
### Quantum computers
Cryptographically relevant quantum computer, if built, will allow to
utilize Grover's algorithm to break hashes in 2^n/2 operations, instead of 2^n.
This means SHA256 should be replaced with SHA512, SHA3-256 with SHA3-512, SHAKE128 with SHAKE256 etc.
Australian ASD prohibits SHA256 and similar hashes [after 2030](https://www.cyber.gov.au/resources-business-and-government/essential-cyber-security/ism/cyber-security-guidelines/guidelines-cryptography).
## Upgrading
Supported node.js versions:
- v2: v20.19+ (ESM-only)
- v1: v14.21+ (ESM & CJS)
v2.0 changelog:
- The package is now ESM-only. ESM can finally be loaded from common.js on node v20.19+
- `.js` extension must be used for all modules
- Old: `@noble/hashes/sha3`
- New: `@noble/hashes/sha3.js`
- This simplifies working in browsers natively without transpilers
- Only allow Uint8Array as hash inputs, prohibit `string`
- Strict validation checks improve security
- To replicate previous behavior, use `utils.utf8ToBytes`
- Rename / remove some modules for consistency. Previously, sha384 resided in sha512, which was weird
- `sha256`, `sha512` => `sha2.js` (consistent with `sha3.js`)
- `blake2b`, `blake2s` => `blake2.js` (consistent with `blake3.js`, `blake1.js`)
- `ripemd160`, `sha1`, `md5` => `legacy.js` (all low-security hashes are there)
- `_assert` => `utils.js`
- `crypto` internal module got removed: use built-in WebCrypto instead
- Improve typescript types & option autocomplete
- Bump compilation target from es2020 to es2022
## Contributing & testing
`test/misc` directory contains implementations of loop unrolling and md5.
- `npm install && npm run build && npm test` will build the code and run tests.
- `npm run lint` / `npm run format` will run linter / fix linter issues.
- `npm run bench` will run benchmarks
- `npm run build:release` will build single file
- There is **additional** 20-min DoS test `npm run test:dos` and 2-hour multicore test `npm run test:slow`.
See [our approach to testing](./test/README.md)
Some hashes are outside of scope of the library:
- [Pedersen in micro-zk-proofs](https://github.com/paulmillr/micro-zk-proofs/blob/1ed5ce1253583b2e540eef7f3477fb52bf5344ff/src/pedersen.ts)
- [Poseidon in noble-curves](https://github.com/paulmillr/noble-curves/blob/3d124dd3ecec8b6634cc0b2ba1c183aded5304f9/src/abstract/poseidon.ts)
- [Poly1305 & GHash in noble-ciphers](https://github.com/paulmillr/noble-ciphers)
See [paulmillr.com/noble](https://paulmillr.com/noble/) for useful resources, articles, documentation and demos related to the library.
## Speed
```sh
npm run bench
```
Benchmarks measured on Apple M4. If you need truly exemplar performance, switch to [awasm-noble](https://github.com/paulmillr/awasm-noble).
```
# 32B
sha256 x 2,016,129 ops/sec @ 496ns/op
sha512 x 740,740 ops/sec @ 1μs/op
sha3_256 x 287,686 ops/sec @ 3μs/op
sha3_512 x 288,267 ops/sec @ 3μs/op
k12 x 476,190 ops/sec @ 2μs/op
blake2b x 410,340 ops/sec @ 2μs/op
blake2s x 942,507 ops/sec @ 1μs/op
blake3 x 1,006,036 ops/sec @ 994ns/op
ripemd160 x 1,410,437 ops/sec @ 709ns/op
md5 x 1,663,893 ops/sec @ 601ns/op
sha1 x 1,589,825 ops/sec @ 629ns/op
# 1MB
sha256 x 331 ops/sec @ 3ms/op
sha512 x 128 ops/sec @ 7ms/op
sha3_256 x 39 ops/sec @ 25ms/op
sha3_512 x 21 ops/sec @ 46ms/op
kt128 x 91 ops/sec @ 10ms/op
kt256 x 75 ops/sec @ 13ms/op
turboshake128 x 93 ops/sec @ 10ms/op
blake256 x 57 ops/sec @ 17ms/op
blake2b x 61 ops/sec @ 16ms/op
blake2s x 78 ops/sec @ 12ms/op
blake3 x 95 ops/sec @ 10ms/op
ripemd160 x 177 ops/sec @ 5ms/op
md5 x 250 ops/sec @ 3ms/op
sha1 x 416 ops/sec @ 2ms/op
# MAC
hmac(sha256) x 599,880 ops/sec @ 1μs/op
hmac(sha512) x 197,122 ops/sec @ 5μs/op
kmac256 x 87,981 ops/sec @ 11μs/op
blake3(key) x 796,812 ops/sec @ 1μs/op
# KDF
hkdf(sha256) x 259,942 ops/sec @ 3μs/op
blake3(context) x 424,808 ops/sec @ 2μs/op
pbkdf2(sha256, c: 2 ** 18) x 5 ops/sec @ 197ms/op
pbkdf2(sha512, c: 2 ** 18) x 1 ops/sec @ 630ms/op
scrypt(n: 2 ** 18, r: 8, p: 1) x 2 ops/sec @ 400ms/op
argon2id(t: 1, m: 256MB) 2881ms
```
The library could be 3x faster by utilizing loop unrolling. It isn't used because
unrolling a) would increase bundle size b) make lib un-readable c) current perf is "fast enough"
for most use-cases.
## License
The MIT License (MIT)
Copyright (c) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com)
See LICENSE file.
@@ -0,0 +1,16 @@
// packages/react/use-previous/src/use-previous.tsx
import * as React from "react";
function usePrevious(value) {
const ref = React.useRef({ value, previous: value });
return React.useMemo(() => {
if (ref.current.value !== value) {
ref.current.previous = ref.current.value;
ref.current.value = value;
}
return ref.current.previous;
}, [value]);
}
export {
usePrevious
};
//# sourceMappingURL=index.mjs.map
@@ -0,0 +1,3 @@
// Make exports work in Node < 12
// eslint-disable-next-line no-undef, unicorn/prefer-module
module.exports = require("./dist/commonjs/decode.js");
@@ -0,0 +1,13 @@
"use strict";
const basicLogPrefix = require("./basicLogPrefix.js");
const formatMessage = require("./formatMessage.js");
class BasicLayout {
/**
* Format the log event (格式化日志事件)
* @param event Log event (日志事件)
*/
format(event) {
return `${basicLogPrefix(event)} ${formatMessage(event.message)}`;
}
}
module.exports = BasicLayout;
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"_E"},B:{"2":"_I","33":"_K"},C:{"2":"_S"},D:{"33":"_Q"},E:{"2":"_e","33":"_DB"},F:{"2":"_T","33":"_a"},G:{"33":"_M"},H:{"2":"1D"},I:{"33":"_P"},J:{"33":"_B"},K:{"2":"_D","33":"H"},L:{"33":"I"},M:{"2":"YC"},N:{"2":"_A"},O:{"33":"bC"},P:{"33":"_F"},Q:{"33":"JE"},R:{"33":"KE"},S:{"2":"_C"}},B:7,C:"CSS Reflections",D:true};
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2012 Paul Miller (https://paulmillr.com), Elan Shanker
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,27 @@
interface Result {
name: "AssertionError" | "AssertionResult";
ok: boolean;
toJSON(...args: unknown[]): Record<string, unknown>;
}
declare class AssertionError<T> extends Error implements Result {
[key: string]: unknown
name: "AssertionError";
ok: false;
message: string;
// deno-lint-ignore ban-types
constructor(message: string, props?: T, ssf?: Function);
stack: string;
toJSON(stack?: boolean): Record<string, unknown>;
}
declare class AssertionResult<T> implements Result {
[key: string]: unknown
name: "AssertionResult";
ok: true;
message: string;
constructor(props?: T);
toJSON(): Record<string, unknown>;
}
export { AssertionError, AssertionResult, Result };
@@ -0,0 +1,839 @@
# Dispatcher
<!--introduced_in=v4.0.0-->
<!--type=module-->
<!-- source_link=lib/dispatcher/dispatcher.js -->
> Stability: 2 - Stable
`Dispatcher` is the core abstraction used to dispatch HTTP requests in undici.
It extends [`EventEmitter`][] and defines the low-level [`dispatch()`][] contract
along with the higher-level [`request()`][], [`stream()`][], [`pipeline()`][],
[`connect()`][], and [`upgrade()`][] methods that every concrete dispatcher
provides.
`Dispatcher` itself is abstract: its [`dispatch()`][], [`close()`][], and
[`destroy()`][] methods throw `Error: not implemented`. Concrete dispatchers such
as [`Client`][], [`Pool`][], [`BalancedPool`][], and [`Agent`][] implement the
contract and are what application code instantiates. Requests are not guaranteed
to be dispatched in the order in which they are invoked.
```mjs
import { Dispatcher, Agent } from 'undici'
const dispatcher = new Agent()
console.log(dispatcher instanceof Dispatcher) // true
```
## Class: `Dispatcher`
<!-- YAML
added: v4.0.0
-->
* Extends: {EventEmitter}
Base dispatcher class. Concrete dispatchers extend it and implement the
[`dispatch()`][] method on which the other request helpers are built.
### `dispatcher.close([callback])`
<!-- YAML
added: v4.0.0
-->
* `callback` {Function} (optional) Invoked once the dispatcher is closed.
* `error` {Error|null}
* Returns: {Promise} A `Promise` is returned only when `callback` is omitted. It
resolves with `void` once the dispatcher is closed.
Closes the dispatcher and gracefully waits for enqueued requests to complete
before resolving or invoking `callback`.
```mjs
import { createServer } from 'node:http'
import { Client } from 'undici'
import { once } from 'node:events'
const server = createServer((request, response) => {
response.end('undici')
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
try {
const { body } = await client.request({ path: '/', method: 'GET' })
body.setEncoding('utf8')
body.on('data', console.log)
} catch (error) {}
await client.close()
console.log('Client closed')
server.close()
```
### `dispatcher.connect(options[, callback])`
<!-- YAML
added: v4.0.0
-->
* `options` {Object}
* `origin` {string|URL} The origin to connect to.
* `path` {string} The request path.
* `headers` {UndiciHeaders} Request headers. **Default:** `null`.
* `signal` {AbortSignal|EventEmitter|null} A signal used to abort the request.
**Default:** `null`.
* `opaque` {any} An opaque value passed through to the returned `ConnectData`.
* `responseHeaders` {string|null} Set to `'raw'` to return the response headers
as a raw array instead of an object. **Default:** `null`.
* `callback` {Function} (optional) Invoked when the connection is established.
* `error` {Error|null}
* `data` {Object}
* `statusCode` {number}
* `headers` {Object} The response headers.
* `socket` {Duplex} The established socket.
* `opaque` {any} The `opaque` value passed in `options`.
* Returns: {Promise} A `Promise` is returned only when `callback` is omitted. It
resolves with the `data` object described above.
Starts two-way communications with the requested resource using the
[HTTP `CONNECT`][] method.
```mjs
import { createServer } from 'node:http'
import { Client } from 'undici'
import { once } from 'node:events'
const server = createServer((request, response) => {
throw new Error('should never get here')
}).listen()
server.on('connect', (req, socket, head) => {
socket.write('HTTP/1.1 200 Connection established\r\n\r\n')
let data = head.toString()
socket.on('data', (buf) => {
data += buf.toString()
})
socket.on('end', () => {
socket.end(data)
})
})
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
try {
const { socket } = await client.connect({ path: '/' })
const wanted = 'Body'
let data = ''
socket.on('data', d => { data += d })
socket.on('end', () => {
console.log(`Data received: ${data.toString()} | Data wanted: ${wanted}`)
client.close()
server.close()
})
socket.write(wanted)
socket.end()
} catch (error) {}
```
### `dispatcher.destroy([error[, callback]])`
<!-- YAML
added: v4.0.0
-->
* `error` {Error|null} (optional) The error with which pending requests are
rejected. **Default:** `null`.
* `callback` {Function} (optional) Invoked once the socket is closed.
* Returns: {Promise} A `Promise` is returned only when `callback` is omitted. It
resolves with `void` once the dispatcher is destroyed.
Destroys the dispatcher abruptly with the given `error`. All pending and running
requests are asynchronously aborted and rejected. Because the operation is
dispatched asynchronously, dispatched requests may still make some progress
before being aborted.
Both arguments are optional, so the method can be called in four ways:
```mjs
dispatcher.destroy() // -> Promise
dispatcher.destroy(new Error()) // -> Promise
dispatcher.destroy(() => {}) // -> void
dispatcher.destroy(new Error(), () => {}) // -> void
```
```mjs
import { createServer } from 'node:http'
import { Client } from 'undici'
import { once } from 'node:events'
const server = createServer((request, response) => {
response.end()
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
try {
const request = client.request({ path: '/', method: 'GET' })
client.destroy()
.then(() => {
console.log('Client destroyed')
server.close()
})
await request
} catch (error) {
console.error(error)
}
```
### `dispatcher.dispatch(options, handler)`
<!-- YAML
added: v4.0.0
-->
* `options` {Object}
* `origin` {string|URL} (optional) The origin to dispatch the request to.
* `path` {string} The request path.
* `method` {string} The HTTP method, e.g. `'GET'` or `'POST'`.
* `body` {string|Buffer|Uint8Array|Readable|FormData|null} The request body.
Undici's network clients require a `FormData` body created by the same
undici package instance. A body from another source, including Node.js's
built-in `FormData`, is rejected with an `InvalidArgumentError`.
**Default:** `null`.
* `headers` {UndiciHeaders} Request headers. **Default:** `null`.
* `query` {Object} Query string parameters embedded into the request URL. Both
keys and values are encoded with `encodeURIComponent`. **Default:** `null`.
* `idempotent` {boolean} Whether the request can be safely retried. If `false`,
the request is not sent until all preceding requests in the pipeline have
completed. **Default:** `true` when `method` is `'HEAD'` or `'GET'`.
* `blocking` {boolean} Whether the response is expected to block the pipeline.
When `true`, further pipelining on the same connection is avoided until
headers have been received. **Default:** `method !== 'HEAD'`.
* `typeOfService` {number|null} The IP Type of Service (ToS) value for the
request socket. Must be an integer between `0` and `255`. **Default:** `0`.
* `upgrade` {boolean|string|null} Upgrades the request, e.g. to `'Websocket'`.
**Default:** `null`, or the request method when it is `'CONNECT'`.
* `headersTimeout` {number|null} The time, in milliseconds, the parser waits to
receive the complete HTTP headers. Defaults to 300 seconds.
* `bodyTimeout` {number|null} The time, in milliseconds, after which the request
times out while receiving body data. Monitors the time between body chunks.
Use `0` to disable it entirely. Defaults to 300 seconds.
HTTP/1.1 headers/body parser timeouts are not guaranteed to fire with exact
millisecond precision: delays up to 1000ms use native timers, while larger
delays use undici's lower-overhead fast timers with a target resolution
around 500ms.
* `reset` {boolean} Whether the request should establish a keep-alive
connection. **Default:** `false`.
* `expectContinue` {boolean} For HTTP/2, appends the `expect: 100-continue`
header and halts the request body until a `100 Continue` is received from the
remote server. **Default:** `false`.
* `handler` {Object} A set of callbacks invoked over the request lifecycle.
* `onRequestStart` {Function} Invoked before the request is dispatched on the
socket. May be invoked multiple times when the request is retried.
* `controller` {DispatchController}
* `context` {any}
* `onRequestUpgrade` {Function} (optional) Invoked when the request is upgraded.
Required when `options.upgrade` is set or `options.method` is `'CONNECT'`.
* `controller` {DispatchController}
* `statusCode` {number}
* `headers` {Object}
* `socket` {Duplex}
* `onResponseStart` {Function} (optional) Invoked when the status code and
headers have been received. May be invoked multiple times for 1xx
informational responses. Not used for `upgrade` requests.
* `controller` {DispatchController}
* `statusCode` {number}
* `headers` {Object}
* `statusMessage` {string} (optional)
* `onResponseData` {Function} (optional) Invoked when response payload data is
received. Not used for `upgrade` requests.
* `controller` {DispatchController}
* `chunk` {Buffer}
* `onResponseEnd` {Function} (optional) Invoked when the response payload and
trailers have been received and the request has completed. Not used for
`upgrade` requests.
* `controller` {DispatchController}
* `trailers` {Object}
* `onResponseError` {Function} (optional) Invoked when an error occurs. Must not
throw.
* `controller` {DispatchController}
* `error` {Error}
* `onResponseStarted` {Function} (optional) Invoked when the response is
received, before headers have been read.
* `onBodySent` {Function} (optional) Invoked when a chunk of the request body is
sent. May be invoked multiple times for chunked requests.
* `chunk` {Buffer}
* `onRequestSent` {Function} (optional) Invoked after the request body is fully
sent.
* Returns: {boolean} `false` when the dispatcher is busy and further `dispatch()`
calls will make no progress until the [`'drain'`][] event is emitted.
This is the low-level API on which all the higher-level methods are built. This
API is expected to evolve through semver-major versions and is less stable than
the higher-level methods. It is primarily intended for library developers who
implement higher-level APIs on top of it.
The `controller` passed to each handler is a `DispatchController` with the
following shape:
* `aborted` {boolean} Whether the request has been aborted.
* `paused` {boolean} Whether the request is paused.
* `reason` {Error|null} The reason the request was aborted, if any.
* `rawHeaders` {Buffer[]|string[]|Object|null} The raw response headers,
preserving duplicates and casing.
* `rawTrailers` {Buffer[]|string[]|Object|null} The raw response trailers.
* `abort(reason)` Aborts the request with the given `reason`.
* `pause()` Pauses the response stream.
* `resume()` Resumes the response stream.
Call `controller.pause()` and `controller.resume()` to apply backpressure rather
than returning `false` from a handler.
```mjs
import { createServer } from 'node:http'
import { Client } from 'undici'
import { once } from 'node:events'
const server = createServer((request, response) => {
response.end('Hello, World!')
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
const data = []
client.dispatch({
path: '/',
method: 'GET',
headers: { 'x-foo': 'bar' }
}, {
onRequestStart: () => {
console.log('Connected!')
},
onResponseError: (_controller, error) => {
console.error(error)
},
onResponseStart: (_controller, statusCode, headers) => {
console.log(`statusCode: ${statusCode} | headers: ${JSON.stringify(headers)}`)
},
onResponseData: (_controller, chunk) => {
data.push(chunk)
},
onResponseEnd: (_controller, trailers) => {
console.log(`trailers: ${JSON.stringify(trailers)}`)
console.log(`Data: ${Buffer.concat(data).toString('utf8')}`)
client.close()
server.close()
}
})
```
### `dispatcher.pipeline(options, handler)`
<!-- YAML
added: v4.0.0
-->
* `options` {Object} Accepts every field of [`dispatcher.request()`][]'s
`options`, plus:
* `objectMode` {boolean} Set to `true` when `handler` returns an object stream.
**Default:** `false`.
* `handler` {Function} Returns a `Readable` from which the result is read.
* `data` {Object}
* `statusCode` {number}
* `headers` {Object} The response headers.
* `opaque` {any} The `opaque` value passed in `options`.
* `body` {Readable} The response body.
* `context` {Object}
* Returns: {Readable}
* Returns: {Duplex} A duplex stream that writes to the request and reads from the
response.
For easy use with [`stream.pipeline()`][]. The `handler` should return a
`Readable` from which the result is read. Usually it returns the `body` directly,
unless a transformation is needed based on, for example, `headers` or
`statusCode`. The `handler` should validate the response and save any required
state; if there is an error, it should be thrown.
```mjs
import { Readable, Writable, PassThrough, pipeline } from 'node:stream'
import { createServer } from 'node:http'
import { Client } from 'undici'
import { once } from 'node:events'
const server = createServer((request, response) => {
request.pipe(response)
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
let res = ''
pipeline(
new Readable({
read () {
this.push(Buffer.from('undici'))
this.push(null)
}
}),
client.pipeline({ path: '/', method: 'GET' }, ({ statusCode, headers, body }) => {
console.log(`response received ${statusCode}`)
console.log('headers', headers)
return pipeline(body, new PassThrough(), () => {})
}),
new Writable({
write (chunk, _, callback) {
res += chunk.toString()
callback()
},
final (callback) {
console.log(`Response pipelined to writable: ${res}`)
callback()
}
}),
error => {
if (error) {
console.error(error)
}
client.close()
server.close()
}
)
```
### `dispatcher.request(options[, callback])`
<!-- YAML
added: v4.0.0
-->
* `options` {Object} Accepts every field of [`dispatcher.dispatch()`][]'s
`options`, plus:
* `opaque` {any} A value passed through to the returned response data.
**Default:** `null`.
* `signal` {AbortSignal|EventEmitter|null} A signal used to abort the request.
**Default:** `null`.
* `onInfo` {Function|null} Invoked for each informational (1xx) response
received. **Default:** `null`.
* `info` {Object}
* `statusCode` {number}
* `headers` {Object}
* `responseHeaders` {string|null} Set to `'raw'` to return the response headers
as a raw array. **Default:** `null`.
* `highWaterMark` {number} The high water mark of the response body stream.
**Default:** `65536` (64 KiB).
* `callback` {Function} (optional) Invoked when the response is received.
* `error` {Error|null}
* `data` {Object}
* `statusCode` {number}
* `statusText` {string} The status message, e.g. `'OK'` or `'Not Found'`.
* `headers` {Object} The response headers. All keys are lower-cased.
* `body` {Readable} The response body, which also implements the
[body mixin][] from the Fetch Standard.
* `trailers` {Object} Starts out empty and is mutated to contain the trailers
after `body` emits `'end'`.
* `opaque` {any} The `opaque` value passed in `options`.
* `context` {Object}
* Returns: {Promise} A `Promise` is returned only when `callback` is omitted. It
resolves with the `data` object described above.
Performs an HTTP request. `options.method` must not be `'CONNECT'`.
Non-idempotent requests are not pipelined, to avoid indirect failures. Idempotent
requests are automatically retried if they fail due to an indirect failure from
the request at the head of the pipeline; this does not apply to idempotent
requests with a stream request body. All response bodies must always be fully
consumed or destroyed.
The `body` exposes the following [body mixin][] methods and properties:
[`.arrayBuffer()`][], [`.blob()`][], [`.bytes()`][], [`.json()`][],
[`.text()`][], `body`, and `bodyUsed`. A body cannot be consumed twice; for
example, calling `text()` after `json()` throws a `TypeError`. The body also
provides `dump({ limit })`, which discards up to `limit` bytes (default
`131072`) without destroying the socket.
> [!WARNING]
> The `arrayBuffer()`, `blob()`, `bytes()`, `json()`, and `text()` methods buffer
> the entire body in memory before returning. Where applicable, they also decode
> or parse the payload and retain that representation in memory. Calling these
> methods therefore means trusting that the body is small enough to fit in the
> available memory. Do not use them for bodies received from untrusted or
> user-controlled sources. Instead, process `body` as a `Readable` stream and
> enforce an application-specific size limit.
The body is always a `Readable`, even when empty. Deserializing an empty body
with `json()` throws. To guard against this, verify the status code is not `204`
and the `content-type` header starts with `application/json` before calling
`json()`.
```mjs
import { createServer } from 'node:http'
import { Client } from 'undici'
import { once } from 'node:events'
const server = createServer((request, response) => {
response.end('Hello, World!')
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
try {
const { body, headers, statusCode, statusText, trailers } = await client.request({
path: '/',
method: 'GET'
})
console.log(`response received ${statusCode}`)
console.log('headers', headers)
body.setEncoding('utf8')
body.on('data', console.log)
body.on('error', console.error)
body.on('end', () => {
console.log('trailers', trailers)
})
client.close()
server.close()
} catch (error) {
console.error(error)
}
```
A request can be aborted with an `AbortSignal`, with any `EventEmitter` that
emits an `'abort'` event, or by destroying the response body:
```mjs
import { Client } from 'undici'
const client = new Client('http://localhost:3000')
const abortController = new AbortController()
try {
client.request({ path: '/', method: 'GET', signal: abortController.signal })
} catch (error) {
console.error(error) // RequestAbortedError
}
abortController.abort()
```
When the response body is conditionally read, always fully consume it otherwise:
```mjs
const { body, statusCode } = await client.request({ path: '/', method: 'GET' })
if (statusCode === 200) {
return await body.arrayBuffer()
}
await body.dump()
return null
```
### `dispatcher.stream(options, factory[, callback])`
<!-- YAML
added: v4.0.0
-->
* `options` {Object} Accepts the same fields as [`dispatcher.request()`][]'s
`options`.
* `factory` {Function} Returns the `Writable` to which the response is written.
* `data` {Object}
* `statusCode` {number}
* `headers` {Object} The response headers.
* `opaque` {any} The `opaque` value passed in `options`.
* `context` {Object}
* Returns: {Writable}
* `callback` {Function} (optional) Invoked when the request has completed.
* `error` {Error|null}
* `data` {Object}
* `opaque` {any} The `opaque` value passed in `options`.
* `trailers` {Object}
* Returns: {Promise} A `Promise` is returned only when `callback` is omitted. It
resolves with the `data` object described above.
A faster version of [`dispatcher.request()`][]. The `factory` returns a
[`Writable`][] to which the response is written, which avoids creating an
intermediate [`Readable`][] when the caller intends to pipe the response body
directly to a `Writable`.
Use `options.opaque` to avoid creating a closure for the `factory` method. This
pattern works well with Node.js web frameworks such as [Fastify][].
```mjs
import { createServer } from 'node:http'
import { Client } from 'undici'
import { once } from 'node:events'
import { Writable } from 'node:stream'
const server = createServer((request, response) => {
response.end('Hello, World!')
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
const bufs = []
try {
await client.stream({
path: '/',
method: 'GET',
opaque: { bufs }
}, ({ statusCode, headers, opaque: { bufs } }) => {
console.log(`response received ${statusCode}`)
console.log('headers', headers)
return new Writable({
write (chunk, encoding, callback) {
bufs.push(chunk)
callback()
}
})
})
console.log(Buffer.concat(bufs).toString('utf-8'))
client.close()
server.close()
} catch (error) {
console.error(error)
}
```
### `dispatcher.upgrade(options[, callback])`
<!-- YAML
added: v4.0.0
-->
* `options` {Object}
* `path` {string} The request path.
* `method` {string} The HTTP method. **Default:** `'GET'`.
* `headers` {UndiciHeaders} Request headers. **Default:** `null`.
* `protocol` {string} A comma-separated list of protocols, in descending
preference order. **Default:** `'Websocket'`.
* `signal` {AbortSignal|EventEmitter|null} A signal used to abort the request.
**Default:** `null`.
* `responseHeaders` {string|null} Set to `'raw'` to return the response headers
as a raw array. **Default:** `null`.
* `callback` {Function} (optional) Invoked when the upgrade completes.
* `error` {Error|null}
* `data` {Object}
* `headers` {Object} The response headers.
* `socket` {Duplex} The upgraded socket.
* `opaque` {any}
* Returns: {Promise} A `Promise` is returned only when `callback` is omitted. It
resolves with the `data` object described above.
Upgrades to a different protocol. See
[MDN: Protocol upgrade mechanism][] for more details.
```mjs
import { createServer } from 'node:http'
import { Client } from 'undici'
import { once } from 'node:events'
const server = createServer((request, response) => {
response.statusCode = 101
response.setHeader('connection', 'upgrade')
response.setHeader('upgrade', request.headers.upgrade)
response.end()
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
try {
const { headers, socket } = await client.upgrade({ path: '/' })
socket.on('end', () => {
console.log(`upgrade: ${headers.upgrade}`) // upgrade: Websocket
client.close()
server.close()
})
socket.end()
} catch (error) {
console.error(error)
client.close()
server.close()
}
```
### `dispatcher.compose(interceptors[, interceptor])`
<!-- YAML
added: v6.9.0
-->
* `interceptors` {Array|Function} An array of interceptor functions, or the first
of several interceptors passed as separate arguments.
* `...interceptor` {Function} Additional interceptors when passed as separate
arguments.
* Returns: {Dispatcher} A new dispatcher that applies the interceptors over the
current dispatcher's [`dispatch()`][] method.
Composes a new dispatcher from the current dispatcher and the given
interceptors. Each interceptor is a function that takes a `dispatch` method and
returns a `dispatch`-like function with the same signature
(`(options, handler)`).
The order of the interceptors matters: the last interceptor in the chain is the
first to be called. Forking the chain of interceptors can lead to unexpected
results.
```text
compose([interceptor1, interceptor2, interceptor3])
Request flow:
Request -> interceptor3 -> interceptor2 -> interceptor1 -> dispatcher.dispatch
(called first) (called second) (called last)
```
```mjs
import { Client, RedirectHandler } from 'undici'
const redirectInterceptor = dispatch => {
return (opts, handler) => {
const { maxRedirections } = opts
if (!maxRedirections) {
return dispatch(opts, handler)
}
const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler)
opts = { ...opts, maxRedirections: 0 } // Stop the sub-dispatcher from also redirecting.
return dispatch(opts, redirectHandler)
}
}
const client = new Client('http://localhost:3000').compose(redirectInterceptor)
await client.request({ path: '/', method: 'GET' })
```
Interceptors can be chained by calling `compose()` repeatedly:
```mjs
import { Client } from 'undici'
const client = new Client('http://localhost:3000')
.compose(redirectInterceptor)
.compose(retryInterceptor)
await client.request({ path: '/', method: 'GET' })
```
For the full list of built-in interceptors provided by undici, see [Interceptors](Interceptors.md).
For an example of a custom interceptor that wraps handler callbacks, see
[Custom interceptors](Interceptors.md#custom-interceptors).
### Event: `'connect'`
<!-- YAML
added: v4.0.0
-->
* `origin` {URL}
* `targets` {Array<Dispatcher>}
Emitted when the dispatcher has connected to the origin.
### Event: `'disconnect'`
<!-- YAML
added: v4.0.0
-->
* `origin` {URL}
* `targets` {Array<Dispatcher>}
* `error` {Error}
Emitted when the dispatcher has been disconnected from the origin.
For HTTP/2, this event is also emitted when the dispatcher receives a
[GOAWAY frame][], with an error whose message is `HTTP/2: "GOAWAY" frame received`
and whose code is `UND_ERR_INFO`. Because of the binary-framing nature of the
protocol, a request may hang if a frame is received between the `HEADER` and
`DATA` frames. It is recommended to handle this event and close the dispatcher to
create a new HTTP/2 session.
### Event: `'connectionError'`
<!-- YAML
added: v4.0.0
-->
* `origin` {URL}
* `targets` {Array<Dispatcher>}
* `error` {Error}
Emitted when the dispatcher fails to connect to the origin.
### Event: `'drain'`
<!-- YAML
added: v4.0.0
-->
* `origin` {URL}
Emitted when the dispatcher is no longer busy and further [`dispatch()`][] calls
can make progress.
## Pre-built interceptors
For the full reference of built-in interceptors (`dump`, `retry`, `redirect`,
`decompress`, `responseError`, `dns`, `cache`, `deduplicate`) and their options,
see [Interceptors](Interceptors.md).
[Fastify]: https://fastify.dev
[GOAWAY frame]: https://webconcepts.info/concepts/http2-frame-type/0x7
[HTTP `CONNECT`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT
[MDN: Protocol upgrade mechanism]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism
[`.arrayBuffer()`]: https://fetch.spec.whatwg.org/#dom-body-arraybuffer
[`.blob()`]: https://fetch.spec.whatwg.org/#dom-body-blob
[`.bytes()`]: https://fetch.spec.whatwg.org/#dom-body-bytes
[`.json()`]: https://fetch.spec.whatwg.org/#dom-body-json
[`.text()`]: https://fetch.spec.whatwg.org/#dom-body-text
[`'drain'`]: #event-drain
[`Agent`]: Agent.md#class-agent
[`BalancedPool`]: BalancedPool.md#class-balancedpool
[`Client`]: Client.md#class-client
[`EventEmitter`]: https://nodejs.org/api/events.html#class-eventemitter
[`Pool`]: Pool.md#class-pool
[`Readable`]: https://nodejs.org/api/stream.html#class-streamreadable
[`Writable`]: https://nodejs.org/api/stream.html#class-streamwritable
[`close()`]: #dispatcherclosecallback
[`connect()`]: #dispatcherconnectoptions-callback
[`destroy()`]: #dispatcherdestroyerror-callback
[`dispatch()`]: #dispatcherdispatchoptions-handler
[`dispatcher.compose()`]: #dispatchercomposeinterceptors-interceptor
[`dispatcher.dispatch()`]: #dispatcherdispatchoptions-handler
[`dispatcher.request()`]: #dispatcherrequestoptions-callback
[`pipeline()`]: #dispatcherpipelineoptions-handler
[`request()`]: #dispatcherrequestoptions-callback
[`stream()`]: #dispatcherstreamoptions-factory-callback
[`stream.pipeline()`]: https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options
[`upgrade()`]: #dispatcherupgradeoptions-callback
[body mixin]: https://fetch.spec.whatwg.org/#body-mixin
@@ -0,0 +1,41 @@
import { useState, useEffect } from 'react';
import { env } from './env';
const cache = new WeakMap();
const NO_OPTIONS = {};
export function useSidecar(importer, effect) {
const options = (effect && effect.options) || NO_OPTIONS;
if (env.isNode && !options.ssr) {
return [null, null];
}
// eslint-disable-next-line react-hooks/rules-of-hooks
return useRealSidecar(importer, effect);
}
function useRealSidecar(importer, effect) {
const options = (effect && effect.options) || NO_OPTIONS;
const couldUseCache = env.forceCache || (env.isNode && !!options.ssr) || !options.async;
const [Car, setCar] = useState(couldUseCache ? () => cache.get(importer) : undefined);
const [error, setError] = useState(null);
useEffect(() => {
if (!Car) {
importer().then((car) => {
const resolved = effect ? effect.read() : car.default || car;
if (!resolved) {
console.error('Sidecar error: with importer', importer);
let error;
if (effect) {
console.error('Sidecar error: with medium', effect);
error = new Error('Sidecar medium was not found');
}
else {
error = new Error('Sidecar was not found in exports');
}
setError(() => error);
throw error;
}
cache.set(importer, resolved);
setCar(() => resolved);
}, (e) => setError(() => e));
}
}, []);
return [Car, error];
}
@@ -0,0 +1,36 @@
import { f as createRule, w as canTokensBeAdjacent } from "../utils.js";
var no_floating_decimal_default = createRule({
name: "no-floating-decimal",
meta: {
type: "layout",
docs: { description: "Disallow leading or trailing decimal points in numeric literals" },
fixable: "code",
schema: [],
messages: {
leading: "A leading decimal point can be confused with a dot.",
trailing: "A trailing decimal point can be confused with a dot."
}
},
create(context) {
const sourceCode = context.sourceCode;
return { Literal(node) {
if (typeof node.value === "number") {
if (node.raw.startsWith(".")) context.report({
node,
messageId: "leading",
fix(fixer) {
const tokenBefore = sourceCode.getTokenBefore(node);
const needsSpaceBefore = tokenBefore && tokenBefore.range[1] === node.range[0] && !canTokensBeAdjacent(tokenBefore, `0${node.raw}`);
return fixer.insertTextBefore(node, needsSpaceBefore ? " 0" : "0");
}
});
if (node.raw.indexOf(".") === node.raw.length - 1) context.report({
node,
messageId: "trailing",
fix: (fixer) => fixer.insertTextAfter(node, "0")
});
}
} };
}
});
export { no_floating_decimal_default as t };
@@ -0,0 +1,68 @@
/*
Copyright (c) 2015-present, Facebook, Inc.
This source code is licensed under the MIT license found in the
LICENSE file at
https://github.com/react/create-react-app/blob/main/LICENSE
*/
/* global Application */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function run(argv) {
const urlToOpen = argv[0]
// Allow requested program to be optional, default to Google Chrome
const programName = argv[1] ?? 'Google Chrome'
const app = Application(programName)
if (app.windows.length === 0) {
app.Window().make()
}
// 1: Looking for tab running debugger then,
// Reload debugging tab if found, then return
const found = lookupTabWithUrl(urlToOpen, app)
if (found) {
found.targetWindow.activeTabIndex = found.targetTabIndex
found.targetTab.reload()
found.targetWindow.index = 1
app.activate()
return
}
// 2: Looking for Empty tab
// In case debugging tab was not found
// We try to find an empty tab instead
const emptyTabFound = lookupTabWithUrl('chrome://newtab/', app)
if (emptyTabFound) {
emptyTabFound.targetWindow.activeTabIndex = emptyTabFound.targetTabIndex
emptyTabFound.targetTab.url = urlToOpen
app.activate()
return
}
// 3: Create new tab
// both debugging and empty tab were not found make a new tab with url
const firstWindow = app.windows[0]
firstWindow.tabs.push(app.Tab({ url: urlToOpen }))
app.activate()
}
/**
* Lookup tab with given url
*/
function lookupTabWithUrl(lookupUrl, app) {
const windows = app.windows()
for (const window of windows) {
for (const [tabIndex, tab] of window.tabs().entries()) {
if (tab.url().includes(lookupUrl)) {
return {
targetTab: tab,
targetTabIndex: tabIndex + 1,
targetWindow: window,
}
}
}
}
}
@@ -0,0 +1,171 @@
import { f as createRule, g as import_ast_utils } from "../utils.js";
const OPTION_VALUE = { oneOf: [{
type: "string",
enum: ["always", "never"]
}, {
type: "object",
properties: {
multiline: { type: "boolean" },
minProperties: {
type: "integer",
minimum: 0
},
consistent: { type: "boolean" }
},
additionalProperties: false,
minProperties: 1
}] };
var object_curly_newline_default = createRule({
name: "object-curly-newline",
meta: {
type: "layout",
docs: { description: "Enforce consistent line breaks after opening and before closing braces" },
fixable: "whitespace",
schema: [{ oneOf: [OPTION_VALUE, {
type: "object",
properties: {
ObjectExpression: OPTION_VALUE,
ObjectPattern: OPTION_VALUE,
ImportDeclaration: OPTION_VALUE,
ExportDeclaration: OPTION_VALUE,
TSTypeLiteral: OPTION_VALUE,
TSInterfaceBody: OPTION_VALUE,
TSEnumBody: OPTION_VALUE
},
additionalProperties: false,
minProperties: 1
}] }],
defaultOptions: [],
messages: {
unexpectedLinebreakBeforeClosingBrace: "Unexpected line break before this closing brace.",
unexpectedLinebreakAfterOpeningBrace: "Unexpected line break after this opening brace.",
expectedLinebreakBeforeClosingBrace: "Expected a line break before this closing brace.",
expectedLinebreakAfterOpeningBrace: "Expected a line break after this opening brace."
}
},
create(context, [options]) {
const sourceCode = context.sourceCode;
function normalizeOptionValue(value) {
let multiline = false;
let minProperties = Number.POSITIVE_INFINITY;
let consistent = false;
if (value) if (value === "always") minProperties = 0;
else if (value === "never") minProperties = Number.POSITIVE_INFINITY;
else {
multiline = Boolean(value.multiline);
minProperties = value.minProperties || Number.POSITIVE_INFINITY;
consistent = Boolean(value.consistent);
}
else consistent = true;
return {
multiline,
minProperties,
consistent
};
}
function isObject(value) {
return typeof value === "object" && value !== null;
}
function isNodeSpecificOption(option) {
return isObject(option) || typeof option === "string";
}
function normalizeOptions(options) {
if (isObject(options) && Object.values(options).some(isNodeSpecificOption)) return {
ObjectExpression: normalizeOptionValue(options.ObjectExpression),
ObjectPattern: normalizeOptionValue(options.ObjectPattern),
ImportDeclaration: normalizeOptionValue(options.ImportDeclaration),
ExportNamedDeclaration: normalizeOptionValue(options.ExportDeclaration),
TSTypeLiteral: normalizeOptionValue(options.TSTypeLiteral),
TSInterfaceBody: normalizeOptionValue(options.TSInterfaceBody),
TSEnumBody: normalizeOptionValue(options.TSEnumBody)
};
const value = normalizeOptionValue(options);
return {
ObjectExpression: value,
ObjectPattern: value,
ImportDeclaration: value,
ExportNamedDeclaration: value,
TSTypeLiteral: value,
TSInterfaceBody: value,
TSEnumBody: value
};
}
const normalizedOptions = normalizeOptions(options);
function areLineBreaksRequired(node, options, first, last) {
let objectProperties;
if (node.type === "ObjectExpression" || node.type === "ObjectPattern") objectProperties = node.properties;
else if (node.type === "TSTypeLiteral") objectProperties = node.members;
else if (node.type === "TSInterfaceBody") objectProperties = node.body;
else if (node.type === "TSEnumBody") objectProperties = node.members;
else objectProperties = node.specifiers.filter((s) => s.type === "ImportSpecifier" || s.type === "ExportSpecifier");
return objectProperties.length >= options.minProperties || options.multiline && objectProperties.length > 0 && !(0, import_ast_utils.isTokenOnSameLine)(last, first);
}
function check(node) {
const options = normalizedOptions[node.type];
if (node.type === "ImportDeclaration" && !node.specifiers.some((specifier) => specifier.type === "ImportSpecifier") || node.type === "ExportNamedDeclaration" && !node.specifiers.some((specifier) => specifier.type === "ExportSpecifier")) return;
const openBrace = sourceCode.getFirstToken(node, (token) => token.value === "{");
let closeBrace;
if (node.type === "ObjectPattern" && node.typeAnnotation) closeBrace = sourceCode.getTokenBefore(node.typeAnnotation);
else closeBrace = sourceCode.getLastToken(node, (token) => token.value === "}");
let first = sourceCode.getTokenAfter(openBrace, { includeComments: true });
let last = sourceCode.getTokenBefore(closeBrace, { includeComments: true });
const needsLineBreaks = areLineBreaksRequired(node, options, first, last);
const hasCommentsFirstToken = (0, import_ast_utils.isCommentToken)(first);
const hasCommentsLastToken = (0, import_ast_utils.isCommentToken)(last);
first = sourceCode.getTokenAfter(openBrace);
last = sourceCode.getTokenBefore(closeBrace);
if (needsLineBreaks) {
if ((0, import_ast_utils.isTokenOnSameLine)(openBrace, first)) context.report({
messageId: "expectedLinebreakAfterOpeningBrace",
node,
loc: openBrace.loc,
fix(fixer) {
if (hasCommentsFirstToken) return null;
return fixer.insertTextAfter(openBrace, "\n");
}
});
if ((0, import_ast_utils.isTokenOnSameLine)(last, closeBrace)) context.report({
messageId: "expectedLinebreakBeforeClosingBrace",
node,
loc: closeBrace.loc,
fix(fixer) {
if (hasCommentsLastToken) return null;
return fixer.insertTextBefore(closeBrace, "\n");
}
});
} else {
const consistent = options.consistent;
const hasLineBreakBetweenOpenBraceAndFirst = !(0, import_ast_utils.isTokenOnSameLine)(openBrace, first);
const hasLineBreakBetweenCloseBraceAndLast = !(0, import_ast_utils.isTokenOnSameLine)(last, closeBrace);
if (!consistent && hasLineBreakBetweenOpenBraceAndFirst || consistent && hasLineBreakBetweenOpenBraceAndFirst && !hasLineBreakBetweenCloseBraceAndLast) context.report({
messageId: "unexpectedLinebreakAfterOpeningBrace",
node,
loc: openBrace.loc,
fix(fixer) {
if (hasCommentsFirstToken) return null;
return fixer.removeRange([openBrace.range[1], first.range[0]]);
}
});
if (!consistent && hasLineBreakBetweenCloseBraceAndLast || consistent && !hasLineBreakBetweenOpenBraceAndFirst && hasLineBreakBetweenCloseBraceAndLast) context.report({
messageId: "unexpectedLinebreakBeforeClosingBrace",
node,
loc: closeBrace.loc,
fix(fixer) {
if (hasCommentsLastToken) return null;
return fixer.removeRange([last.range[1], closeBrace.range[0]]);
}
});
}
}
return {
ObjectExpression: check,
ObjectPattern: check,
ImportDeclaration: check,
ExportNamedDeclaration: check,
TSTypeLiteral: check,
TSInterfaceBody: check,
TSEnumBody: check
};
}
});
export { object_curly_newline_default as t };
@@ -0,0 +1,412 @@
flf2a$ 4 3 8 0 3
Bracket Letters By Joan Stark
Website: http://www.geocities.com/SoHo/7373/
Figlet conversion by patorjk, April 17, 2008
$ $@
$ $@
$ $@
$ $@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
.--. @
/ {} \ @
/ /\ \@
`-' `-'@@
.----. @
| {} }@
| {} }@
`----' @@
.---. @
/ ___}@
\ }@
`---' @@
.----. @
| {} \@
| /@
`----' @@
.----.@
| {_ @
| {__ @
`----'@@
.----.@
| {_ @
| | @
`-' @@
.---. @
/ __}@
\ {_ }@
`---' @@
.-. .-.@
| {_} |@
| { } |@
`-' `-'@@
.-.@
| |@
| |@
`-'@@
.-.@
.-.| |@
| {} |@
`----'@@
.-. .-.@
| |/ / @
| |\ \ @
`-' `-'@@
.-. @
| | @
| `--.@
`----'@@
.-. .-.@
| `.' |@
| |\ /| |@
`-' ` `-'@@
.-. .-.@
| `| |@
| |\ |@
`-' `-'@@
.----. @
/ {} \@
\ /@
`----' @@
.----. @
| {} }@
| .--' @
`-' @@
.----. @
/ {} \@
\ /@
`-----`@@
.----. @
| {} }@
| .-. \@
`-' `-'@@
.----.@
{ {__ @
.-._} }@
`----' @@
.---. @
{_ _}@
| | @
`-' @@
.-. .-.@
| { } |@
| {_} |@
`-----'@@
.-. .-.@
| | | |@
\ \_/ /@
`---' @@
.-. . .-.@
| |/ \| |@
| .'. |@
`-' `-'@@
.-. .-.@
\ \/ / @
/ /\ \ @
`-' `-'@@
.-. .-.@
\ \/ / @
} { @
`--' @@
.---. @
{_ / @
/ }@
`---' @@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
.--. @
/ {} \ @
/ /\ \@
`-' `-'@@
.----. @
| {} }@
| {} }@
`----' @@
.---. @
/ ___}@
\ }@
`---' @@
.----. @
| {} \@
| /@
`----' @@
.----.@
| {_ @
| {__ @
`----'@@
.----.@
| {_ @
| | @
`-' @@
.---. @
/ __}@
\ {_ }@
`---' @@
.-. .-.@
| {_} |@
| { } |@
`-' `-'@@
.-.@
| |@
| |@
`-'@@
.-.@
.-.| |@
| {} |@
`----'@@
.-. .-.@
| |/ / @
| |\ \ @
`-' `-'@@
.-. @
| | @
| `--.@
`----'@@
.-. .-.@
| `.' |@
| |\ /| |@
`-' ` `-'@@
.-. .-.@
| `| |@
| |\ |@
`-' `-'@@
.----. @
/ {} \@
\ /@
`----' @@
.----. @
| {} }@
| .--' @
`-' @@
.----. @
/ {} \@
\ /@
`-----`@@
.----. @
| {} }@
| .-. \@
`-' `-'@@
.----.@
{ {__ @
.-._} }@
`----' @@
.---. @
{_ _}@
| | @
`-' @@
.-. .-.@
| { } |@
| {_} |@
`-----'@@
.-. .-.@
| | | |@
\ \_/ /@
`---' @@
.-. . .-.@
| |/ \| |@
| .'. |@
`-' `-'@@
.-. .-.@
\ \/ / @
/ /\ \ @
`-' `-'@@
.-. .-.@
\ \/ / @
} { @
`--' @@
.---. @
{_ / @
/ }@
`---' @@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@
@
@
@@
@@ -0,0 +1,13 @@
{
"files": ["src/hfs-types.ts"],
"compilerOptions": {
"declaration": true,
"emitDeclarationOnly": true,
"allowJs": true,
"checkJs": true,
"outDir": "dist",
"target": "ES2022",
"moduleResolution": "NodeNext",
"module": "NodeNext"
}
}
@@ -0,0 +1,532 @@
"use strict"
var Buffer = require("safer-buffer").Buffer
// Multibyte codec. In this scheme, a character is represented by 1 or more bytes.
// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences.
// To save memory and loading time, we read table files only when requested.
exports._dbcs = DBCSCodec
var UNASSIGNED = -1
var GB18030_CODE = -2
var SEQ_START = -10
var NODE_START = -1000
var UNASSIGNED_NODE = new Array(0x100)
var DEF_CHAR = -1
for (var i = 0; i < 0x100; i++) { UNASSIGNED_NODE[i] = UNASSIGNED }
// Class DBCSCodec reads and initializes mapping tables.
function DBCSCodec (codecOptions, iconv) {
this.encodingName = codecOptions.encodingName
if (!codecOptions) { throw new Error("DBCS codec is called without the data.") }
if (!codecOptions.table) { throw new Error("Encoding '" + this.encodingName + "' has no data.") }
// Load tables.
var mappingTable = codecOptions.table()
// Decode tables: MBCS -> Unicode.
// decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256.
// Trie root is decodeTables[0].
// Values: >= 0 -> unicode character code. can be > 0xFFFF
// == UNASSIGNED -> unknown/unassigned sequence.
// == GB18030_CODE -> this is the end of a GB18030 4-byte sequence.
// <= NODE_START -> index of the next node in our trie to process next byte.
// <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq.
this.decodeTables = []
this.decodeTables[0] = UNASSIGNED_NODE.slice(0) // Create root node.
// Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here.
this.decodeTableSeq = []
// Actual mapping tables consist of chunks. Use them to fill up decode tables.
for (var i = 0; i < mappingTable.length; i++) { this._addDecodeChunk(mappingTable[i]) }
// Load & create GB18030 tables when needed.
if (typeof codecOptions.gb18030 === "function") {
this.gb18030 = codecOptions.gb18030() // Load GB18030 ranges.
// Add GB18030 common decode nodes.
var commonThirdByteNodeIdx = this.decodeTables.length
this.decodeTables.push(UNASSIGNED_NODE.slice(0))
var commonFourthByteNodeIdx = this.decodeTables.length
this.decodeTables.push(UNASSIGNED_NODE.slice(0))
// Fill out the tree
var firstByteNode = this.decodeTables[0]
for (var i = 0x81; i <= 0xFE; i++) {
var secondByteNode = this.decodeTables[NODE_START - firstByteNode[i]]
for (var j = 0x30; j <= 0x39; j++) {
if (secondByteNode[j] === UNASSIGNED) {
secondByteNode[j] = NODE_START - commonThirdByteNodeIdx
} else if (secondByteNode[j] > NODE_START) {
throw new Error("gb18030 decode tables conflict at byte 2")
}
var thirdByteNode = this.decodeTables[NODE_START - secondByteNode[j]]
for (var k = 0x81; k <= 0xFE; k++) {
if (thirdByteNode[k] === UNASSIGNED) {
thirdByteNode[k] = NODE_START - commonFourthByteNodeIdx
} else if (thirdByteNode[k] === NODE_START - commonFourthByteNodeIdx) {
continue
} else if (thirdByteNode[k] > NODE_START) {
throw new Error("gb18030 decode tables conflict at byte 3")
}
var fourthByteNode = this.decodeTables[NODE_START - thirdByteNode[k]]
for (var l = 0x30; l <= 0x39; l++) {
if (fourthByteNode[l] === UNASSIGNED) { fourthByteNode[l] = GB18030_CODE }
}
}
}
}
}
this.defaultCharUnicode = iconv.defaultCharUnicode
// Encode tables: Unicode -> DBCS.
// `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance.
// Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null.
// Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.).
// == UNASSIGNED -> no conversion found. Output a default char.
// <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence.
this.encodeTable = []
// `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of
// objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key
// means end of sequence (needed when one sequence is a strict subsequence of another).
// Objects are kept separately from encodeTable to increase performance.
this.encodeTableSeq = []
// Some chars can be decoded, but need not be encoded.
var skipEncodeChars = {}
if (codecOptions.encodeSkipVals) {
for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) {
var val = codecOptions.encodeSkipVals[i]
if (typeof val === "number") { skipEncodeChars[val] = true } else {
for (var j = val.from; j <= val.to; j++) { skipEncodeChars[j] = true }
}
}
}
// Use decode trie to recursively fill out encode tables.
this._fillEncodeTable(0, 0, skipEncodeChars)
// Add more encoding pairs when needed.
if (codecOptions.encodeAdd) {
for (var uChar in codecOptions.encodeAdd) {
if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) { this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]) }
}
}
this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]
if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]["?"]
if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0)
}
DBCSCodec.prototype.encoder = DBCSEncoder
DBCSCodec.prototype.decoder = DBCSDecoder
// Decoder helpers
DBCSCodec.prototype._getDecodeTrieNode = function (addr) {
var bytes = []
for (; addr > 0; addr >>>= 8) { bytes.push(addr & 0xFF) }
if (bytes.length == 0) { bytes.push(0) }
var node = this.decodeTables[0]
for (var i = bytes.length - 1; i > 0; i--) { // Traverse nodes deeper into the trie.
var val = node[bytes[i]]
if (val == UNASSIGNED) { // Create new node.
node[bytes[i]] = NODE_START - this.decodeTables.length
this.decodeTables.push(node = UNASSIGNED_NODE.slice(0))
} else if (val <= NODE_START) { // Existing node.
node = this.decodeTables[NODE_START - val]
} else { throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)) }
}
return node
}
DBCSCodec.prototype._addDecodeChunk = function (chunk) {
// First element of chunk is the hex mbcs code where we start.
var curAddr = parseInt(chunk[0], 16)
// Choose the decoding node where we'll write our chars.
var writeTable = this._getDecodeTrieNode(curAddr)
curAddr = curAddr & 0xFF
// Write all other elements of the chunk to the table.
for (var k = 1; k < chunk.length; k++) {
var part = chunk[k]
if (typeof part === "string") { // String, write as-is.
for (var l = 0; l < part.length;) {
var code = part.charCodeAt(l++)
if (code >= 0xD800 && code < 0xDC00) { // Decode surrogate
var codeTrail = part.charCodeAt(l++)
if (codeTrail >= 0xDC00 && codeTrail < 0xE000) { writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00) } else { throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]) }
} else if (code > 0x0FF0 && code <= 0x0FFF) { // Character sequence (our own encoding used)
var len = 0xFFF - code + 2
var seq = []
for (var m = 0; m < len; m++) { seq.push(part.charCodeAt(l++)) } // Simple variation: don't support surrogates or subsequences in seq.
writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length
this.decodeTableSeq.push(seq)
} else { writeTable[curAddr++] = code } // Basic char
}
} else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character.
var charCode = writeTable[curAddr - 1] + 1
for (var l = 0; l < part; l++) { writeTable[curAddr++] = charCode++ }
} else { throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]) }
}
if (curAddr > 0xFF) { throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr) }
}
// Encoder helpers
DBCSCodec.prototype._getEncodeBucket = function (uCode) {
var high = uCode >> 8 // This could be > 0xFF because of astral characters.
if (this.encodeTable[high] === undefined) {
this.encodeTable[high] = UNASSIGNED_NODE.slice(0)
} // Create bucket on demand.
return this.encodeTable[high]
}
DBCSCodec.prototype._setEncodeChar = function (uCode, dbcsCode) {
var bucket = this._getEncodeBucket(uCode)
var low = uCode & 0xFF
if (bucket[low] <= SEQ_START) { this.encodeTableSeq[SEQ_START - bucket[low]][DEF_CHAR] = dbcsCode } // There's already a sequence, set a single-char subsequence of it.
else if (bucket[low] == UNASSIGNED) { bucket[low] = dbcsCode }
}
DBCSCodec.prototype._setEncodeSequence = function (seq, dbcsCode) {
// Get the root of character tree according to first character of the sequence.
var uCode = seq[0]
var bucket = this._getEncodeBucket(uCode)
var low = uCode & 0xFF
var node
if (bucket[low] <= SEQ_START) {
// There's already a sequence with - use it.
node = this.encodeTableSeq[SEQ_START - bucket[low]]
} else {
// There was no sequence object - allocate a new one.
node = {}
if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low] // If a char was set before - make it a single-char subsequence.
bucket[low] = SEQ_START - this.encodeTableSeq.length
this.encodeTableSeq.push(node)
}
// Traverse the character tree, allocating new nodes as needed.
for (var j = 1; j < seq.length - 1; j++) {
var oldVal = node[uCode]
if (typeof oldVal === "object") { node = oldVal } else {
node = node[uCode] = {}
if (oldVal !== undefined) { node[DEF_CHAR] = oldVal }
}
}
// Set the leaf to given dbcsCode.
uCode = seq[seq.length - 1]
node[uCode] = dbcsCode
}
DBCSCodec.prototype._fillEncodeTable = function (nodeIdx, prefix, skipEncodeChars) {
var node = this.decodeTables[nodeIdx]
var hasValues = false
var subNodeEmpty = {}
for (var i = 0; i < 0x100; i++) {
var uCode = node[i]
var mbCode = prefix + i
if (skipEncodeChars[mbCode]) { continue }
if (uCode >= 0) {
this._setEncodeChar(uCode, mbCode)
hasValues = true
} else if (uCode <= NODE_START) {
var subNodeIdx = NODE_START - uCode
if (!subNodeEmpty[subNodeIdx]) { // Skip empty subtrees (they are too large in gb18030).
var newPrefix = (mbCode << 8) >>> 0 // NOTE: '>>> 0' keeps 32-bit num positive.
if (this._fillEncodeTable(subNodeIdx, newPrefix, skipEncodeChars)) { hasValues = true } else { subNodeEmpty[subNodeIdx] = true }
}
} else if (uCode <= SEQ_START) {
this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode)
hasValues = true
}
}
return hasValues
}
// == Encoder ==================================================================
function DBCSEncoder (options, codec) {
// Encoder state
this.leadSurrogate = -1
this.seqObj = undefined
// Static data
this.encodeTable = codec.encodeTable
this.encodeTableSeq = codec.encodeTableSeq
this.defaultCharSingleByte = codec.defCharSB
this.gb18030 = codec.gb18030
}
DBCSEncoder.prototype.write = function (str) {
var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3))
var leadSurrogate = this.leadSurrogate
var seqObj = this.seqObj
var nextChar = -1
var i = 0; var j = 0
while (true) {
// 0. Get next character.
if (nextChar === -1) {
if (i == str.length) break
var uCode = str.charCodeAt(i++)
} else {
var uCode = nextChar
nextChar = -1
}
// 1. Handle surrogates.
if (uCode >= 0xD800 && uCode < 0xE000) { // Char is one of surrogates.
if (uCode < 0xDC00) { // We've got lead surrogate.
if (leadSurrogate === -1) {
leadSurrogate = uCode
continue
} else {
leadSurrogate = uCode
// Double lead surrogate found.
uCode = UNASSIGNED
}
} else { // We've got trail surrogate.
if (leadSurrogate !== -1) {
uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00)
leadSurrogate = -1
} else {
// Incomplete surrogate pair - only trail surrogate found.
uCode = UNASSIGNED
}
}
} else if (leadSurrogate !== -1) {
// Incomplete surrogate pair - only lead surrogate found.
nextChar = uCode; uCode = UNASSIGNED // Write an error, then current char.
leadSurrogate = -1
}
// 2. Convert uCode character.
var dbcsCode = UNASSIGNED
if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence
var resCode = seqObj[uCode]
if (typeof resCode === "object") { // Sequence continues.
seqObj = resCode
continue
} else if (typeof resCode === "number") { // Sequence finished. Write it.
dbcsCode = resCode
} else if (resCode == undefined) { // Current character is not part of the sequence.
// Try default character for this sequence
resCode = seqObj[DEF_CHAR]
if (resCode !== undefined) {
dbcsCode = resCode // Found. Write it.
nextChar = uCode // Current character will be written too in the next iteration.
} else {
// TODO: What if we have no default? (resCode == undefined)
// Then, we should write first char of the sequence as-is and try the rest recursively.
// Didn't do it for now because no encoding has this situation yet.
// Currently, just skip the sequence and write current char.
}
}
seqObj = undefined
} else if (uCode >= 0) { // Regular character
var subtable = this.encodeTable[uCode >> 8]
if (subtable !== undefined) { dbcsCode = subtable[uCode & 0xFF] }
if (dbcsCode <= SEQ_START) { // Sequence start
seqObj = this.encodeTableSeq[SEQ_START - dbcsCode]
continue
}
if (dbcsCode == UNASSIGNED && this.gb18030) {
// Use GB18030 algorithm to find character(s) to write.
var idx = findIdx(this.gb18030.uChars, uCode)
if (idx != -1) {
var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx])
newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600
newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260
newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10
newBuf[j++] = 0x30 + dbcsCode
continue
}
}
}
// 3. Write dbcsCode character.
if (dbcsCode === UNASSIGNED) { dbcsCode = this.defaultCharSingleByte }
if (dbcsCode < 0x100) {
newBuf[j++] = dbcsCode
} else if (dbcsCode < 0x10000) {
newBuf[j++] = dbcsCode >> 8 // high byte
newBuf[j++] = dbcsCode & 0xFF // low byte
} else if (dbcsCode < 0x1000000) {
newBuf[j++] = dbcsCode >> 16
newBuf[j++] = (dbcsCode >> 8) & 0xFF
newBuf[j++] = dbcsCode & 0xFF
} else {
newBuf[j++] = dbcsCode >>> 24
newBuf[j++] = (dbcsCode >>> 16) & 0xFF
newBuf[j++] = (dbcsCode >>> 8) & 0xFF
newBuf[j++] = dbcsCode & 0xFF
}
}
this.seqObj = seqObj
this.leadSurrogate = leadSurrogate
return newBuf.slice(0, j)
}
DBCSEncoder.prototype.end = function () {
if (this.leadSurrogate === -1 && this.seqObj === undefined) { return } // All clean. Most often case.
var newBuf = Buffer.alloc(10); var j = 0
if (this.seqObj) { // We're in the sequence.
var dbcsCode = this.seqObj[DEF_CHAR]
if (dbcsCode !== undefined) { // Write beginning of the sequence.
if (dbcsCode < 0x100) {
newBuf[j++] = dbcsCode
} else {
newBuf[j++] = dbcsCode >> 8 // high byte
newBuf[j++] = dbcsCode & 0xFF // low byte
}
} else {
// See todo above.
}
this.seqObj = undefined
}
if (this.leadSurrogate !== -1) {
// Incomplete surrogate pair - only lead surrogate found.
newBuf[j++] = this.defaultCharSingleByte
this.leadSurrogate = -1
}
return newBuf.slice(0, j)
}
// Export for testing
DBCSEncoder.prototype.findIdx = findIdx
// == Decoder ==================================================================
function DBCSDecoder (options, codec) {
// Decoder state
this.nodeIdx = 0
this.prevBytes = []
// Static data
this.decodeTables = codec.decodeTables
this.decodeTableSeq = codec.decodeTableSeq
this.defaultCharUnicode = codec.defaultCharUnicode
this.gb18030 = codec.gb18030
}
DBCSDecoder.prototype.write = function (buf) {
var newBuf = Buffer.alloc(buf.length * 2)
var nodeIdx = this.nodeIdx
var prevBytes = this.prevBytes; var prevOffset = this.prevBytes.length
var seqStart = -this.prevBytes.length // idx of the start of current parsed sequence.
var uCode
for (var i = 0, j = 0; i < buf.length; i++) {
var curByte = (i >= 0) ? buf[i] : prevBytes[i + prevOffset]
// Lookup in current trie node.
var uCode = this.decodeTables[nodeIdx][curByte]
if (uCode >= 0) {
// Normal character, just use it.
} else if (uCode === UNASSIGNED) { // Unknown char.
// TODO: Callback with seq.
uCode = this.defaultCharUnicode.charCodeAt(0)
i = seqStart // Skip one byte ('i' will be incremented by the for loop) and try to parse again.
} else if (uCode === GB18030_CODE) {
if (i >= 3) {
var ptr = (buf[i - 3] - 0x81) * 12600 + (buf[i - 2] - 0x30) * 1260 + (buf[i - 1] - 0x81) * 10 + (curByte - 0x30)
} else {
var ptr = (prevBytes[i - 3 + prevOffset] - 0x81) * 12600 +
(((i - 2 >= 0) ? buf[i - 2] : prevBytes[i - 2 + prevOffset]) - 0x30) * 1260 +
(((i - 1 >= 0) ? buf[i - 1] : prevBytes[i - 1 + prevOffset]) - 0x81) * 10 +
(curByte - 0x30)
}
var idx = findIdx(this.gb18030.gbChars, ptr)
uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]
} else if (uCode <= NODE_START) { // Go to next trie node.
nodeIdx = NODE_START - uCode
continue
} else if (uCode <= SEQ_START) { // Output a sequence of chars.
var seq = this.decodeTableSeq[SEQ_START - uCode]
for (var k = 0; k < seq.length - 1; k++) {
uCode = seq[k]
newBuf[j++] = uCode & 0xFF
newBuf[j++] = uCode >> 8
}
uCode = seq[seq.length - 1]
} else { throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte) }
// Write the character to buffer, handling higher planes using surrogate pair.
if (uCode >= 0x10000) {
uCode -= 0x10000
var uCodeLead = 0xD800 | (uCode >> 10)
newBuf[j++] = uCodeLead & 0xFF
newBuf[j++] = uCodeLead >> 8
uCode = 0xDC00 | (uCode & 0x3FF)
}
newBuf[j++] = uCode & 0xFF
newBuf[j++] = uCode >> 8
// Reset trie node.
nodeIdx = 0; seqStart = i + 1
}
this.nodeIdx = nodeIdx
this.prevBytes = (seqStart >= 0)
? Array.prototype.slice.call(buf, seqStart)
: prevBytes.slice(seqStart + prevOffset).concat(Array.prototype.slice.call(buf))
return newBuf.slice(0, j).toString("ucs2")
}
DBCSDecoder.prototype.end = function () {
var ret = ""
// Try to parse all remaining chars.
while (this.prevBytes.length > 0) {
// Skip 1 character in the buffer.
ret += this.defaultCharUnicode
var bytesArr = this.prevBytes.slice(1)
// Parse remaining as usual.
this.prevBytes = []
this.nodeIdx = 0
if (bytesArr.length > 0) { ret += this.write(bytesArr) }
}
this.prevBytes = []
this.nodeIdx = 0
return ret
}
// Binary search for GB18030. Returns largest i such that table[i] <= val.
function findIdx (table, val) {
if (table[0] > val) { return -1 }
var l = 0; var r = table.length
while (l < r - 1) { // always table[l] <= val < table[r]
var mid = l + ((r - l + 1) >> 1)
if (table[mid] <= val) { l = mid } else { r = mid }
}
return l
}
@@ -0,0 +1,33 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
const description = "a description";
test("passing `description` to schema should add a description", () => {
expect(z.string({ description }).description).toEqual(description);
expect(z.number({ description }).description).toEqual(description);
expect(z.boolean({ description }).description).toEqual(description);
});
test("`.describe` should add a description", () => {
expect(z.string().describe(description).description).toEqual(description);
expect(z.number().describe(description).description).toEqual(description);
expect(z.boolean().describe(description).description).toEqual(description);
});
test("description should carry over to chained schemas", () => {
const schema = z.string({ description });
expect(schema.description).toEqual(description);
expect(schema.optional().description).toEqual(description);
expect(schema.optional().nullable().default("default").description).toEqual(description);
});
test("description should not carry over to chained array schema", () => {
const schema = z.string().describe(description);
expect(schema.description).toEqual(description);
expect(schema.array().description).toEqual(undefined);
expect(z.array(schema).description).toEqual(undefined);
});
@@ -0,0 +1 @@
module.exports={C:{"34":0.00222,"112":0.02001,"113":0.00222,"114":0.00445,"115":0.01334,"119":0.00667,"120":0.15561,"121":0.23119,"124":0.02001,"127":0.01334,"130":0.01112,"132":0.00445,"140":0.01556,"143":0.00667,"146":0.00222,"147":0.00222,"149":0.00889,"150":0.01334,"152":0.00667,"153":0.02223,"154":0.0578,"155":0.14894,"156":0.20007,"157":0.00445,_:"2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 116 117 118 122 123 125 126 128 129 131 133 134 135 136 137 138 139 141 142 144 145 148 151 158 159 160 3.5 3.6"},D:{"53":0.00445,"56":0.01112,"63":0.00222,"64":0.00889,"66":0.00445,"68":0.00445,"69":0.00445,"70":0.00222,"72":0.00222,"74":0.00222,"75":0.00667,"78":0.00222,"79":0.00889,"86":0.00222,"87":0.01112,"92":0.00667,"93":0.00222,"97":0.00222,"98":0.01112,"101":0.00667,"103":0.08225,"104":0.01778,"105":0.03335,"106":0.01778,"107":0.01778,"108":0.01334,"109":0.37346,"110":0.01556,"111":0.03112,"112":0.01778,"114":0.00445,"116":0.0289,"117":0.01334,"118":0.41348,"119":0.26676,"120":0.30011,"121":0.00222,"122":0.02223,"123":0.03335,"124":0.01778,"126":0.01334,"127":0.00222,"128":0.00667,"130":0.01112,"131":0.05113,"133":0.07114,"134":0.09114,"135":0.04891,"136":0.06002,"137":0.05335,"138":0.09114,"139":0.06891,"140":0.05335,"141":0.05113,"142":0.16228,"143":0.02001,"144":0.02001,"145":0.04891,"146":0.08447,"147":0.0289,"148":0.04224,"149":0.06669,"150":0.27121,"151":1.17819,"152":4.66608,"153":3.46343,"154":0.77138,"155":0.00667,_:"4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 54 55 57 58 59 60 61 62 65 67 71 73 76 77 80 81 83 84 85 88 89 90 91 94 95 96 99 100 102 113 115 125 129 132 156 157"},F:{"46":0.00445,"66":0.00667,"89":0.00445,"94":0.00445,"95":0.01112,"100":0.00445,"101":0.00445,"105":0.00889,"107":0.00889,"114":0.00222,"116":0.00667,"120":0.00445,"121":0.00889,"122":0.00667,"127":0.00889,"133":0.01112,"134":0.06002,"135":0.42237,_:"9 11 12 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 47 48 49 50 51 52 53 54 55 56 57 58 60 62 63 64 65 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 90 91 92 93 96 97 98 99 102 103 104 106 108 109 110 111 112 113 115 117 118 119 123 124 125 126 131 132 9.5-9.6 10.0-10.1 10.5 10.6 11.1 11.5 11.6 12.1"},B:{"14":0.00222,"16":0.00445,"17":0.00222,"18":0.01112,"84":0.00222,"89":0.00445,"90":0.00222,"92":0.02445,"100":0.01334,"107":0.00445,"109":0.00222,"111":0.01112,"113":0.00222,"114":0.00445,"117":0.00222,"119":0.1156,"120":0.12449,"122":0.01112,"123":0.00667,"131":0.00222,"132":0.00222,"134":0.00222,"138":0.00222,"140":0.00445,"142":0.00222,"143":0.00222,"144":0.00222,"145":0.00667,"146":0.00667,"147":0.00445,"148":0.00889,"149":0.02001,"150":0.02445,"151":0.09781,"152":1.00924,"153":1.18708,"154":0.29788,_:"12 13 15 79 80 81 83 85 86 87 88 91 93 94 95 96 97 98 99 101 102 103 104 105 106 108 110 112 115 116 118 121 124 125 126 127 128 129 130 133 135 136 137 139 141"},E:{"11":0.00222,"14":0.00222,"27":0.02001,_:"4 5 6 7 8 9 10 12 13 15 3.1 3.2 5.1 6.1 7.1 9.1 10.1 11.1 12.1 14.1 15.2-15.3 15.4 16.1 16.2 16.4 17.0 17.2 17.3 17.4 18.0 18.1 27.1 TP","13.1":0.00222,"15.1":0.00222,"15.5":0.00222,"15.6":0.01556,"16.0":0.00222,"16.3":0.00222,"16.5":0.00445,"16.6":0.01334,"17.1":0.00445,"17.5":0.00222,"17.6":0.0578,"18.2":0.01112,"18.3":0.00222,"18.4":0.06002,"18.5-18.7":0.01112,"26.0":0.00222,"26.1":0.00222,"26.2":0.01112,"26.3":0.01334,"26.4":0.01778,"26.5":0.03335,"26.6":0.1356,"27.2":0.00445},G:{"8":0,"3.2":0,"4.0-4.1":0,"4.2-4.3":0.00061,"5.0-5.1":0.00061,"6.0-6.1":0,"7.0-7.1":0.00122,"8.1-8.4":0,"9.0-9.2":0,"9.3":0,"10.0-10.2":0,"10.3":0.0061,"11.0-11.2":0.00061,"11.3-11.4":0.00122,"12.0-12.1":0,"12.2-12.5":0.01587,"13.0-13.1":0,"13.2":0.00305,"13.3":0,"13.4-13.7":0.00061,"14.0-14.4":0.00244,"14.5-14.8":0.00366,"15.0-15.1":0.00366,"15.2-15.3":0.00244,"15.4":0.00305,"15.5":0.00366,"15.6-15.8":0.07936,"16.0":0.0061,"16.1":0.01099,"16.2":0.0061,"16.3":0.01343,"16.4":0.00305,"16.5":0.00488,"16.6-16.7":0.1105,"17.0":0.00427,"17.1":0.0061,"17.2":0.0061,"17.3":0.00916,"17.4":0.01282,"17.5":0.02503,"17.6-17.7":0.06471,"18.0":0.01343,"18.1":0.02686,"18.2":0.03663,"18.3":0.06349,"18.4":0.03968,"18.5-18.7":0.81989,"26.0":0.03968,"26.1":0.04029,"26.2":0.10501,"26.3":0.11355,"26.4":0.08303,"26.5":0.55616,"26.6":3.43159,"27.0":0.26312,"27.1":0,"27.2":0.00672},P:{"22":0.01868,"23":0.00934,"24":0.02802,"25":0.32692,"26":0.16813,"27":0.06538,"28":0.26154,"29":0.45769,"30":1.89615,_:"4 20 21 5.0-5.4 9.2 10.1 11.1-11.2 12.0 13.0 14.0 15.0 17.0 18.0 19.0","6.2-6.4":0.00934,"7.2-7.4":0.2522,"8.2":0.00934,"16.0":0.02802},I:{"0":0.02331,"3":0,"4":0,"2.1":0,"Line truncated
@@ -0,0 +1,423 @@
/**
* @license React
* react.react-server.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
"use strict";
var ReactSharedInternals = { H: null, A: null };
function formatProdErrorMessage(code) {
var url = "https://react.dev/errors/" + code;
if (1 < arguments.length) {
url += "?args[]=" + encodeURIComponent(arguments[1]);
for (var i = 2; i < arguments.length; i++)
url += "&args[]=" + encodeURIComponent(arguments[i]);
}
return (
"Minified React error #" +
code +
"; visit " +
url +
" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."
);
}
var isArrayImpl = Array.isArray;
function noop() {}
var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"),
REACT_PORTAL_TYPE = Symbol.for("react.portal"),
REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"),
REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"),
REACT_PROFILER_TYPE = Symbol.for("react.profiler"),
REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"),
REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"),
REACT_MEMO_TYPE = Symbol.for("react.memo"),
REACT_LAZY_TYPE = Symbol.for("react.lazy"),
MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
function getIteratorFn(maybeIterable) {
if (null === maybeIterable || "object" !== typeof maybeIterable) return null;
maybeIterable =
(MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) ||
maybeIterable["@@iterator"];
return "function" === typeof maybeIterable ? maybeIterable : null;
}
var hasOwnProperty = Object.prototype.hasOwnProperty,
assign = Object.assign;
function ReactElement(type, key, props) {
var refProp = props.ref;
return {
$$typeof: REACT_ELEMENT_TYPE,
type: type,
key: key,
ref: void 0 !== refProp ? refProp : null,
props: props
};
}
function cloneAndReplaceKey(oldElement, newKey) {
return ReactElement(oldElement.type, newKey, oldElement.props);
}
function isValidElement(object) {
return (
"object" === typeof object &&
null !== object &&
object.$$typeof === REACT_ELEMENT_TYPE
);
}
function escape(key) {
var escaperLookup = { "=": "=0", ":": "=2" };
return (
"$" +
key.replace(/[=:]/g, function (match) {
return escaperLookup[match];
})
);
}
var userProvidedKeyEscapeRegex = /\/+/g;
function getElementKey(element, index) {
return "object" === typeof element && null !== element && null != element.key
? escape("" + element.key)
: index.toString(36);
}
function resolveThenable(thenable) {
switch (thenable.status) {
case "fulfilled":
return thenable.value;
case "rejected":
throw thenable.reason;
default:
switch (
("string" === typeof thenable.status
? thenable.then(noop, noop)
: ((thenable.status = "pending"),
thenable.then(
function (fulfilledValue) {
"pending" === thenable.status &&
((thenable.status = "fulfilled"),
(thenable.value = fulfilledValue));
},
function (error) {
"pending" === thenable.status &&
((thenable.status = "rejected"), (thenable.reason = error));
}
)),
thenable.status)
) {
case "fulfilled":
return thenable.value;
case "rejected":
throw thenable.reason;
}
}
throw thenable;
}
function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
var type = typeof children;
if ("undefined" === type || "boolean" === type) children = null;
var invokeCallback = !1;
if (null === children) invokeCallback = !0;
else
switch (type) {
case "bigint":
case "string":
case "number":
invokeCallback = !0;
break;
case "object":
switch (children.$$typeof) {
case REACT_ELEMENT_TYPE:
case REACT_PORTAL_TYPE:
invokeCallback = !0;
break;
case REACT_LAZY_TYPE:
return (
(invokeCallback = children._init),
mapIntoArray(
invokeCallback(children._payload),
array,
escapedPrefix,
nameSoFar,
callback
)
);
}
}
if (invokeCallback)
return (
(callback = callback(children)),
(invokeCallback =
"" === nameSoFar ? "." + getElementKey(children, 0) : nameSoFar),
isArrayImpl(callback)
? ((escapedPrefix = ""),
null != invokeCallback &&
(escapedPrefix =
invokeCallback.replace(userProvidedKeyEscapeRegex, "$&/") + "/"),
mapIntoArray(callback, array, escapedPrefix, "", function (c) {
return c;
}))
: null != callback &&
(isValidElement(callback) &&
(callback = cloneAndReplaceKey(
callback,
escapedPrefix +
(null == callback.key ||
(children && children.key === callback.key)
? ""
: ("" + callback.key).replace(
userProvidedKeyEscapeRegex,
"$&/"
) + "/") +
invokeCallback
)),
array.push(callback)),
1
);
invokeCallback = 0;
var nextNamePrefix = "" === nameSoFar ? "." : nameSoFar + ":";
if (isArrayImpl(children))
for (var i = 0; i < children.length; i++)
(nameSoFar = children[i]),
(type = nextNamePrefix + getElementKey(nameSoFar, i)),
(invokeCallback += mapIntoArray(
nameSoFar,
array,
escapedPrefix,
type,
callback
));
else if (((i = getIteratorFn(children)), "function" === typeof i))
for (
children = i.call(children), i = 0;
!(nameSoFar = children.next()).done;
)
(nameSoFar = nameSoFar.value),
(type = nextNamePrefix + getElementKey(nameSoFar, i++)),
(invokeCallback += mapIntoArray(
nameSoFar,
array,
escapedPrefix,
type,
callback
));
else if ("object" === type) {
if ("function" === typeof children.then)
return mapIntoArray(
resolveThenable(children),
array,
escapedPrefix,
nameSoFar,
callback
);
array = String(children);
throw Error(
formatProdErrorMessage(
31,
"[object Object]" === array
? "object with keys {" + Object.keys(children).join(", ") + "}"
: array
)
);
}
return invokeCallback;
}
function mapChildren(children, func, context) {
if (null == children) return children;
var result = [],
count = 0;
mapIntoArray(children, result, "", "", function (child) {
return func.call(context, child, count++);
});
return result;
}
function lazyInitializer(payload) {
if (-1 === payload._status) {
var ctor = payload._result;
ctor = ctor();
ctor.then(
function (moduleObject) {
if (0 === payload._status || -1 === payload._status)
(payload._status = 1), (payload._result = moduleObject);
},
function (error) {
if (0 === payload._status || -1 === payload._status)
(payload._status = 2), (payload._result = error);
}
);
-1 === payload._status && ((payload._status = 0), (payload._result = ctor));
}
if (1 === payload._status) return payload._result.default;
throw payload._result;
}
function createCacheRoot() {
return new WeakMap();
}
function createCacheNode() {
return { s: 0, v: void 0, o: null, p: null };
}
exports.Children = {
map: mapChildren,
forEach: function (children, forEachFunc, forEachContext) {
mapChildren(
children,
function () {
forEachFunc.apply(this, arguments);
},
forEachContext
);
},
count: function (children) {
var n = 0;
mapChildren(children, function () {
n++;
});
return n;
},
toArray: function (children) {
return (
mapChildren(children, function (child) {
return child;
}) || []
);
},
only: function (children) {
if (!isValidElement(children)) throw Error(formatProdErrorMessage(143));
return children;
}
};
exports.Fragment = REACT_FRAGMENT_TYPE;
exports.Profiler = REACT_PROFILER_TYPE;
exports.StrictMode = REACT_STRICT_MODE_TYPE;
exports.Suspense = REACT_SUSPENSE_TYPE;
exports.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE =
ReactSharedInternals;
exports.cache = function (fn) {
return function () {
var dispatcher = ReactSharedInternals.A;
if (!dispatcher) return fn.apply(null, arguments);
var fnMap = dispatcher.getCacheForType(createCacheRoot);
dispatcher = fnMap.get(fn);
void 0 === dispatcher &&
((dispatcher = createCacheNode()), fnMap.set(fn, dispatcher));
fnMap = 0;
for (var l = arguments.length; fnMap < l; fnMap++) {
var arg = arguments[fnMap];
if (
"function" === typeof arg ||
("object" === typeof arg && null !== arg)
) {
var objectCache = dispatcher.o;
null === objectCache && (dispatcher.o = objectCache = new WeakMap());
dispatcher = objectCache.get(arg);
void 0 === dispatcher &&
((dispatcher = createCacheNode()), objectCache.set(arg, dispatcher));
} else
(objectCache = dispatcher.p),
null === objectCache && (dispatcher.p = objectCache = new Map()),
(dispatcher = objectCache.get(arg)),
void 0 === dispatcher &&
((dispatcher = createCacheNode()),
objectCache.set(arg, dispatcher));
}
if (1 === dispatcher.s) return dispatcher.v;
if (2 === dispatcher.s) throw dispatcher.v;
try {
var result = fn.apply(null, arguments);
fnMap = dispatcher;
fnMap.s = 1;
return (fnMap.v = result);
} catch (error) {
throw ((result = dispatcher), (result.s = 2), (result.v = error), error);
}
};
};
exports.cacheSignal = function () {
var dispatcher = ReactSharedInternals.A;
return dispatcher ? dispatcher.cacheSignal() : null;
};
exports.captureOwnerStack = function () {
return null;
};
exports.cloneElement = function (element, config, children) {
if (null === element || void 0 === element)
throw Error(formatProdErrorMessage(267, element));
var props = assign({}, element.props),
key = element.key;
if (null != config)
for (propName in (void 0 !== config.key && (key = "" + config.key), config))
!hasOwnProperty.call(config, propName) ||
"key" === propName ||
"__self" === propName ||
"__source" === propName ||
("ref" === propName && void 0 === config.ref) ||
(props[propName] = config[propName]);
var propName = arguments.length - 2;
if (1 === propName) props.children = children;
else if (1 < propName) {
for (var childArray = Array(propName), i = 0; i < propName; i++)
childArray[i] = arguments[i + 2];
props.children = childArray;
}
return ReactElement(element.type, key, props);
};
exports.createElement = function (type, config, children) {
var propName,
props = {},
key = null;
if (null != config)
for (propName in (void 0 !== config.key && (key = "" + config.key), config))
hasOwnProperty.call(config, propName) &&
"key" !== propName &&
"__self" !== propName &&
"__source" !== propName &&
(props[propName] = config[propName]);
var childrenLength = arguments.length - 2;
if (1 === childrenLength) props.children = children;
else if (1 < childrenLength) {
for (var childArray = Array(childrenLength), i = 0; i < childrenLength; i++)
childArray[i] = arguments[i + 2];
props.children = childArray;
}
if (type && type.defaultProps)
for (propName in ((childrenLength = type.defaultProps), childrenLength))
void 0 === props[propName] &&
(props[propName] = childrenLength[propName]);
return ReactElement(type, key, props);
};
exports.createRef = function () {
return { current: null };
};
exports.forwardRef = function (render) {
return { $$typeof: REACT_FORWARD_REF_TYPE, render: render };
};
exports.isValidElement = isValidElement;
exports.lazy = function (ctor) {
return {
$$typeof: REACT_LAZY_TYPE,
_payload: { _status: -1, _result: ctor },
_init: lazyInitializer
};
};
exports.memo = function (type, compare) {
return {
$$typeof: REACT_MEMO_TYPE,
type: type,
compare: void 0 === compare ? null : compare
};
};
exports.use = function (usable) {
return ReactSharedInternals.H.use(usable);
};
exports.useCallback = function (callback, deps) {
return ReactSharedInternals.H.useCallback(callback, deps);
};
exports.useDebugValue = function () {};
exports.useId = function () {
return ReactSharedInternals.H.useId();
};
exports.useMemo = function (create, deps) {
return ReactSharedInternals.H.useMemo(create, deps);
};
exports.version = "19.2.5";
@@ -0,0 +1,17 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const Touchpad = createLucideIcon("Touchpad", [
["rect", { width: "20", height: "16", x: "2", y: "4", rx: "2", key: "18n3k1" }],
["path", { d: "M2 14h20", key: "myj16y" }],
["path", { d: "M12 20v-6", key: "1rm09r" }]
]);
export { Touchpad as default };
//# sourceMappingURL=touchpad.js.map
@@ -0,0 +1,124 @@
import { motionValue } from './index.mjs';
import { JSAnimation } from '../animation/JSAnimation.mjs';
import { isMotionValue } from './utils/is-motion-value.mjs';
import { frame } from '../frameloop/frame.mjs';
/**
* Create a `MotionValue` that animates to its latest value using any transition type.
* Can either be a value or track another `MotionValue`.
*
* ```jsx
* const x = motionValue(0)
* const y = followValue(x, { type: "spring", stiffness: 300 })
* // or with tween
* const z = followValue(x, { type: "tween", duration: 0.5, ease: "easeOut" })
* ```
*
* @param source - Initial value or MotionValue to track
* @param options - Animation transition options
* @returns `MotionValue`
*
* @public
*/
function followValue(source, options) {
const initialValue = isMotionValue(source) ? source.get() : source;
const value = motionValue(initialValue);
attachFollow(value, source, options);
return value;
}
/**
* Attach an animation to a MotionValue that will animate whenever the value changes.
* Similar to attachSpring but supports any transition type (spring, tween, inertia, etc.)
*
* @param value - The MotionValue to animate
* @param source - Initial value or MotionValue to track
* @param options - Animation transition options
* @returns Cleanup function
*
* @public
*/
function attachFollow(value, source, options = {}) {
const initialValue = value.get();
let activeAnimation = null;
let latestValue = initialValue;
let latestSetter;
const unit = typeof initialValue === "string"
? initialValue.replace(/[\d.-]/g, "")
: undefined;
const stopAnimation = () => {
if (activeAnimation) {
activeAnimation.stop();
activeAnimation = null;
}
value.animation = undefined;
};
const startAnimation = () => {
const currentValue = asNumber(value.get());
const targetValue = asNumber(latestValue);
// Don't animate if we're already at the target
if (currentValue === targetValue) {
stopAnimation();
return;
}
// Use the running animation's analytical velocity for accuracy,
// falling back to the MotionValue's velocity for the initial animation.
// This prevents systematic velocity loss at high frame rates (240hz+).
const velocity = activeAnimation
? activeAnimation.getGeneratorVelocity()
: value.getVelocity();
stopAnimation();
activeAnimation = new JSAnimation({
keyframes: [currentValue, targetValue],
velocity,
// Default to spring if no type specified (matches useSpring behavior)
type: "spring",
restDelta: 0.001,
restSpeed: 0.01,
...options,
onUpdate: latestSetter,
});
};
// Use a stable function reference so the frame loop Set deduplicates
// multiple calls within the same frame (e.g. rapid mouse events)
const scheduleAnimation = () => {
startAnimation();
value.animation = activeAnimation ?? undefined;
value["events"].animationStart?.notify();
activeAnimation?.then(() => {
value.animation = undefined;
value["events"].animationComplete?.notify();
});
};
value.attach((v, set) => {
latestValue = v;
latestSetter = (latest) => set(parseValue(latest, unit));
frame.postRender(scheduleAnimation);
}, stopAnimation);
if (isMotionValue(source)) {
let skipNextAnimation = options.skipInitialAnimation === true;
const removeSourceOnChange = source.on("change", (v) => {
if (skipNextAnimation) {
skipNextAnimation = false;
value.jump(parseValue(v, unit), false);
}
else {
value.set(parseValue(v, unit));
}
});
const removeValueOnDestroy = value.on("destroy", removeSourceOnChange);
return () => {
removeSourceOnChange();
removeValueOnDestroy();
};
}
return stopAnimation;
}
function parseValue(v, unit) {
return unit ? v + unit : v;
}
function asNumber(v) {
return typeof v === "number" ? v : parseFloat(v);
}
export { attachFollow, followValue };
//# sourceMappingURL=follow-value.mjs.map
@@ -0,0 +1,589 @@
#ifndef NODE_SQLITE3_SRC_STATEMENT_H
#define NODE_SQLITE3_SRC_STATEMENT_H
#include <cstdlib>
#include <cstring>
#include <string>
#include <queue>
#include <vector>
#include <sqlite3.h>
#include <napi.h>
#include <uv.h>
#include "convert.h"
#include "database.h"
#include "threading.h"
using namespace Napi;
namespace node_sqlite3 {
class Statement : public Napi::ObjectWrap<Statement> {
public:
// Row shape requested from the synchronous read paths. SYNC_ROW_OBJECT
// is the historical default (plain objects, result-column order,
// last-duplicate-wins); SYNC_ROW_ARRAY is the bulk-reader opt-in
// (`{ rowMode: 'array' }`), which skips the per-cell property stores
// entirely — napi_set_element on a pre-sized array has no shape to
// transition, which is what makes it the fastest row we can build.
// SYNC_ROW_PLUCK (`{ rowMode: 'pluck' }`) serves only the first result
// column — better-sqlite3's pluck(), as a per-call option.
enum SyncRowMode {
SYNC_ROW_OBJECT = 0,
SYNC_ROW_ARRAY = 1,
SYNC_ROW_PLUCK = 2,
};
static Napi::Object Init(Napi::Env env, Napi::Object exports);
static Napi::Value New(const Napi::CallbackInfo& info);
// Cross-class argument validation (e.g. "is this a Statement?"),
// against this env's constructor — see Database::HasInstanceIn.
static inline bool HasInstance(Napi::Value val) {
return Database::HasInstanceIn(val,
&Database::AddonData::statement_ctor);
}
friend class Database;
// Runs the finalize work of an original finalize baton (directly, or
// via the deferred wrappers below).
struct Baton;
static void FinishFinalizeBaton(Baton* baton);
struct Baton {
napi_async_work request = NULL;
Statement* stmt;
Napi::FunctionReference callback;
Parameters parameters;
// True when the call site passed a bind argument at all (possibly
// an empty array/object). False means "re-step with the previous
// bindings", which must skip the parameter-count check.
bool bind_supplied = false;
Baton(Statement* stmt_, Napi::Function cb_) : stmt(stmt_) {
stmt->Ref();
callback.Reset(cb_, 1);
}
// Delivers `error` to whichever callback settles this call, used
// by CleanQueue when the statement is torn down with work still
// queued. Returns false when the call has no callback to settle,
// so the caller can fall back to an 'error' event. For most calls
// that callback is `callback`; each() overrides this, because
// there `callback` is the per-row callback and firing it would
// hand the caller a phantom row.
virtual bool Fail(Napi::Value error) {
Napi::Function cb = callback.Value();
if (cb.IsEmpty() || !cb.IsFunction()) return false;
Napi::Value argv[] = { error };
// A throwing callback still counts as settled: it ran.
TRY_CATCH_CALL(stmt->Value(), cb, 1, argv, true);
return true;
}
virtual ~Baton() {
parameters.clear();
if (request) napi_delete_async_work(stmt->Env(), request);
stmt->Unref();
callback.Reset();
}
};
struct RowBaton : Baton {
RowBaton(Statement* stmt_, Napi::Function cb_) :
Baton(stmt_, cb_) {}
Row row;
Columns columns;
// Row shape requested through a trailing `{ rowMode: ... }` options
// bag on the asynchronous read paths (Phase 1 ergonomics parity):
// the same SYNC_ROW_* values the synchronous paths use.
int row_mode = SYNC_ROW_OBJECT;
virtual ~RowBaton() override = default;
};
struct RunBaton : Baton {
RunBaton(Statement* stmt_, Napi::Function cb_) :
Baton(stmt_, cb_), inserted_id(0), changes(0) {}
sqlite3_int64 inserted_id;
int changes;
virtual ~RunBaton() override = default;
};
struct RowsBaton : Baton {
RowsBaton(Statement* stmt_, Napi::Function cb_) :
Baton(stmt_, cb_) {}
Rows rows;
Columns columns;
// See RowBaton::row_mode.
int row_mode = SYNC_ROW_OBJECT;
virtual ~RowsBaton() override = default;
};
// fetch(count, ...): like all(), but steps at most `count` rows so a
// pull-based iterator can apply backpressure. The statement is not
// reset between fetches; the cursor keeps its position.
struct FetchBaton : RowsBaton {
FetchBaton(Statement* stmt_, Napi::Function cb_) :
RowsBaton(stmt_, cb_), count(1), done(false) {}
int count;
// True when sqlite3_step returned SQLITE_DONE: the cursor is
// exhausted and only a rebind can produce more rows.
bool done;
virtual ~FetchBaton() override = default;
};
struct Async;
struct EachBaton : Baton {
Napi::FunctionReference completed;
Async* async; // Isn't deleted when the baton is deleted.
// See RowBaton::row_mode (published into the Async watcher).
int row_mode = SYNC_ROW_OBJECT;
EachBaton(Statement* stmt_, Napi::Function cb_) :
Baton(stmt_, cb_) {}
// When each() was given a completion handler that handler settles
// the call, and takes (err, rowCount). Without one the per-row
// callback is the only thing the caller passed, so the error goes
// there instead — never to both, and never a row-shaped call with
// no error.
virtual bool Fail(Napi::Value error) override {
Napi::Function done = completed.Value();
if (!done.IsEmpty() && done.IsFunction()) {
Napi::Value argv[] = {
error, Napi::Number::New(error.Env(), 0)
};
TRY_CATCH_CALL(stmt->Value(), done, 2, argv, true);
return true;
}
return Baton::Fail(error);
}
virtual ~EachBaton() override {
completed.Reset();
}
};
struct PrepareBaton : Database::Baton {
Statement* stmt;
std::string sql;
PrepareBaton(Database* db_, Napi::Function cb_, Statement* stmt_) :
Baton(db_, cb_), stmt(stmt_) {
stmt->Ref();
}
virtual ~PrepareBaton() override {
stmt->Unref();
if (db->IsClosed()) {
// The database handle was closed before the statement could be
// prepared.
stmt->Finalize_();
}
}
};
typedef void (*Work_Callback)(Baton* baton);
struct Call {
Call(Work_Callback cb_, Baton* baton_) : callback(cb_), baton(baton_) {};
Work_Callback callback;
Baton* baton;
};
// Deferral wrappers for the main-thread finalize paths (see
// Database::MayBlockOnWorkerRoundTrip): they carry the original work
// through the database's exclusive queue so the sqlite3_finalize runs
// on this thread only once no worker can hold the connection mutex.
struct DeferredFinalizeBaton : Database::Baton {
Statement::Baton* inner;
DeferredFinalizeBaton(Database* db_, Statement::Baton* inner_) :
Baton(db_, Napi::Function()), inner(inner_) {}
virtual ~DeferredFinalizeBaton() override {
delete inner;
}
};
struct HandleFinalizeBaton : Database::Baton {
sqlite3_stmt* handle;
HandleFinalizeBaton(Database* db_, sqlite3_stmt* handle_) :
Baton(db_, Napi::Function()), handle(handle_) {}
virtual ~HandleFinalizeBaton() override = default;
};
struct Async {
uv_async_t watcher;
Statement* stmt;
Rows data;
// Column names for the rows currently in `data`. Written by the
// worker thread and read by the main thread, both under the mutex
// below, so a mid-stream re-prepare cannot be missed.
Columns columns;
// Row shape for the delivered rows (EachBaton::row_mode), set once
// before the work starts and read on the JS thread only.
int row_mode = SYNC_ROW_OBJECT;
NODE_SQLITE3_MUTEX_t;
bool completed;
int retrieved;
// Store the callbacks here because we don't have
// access to the baton in the async callback.
Napi::FunctionReference item_cb;
Napi::FunctionReference completed_cb;
Async(Statement* st, uv_async_cb async_cb) :
stmt(st), completed(false), retrieved(0) {
watcher.data = this;
NODE_SQLITE3_MUTEX_INIT
stmt->Ref();
uv_loop_t *loop;
napi_get_uv_event_loop(stmt->Env(), &loop);
uv_async_init(loop, &watcher, async_cb);
}
~Async() {
stmt->Unref();
item_cb.Reset();
completed_cb.Reset();
NODE_SQLITE3_MUTEX_DESTROY
}
};
Statement(const Napi::CallbackInfo& info);
// Finalize-on-GC safety net: tears down a collected statement that
// was never finalized. Runs in the ObjectWrap finalizer, so it must
// not call into JS; see the definition in statement.cc for why each
// step is safe there.
~Statement();
WORK_DEFINITION(Bind)
WORK_DEFINITION(Get)
WORK_DEFINITION(Run)
WORK_DEFINITION(All)
WORK_DEFINITION(Each)
WORK_DEFINITION(Reset)
WORK_DEFINITION(Fetch)
Napi::Value Finalize_(const Napi::CallbackInfo& info);
// End-of-call bookkeeping for an asynchronous statement operation.
void EndCall();
// Runs EndCall() on every exit path from a Work_After* handler. This
// matters because TRY_CATCH_CALL returns early when a JS callback
// throws: doing the bookkeeping inline would then be skipped, leaving
// `locked` set and db->pending elevated forever. The statement's queue
// would never drain again and the sync fast path's idle gate could
// never pass, so one throwing callback would permanently disable
// getSync/runSync/allSync on that connection.
struct CallGuard {
Statement* stmt;
explicit CallGuard(Statement* s) : stmt(s) {}
~CallGuard() { stmt->EndCall(); }
CallGuard(const CallGuard&) = delete;
CallGuard& operator=(const CallGuard&) = delete;
};
// Opt-in synchronous fast path. Only legal when the database is fully
// idle (no worker in flight, nothing queued); otherwise throws.
Napi::Value GetSync(const Napi::CallbackInfo& info);
Napi::Value RunSync(const Napi::CallbackInfo& info);
Napi::Value AllSync(const Napi::CallbackInfo& info);
// Mode-aware accessors for the result of the last run(). lastID throws
// a RangeError in 'number' mode when the rowid is not a safe integer;
// lastIDBigInt is exact in every mode. changes is always a safe number.
Napi::Value GetLastID(const Napi::CallbackInfo& info);
Napi::Value GetLastIDBigInt(const Napi::CallbackInfo& info);
Napi::Value GetChanges(const Napi::CallbackInfo& info);
// True once the statement has been finalized: explicitly, after a
// failed prepare, or by the GC safety net. Operations on a finalized
// statement fail with SQLITE_MISUSE.
Napi::Value FinalizedGetter(const Napi::CallbackInfo& info);
// --- Introspection (Deliverable 07). readonly/parameterCount/
// parameterNames/columns serve a snapshot taken once, under the
// connection mutex, so the accessors never touch the sqlite3_stmt*
// and cannot race a stepping worker or a round-tripping JS callback.
// The sqlite3_stmt result shape does not change across a transparent
// re-prepare, so the snapshot holds for the statement's lifetime.
// status() reads live counters and takes the mutex instead, refusing
// while a JS round trip could hold it.
//
// Taking the snapshot and publishing it are deliberately separate.
// The async prepare runs on a libuv worker, and the accessors run on
// the JS thread: had the worker written the accessor-visible fields
// directly, a getter called during the prepare window would walk a
// std::vector mid-push_back — a dangling read, not merely a stale
// one. So SnapshotMetadata() (preparing thread, mutex held) fills
// pending_meta, and PublishMetadata() (JS thread only) moves it into
// place. The napi async-work completion that calls PublishMetadata()
// is ordered after the worker, so the move needs no atomics.
struct ColumnMeta {
std::string name;
std::string decltype_; // empty = none (expression/alias columns)
std::string database; // SQLITE_ENABLE_COLUMN_METADATA only
std::string table;
std::string origin;
};
struct Metadata {
bool readonly = false;
int param_count = 0;
std::vector<std::string> param_names; // "" entries: unnamed (?)
std::vector<ColumnMeta> columns;
};
void SnapshotMetadata();
void PublishMetadata();
Napi::Value ReadonlyGetter(const Napi::CallbackInfo& info);
Napi::Value ParameterCountGetter(const Napi::CallbackInfo& info);
Napi::Value ParameterNamesGetter(const Napi::CallbackInfo& info);
Napi::Value ColumnsGetter(const Napi::CallbackInfo& info);
Napi::Value Status(const Napi::CallbackInfo& info);
// SQL text accessors (Phase 6): the statement's SQL with bound values
// substituted (sqlite3_expanded_sql) and with literals normalized to
// `?` (sqlite3_normalized_sql, needs SQLITE_ENABLE_NORMALIZE). Both
// read the live statement, so they refuse while a worker round trip
// could hold the connection mutex.
Napi::Value ExpandedSQLGetter(const Napi::CallbackInfo& info);
Napi::Value NormalizedSQLGetter(const Napi::CallbackInfo& info);
// Shared refusal prelude of the two SQL accessors: true when the live
// statement may be read right now.
bool SQLAccessorGate(Napi::Env env);
// Per-statement integer-mode override (Phase 6 parity): 0 = none
// (follow the connection's mode), otherwise one of INTEGER_NUMBER /
// INTEGER_BIGINT / INTEGER_MIXED. Applied by the JS layer right after
// construction, so it is only ever read on the JS thread (all row
// conversion happens there).
Napi::Value SetIntegerMode(const Napi::CallbackInfo& info);
int EffectiveIntegerMode() const {
return has_integer_override ? integer_mode_override
: db->integer_mode;
}
protected:
static void Work_BeginPrepare(Database::Baton* baton);
static void Work_Prepare(napi_env env, void* data);
static void Work_AfterPrepare(napi_env env, napi_status status, void* data);
static void AsyncEach(uv_async_t* handle);
static void CloseCallback(uv_handle_t* handle);
static void Finalize_(Baton* baton);
void Finalize_();
template <class T> inline std::unique_ptr<Values::Field> BindParameter(const Napi::Value source, T pos);
// Binds [start, end) of the call into a baton, popping a trailing
// callback into the baton unless `preset_callback` carries one
// (Get/All/Each/Fetch pop it themselves when a `{ rowMode }` options
// bag sits between the bind parameters and the callback).
template <class T> T* Bind(const Napi::CallbackInfo& info, int start = 0,
int end = -1, Napi::Function preset_callback = Napi::Function());
// The bind-argument shapes (one array / N positional / one named
// object), shared by Bind<T> (into a Baton, for the queued async
// paths) and called directly by the synchronous fast paths, which
// have no Baton to fill. Returns false with a pending exception on
// unsupported values or a malformed shape.
bool ParseBindArguments(const Napi::CallbackInfo& info, int start,
int last, Parameters* parameters);
bool Bind(Parameters&& parameters, bool supplied);
// The synchronous counterpart of ParseBindArguments + Bind: applies the
// call's bind arguments straight onto the statement, with no
// Parameters vector and no heap Values::Field per parameter.
//
// Accepts the same three argument shapes, performs the same arity and
// named-parameter checks, produces the same error text, and leaves the
// statement in the same state on failure. The asynchronous paths keep
// the Field route: they read the arguments on the JS thread and apply
// them on a worker, so there the materialisation is the hand-off.
bool BindArgumentsDirect(const Napi::CallbackInfo& info, int start,
int last, bool supplied);
static void GetRow(Row* row, sqlite3_stmt* stmt, Columns* columns);
// Rebuilds the rooted JS key strings if `columns` differs from the set
// they were built from. Call once per batch, before RowToJS.
void SyncColumnKeys(Napi::Env env, const Columns& columns);
Napi::Value RowToJS(Napi::Env env, Row* row,
int row_mode = SYNC_ROW_OBJECT);
// The scopeless core of RowToJS, and the asynchronous counterpart of
// ConvertCurrentRow: converts one already-materialised Row into the
// caller's HandleScope. Returns false when the 'number'-mode RangeError
// left a pending exception. Callers must store `*out` into a rooted JS
// object before their scope closes.
bool ConvertCellRow(Napi::Env env, Row* row,
const std::vector<napi_value>& keys, int row_mode, napi_value* out);
// Converts a whole materialised result set into a JS array, resolving
// the column keys once and opening one HandleScope per batch of rows
// rather than one per row.
//
// This is the shared tail of every asynchronous read completion
// (all/fetch, and their promise forms). Those paths must materialise
// Cells — the rows are read on a worker thread and converted later on
// the JS thread — but the *conversion* is a plain synchronous pass and
// has no reason to cost more per row than the synchronous paths do.
//
// Returns false when a row raised the RangeError, leaving it pending
// for the caller to deliver to the callback.
bool CellRowsToJS(Napi::Env env, Rows& rows, const Columns& columns,
int row_mode, Napi::Array* out);
// The synchronous counterpart of RowToJS: builds the row object from
// the live statement, with no intermediate Row. Requires the column
// keys to have been synced for the current result shape. `row_mode`
// picks the row shape (object or array); the array shape never reads
// `keys`.
Napi::Value CurrentRowToJS(Napi::Env env,
const std::vector<napi_value>& keys, int row_mode = SYNC_ROW_OBJECT);
// The scopeless core of CurrentRowToJS: converts the current row into
// the caller's HandleScope and reports via the return value whether it
// completed (false = the 'number'-mode RangeError left a pending
// exception). Callers must store `*out` into a rooted JS object before
// their scope closes — which the synchronous paths do immediately,
// into the result array they are building.
bool ConvertCurrentRow(Napi::Env env, const std::vector<napi_value>& keys,
int row_mode, int cols, napi_value* out);
// Resolves the cached column-key references into raw napi_values once
// per call, so a multi-row read does not re-dereference them per cell.
void ResolveColumnKeys(std::vector<napi_value>* out);
// Returns the compiled row factory for the current result shape, or
// NULL when this build/realm/shape cannot use one (see
// AddonData::row_factory_generator, and kMaxFactoryColumns). Compiled
// on first use per shape and dropped whenever the column keys are
// rebuilt, so a mid-stream re-prepare cannot reuse a stale shape.
napi_value RowFactoryForShape(Napi::Env env, int row_mode);
// Drops the compiled factories. Called from the two places that
// invalidate the column keys.
void ResetRowFactories(Napi::Env env);
// Builds one row by calling the shape's factory with the cells as
// arguments — one napi_call_function instead of one V8 store per
// column. `cells` must already hold `cols` converted values.
bool CallRowFactory(Napi::Env env, napi_value factory,
const std::vector<napi_value>& cells, int cols, napi_value* out);
// Above this column count the generated function is not worth it (and
// approaches V8's parameter limit): those shapes keep the store loop.
static const int kMaxFactoryColumns = 256;
// Compiled factories for this statement's current result shape,
// indexed by SyncRowMode. NULL until first used for that mode.
napi_ref row_factory_[2] = { NULL, NULL };
// Converts an int64 cell/rowid according to the database's integer
// mode. Throws a RangeError in 'number' mode for unsafe values;
// callers must check env.IsExceptionPending() afterwards.
Napi::Value Int64ToJS(Napi::Env env, sqlite3_int64 value, const std::string& what);
// Stores the result of a completed run() for the lastID/lastIDBigInt/
// changes accessors.
void RecordRunResult(sqlite3_int64 id, int changes);
void Schedule(Work_Callback callback, Baton* baton);
void Process();
void CleanQueue();
template <class T> static void Error(T* baton);
// True when nothing anywhere on this database is in flight or queued,
// so sqlite can be driven from the main thread without racing the
// worker pool or breaking FIFO ordering.
bool IdleForInline();
// The synchronous methods' shared safety gate: not finalized, fully
// idle, no JavaScript collation or progress handler that would have to
// run on the thread blocked inside SQLite. Throws; false means the
// caller must return env.Null().
bool SyncGate(Napi::Env env);
// RAII marker for "this statement's VM is currently executing on the
// JS thread": a user-defined function invoked from the sync path can
// call back into the synchronous methods, but not into *this*
// statement — re-entering a stepping VM is the one hard rule SQLite
// has (node:sqlite enforces the same since v26.8). Other statements
// on the same connection stay legal: the connection mutex is
// recursive, so a nested step just re-enters it.
struct SyncStepGuard {
Statement* stmt;
explicit SyncStepGuard(Statement* s) : stmt(s) { stmt->sync_in_flight = true; }
~SyncStepGuard() { stmt->sync_in_flight = false; }
SyncStepGuard(const SyncStepGuard&) = delete;
SyncStepGuard& operator=(const SyncStepGuard&) = delete;
};
// Throws the pending status/message as a JS error with errno/code.
void ThrowStatementError(Napi::Env env);
void FailQueue(Napi::Value error, bool emit_if_unhandled = true);
protected:
// NULL when the constructor threw before validation completed; every
// destructor path gates on it.
Database* db = NULL;
sqlite3_stmt* _handle = NULL;
int status = SQLITE_OK;
bool prepared = false;
bool locked = true;
bool finalized = false;
// True while this statement's VM is executing inside a *Sync call on
// the JS thread (see SyncStepGuard): a re-entrant sync call from a
// user-defined function must refuse rather than corrupt the VDBE.
bool sync_in_flight = false;
// Byte offset of the failing token of the most recent failed prepare,
// from sqlite3_error_offset() (-1 when the last error was not a
// prepare error or there was no error). Attached to the thrown
// SqliteError as `offset` (bun:sqlite exposes the same as byteOffset;
// no other Node driver has it). Written under the connection mutex
// wherever a prepare fails; read on the JS thread when the error is
// built, which the async-work completion ordering serializes.
int error_offset = -1;
// Per-statement integer-mode override (see SetIntegerMode).
int integer_mode_override = 0;
bool has_integer_override = false;
// Result of the most recent run(), exposed through the lastID,
// lastIDBigInt and changes accessors.
sqlite3_int64 last_insert_id = 0;
int last_changes = 0;
bool has_run_result = false;
// Payloads of the currently SQLITE_STATIC-bound text/blob parameters.
// Owned until the next rebind or finalize so sqlite never sees a
// dangling pointer when a statement is stepped again without rebinding.
Parameters bound_payloads;
// Rooted JS key strings used for row conversion, plus the column names
// they were built from so a schema change can invalidate them.
std::vector<std::string> column_keys_source;
std::vector<Napi::Reference<Napi::String>> column_keys;
// Shape tracking for the synchronous read paths' key cache: a sync
// call re-reads the live column names only when the statement's shape
// has moved (transparent re-prepare counter or column count changed).
// One sqlite3_stmt_status call per call replaces the fresh heap
// vector<string> of names the old per-call Columns captured.
void SyncColumnKeysLive(Napi::Env env);
Columns sync_columns;
bool sync_keys_valid = false;
int sync_keys_reprepares = -1;
int sync_keys_cols = -1;
// Introspection snapshot. pending_meta is written by the preparing
// thread; meta and meta_valid are touched only by the JS thread, and
// meta_valid gates the accessors (the async prepare window leaves
// them undefined). See the note above PublishMetadata().
Metadata pending_meta;
Metadata meta;
bool meta_valid = false;
std::queue<Call*> queue;
std::string message;
};
}
#endif
@@ -0,0 +1,33 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_hono = require("../../hono.js");
//#region src/helper/factory/index.ts
/**
* @module
* Factory Helper for Hono.
*/
var Factory = class {
initApp;
#defaultAppOptions;
constructor(init) {
this.initApp = init?.initApp;
this.#defaultAppOptions = init?.defaultAppOptions;
}
createApp = (options) => {
const app = new require_hono.Hono(options && this.#defaultAppOptions ? {
...this.#defaultAppOptions,
...options
} : options ?? this.#defaultAppOptions);
if (this.initApp) this.initApp(app);
return app;
};
createMiddleware = (middleware) => middleware;
createHandlers = (...handlers) => {
return handlers.filter((handler) => handler !== void 0);
};
};
const createFactory = (init) => new Factory(init);
const createMiddleware = (middleware) => middleware;
//#endregion
exports.Factory = Factory;
exports.createFactory = createFactory;
exports.createMiddleware = createMiddleware;
@@ -0,0 +1,44 @@
/*
Copyright 2012-2015, Yahoo Inc.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
'use strict';
const { ReportBase } = require('istanbul-lib-report');
class JsonReport extends ReportBase {
constructor(opts) {
super();
this.file = opts.file || 'coverage-final.json';
this.first = true;
}
onStart(root, context) {
this.contentWriter = context.writer.writeFile(this.file);
this.contentWriter.write('{');
}
onDetail(node) {
const fc = node.getFileCoverage();
const key = fc.path;
const cw = this.contentWriter;
if (this.first) {
this.first = false;
} else {
cw.write(',');
}
cw.write(JSON.stringify(key));
cw.write(': ');
cw.write(JSON.stringify(fc));
cw.println('');
}
onEnd() {
const cw = this.contentWriter;
cw.println('}');
cw.close();
}
}
module.exports = JsonReport;
@@ -0,0 +1,485 @@
/**
* SHA3 (keccak) hash function, based on a new "Sponge function" design.
* Different from older hashes, the internal state is bigger than output size.
*
* Check out
* {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf | FIPS-202},
* {@link https://keccak.team/keccak.html | Website}, and
* {@link https://crypto.stackexchange.com/q/15727 | the differences between
* SHA-3 and Keccak}.
*
* Check out `sha3-addons` module for cSHAKE, k12, and others.
* @module
*/
import { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.ts';
// prettier-ignore
import {
abytes, aexists, anumber, aoutput,
clean, createHasher,
oidNist,
swap32IfBE,
u32,
type CHash, type CHashXOF,
type Hash,
type HashInfo,
type HashXOF,
type TArg,
type TRet
} from './utils.ts';
// No __PURE__ annotations in sha3 header:
// EVERYTHING is in fact used on every export.
// Various per round constants calculations
const _0n = BigInt(0);
const _1n = BigInt(1);
const _2n = BigInt(2);
const _7n = BigInt(7);
const _256n = BigInt(256);
// FIPS 202 Algorithm 5 rc(): when the outgoing bit is 1, the 8-bit LFSR xors
// taps 0, 4, 5, and 6, which compresses to the feedback mask `0x71`.
const _0x71n = BigInt(0x71);
const SHA3_PI: number[] = [];
const SHA3_ROTL: number[] = [];
const _SHA3_IOTA: bigint[] = []; // no pure annotation: var is always used
for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
// Pi
[x, y] = [y, (2 * x + 3 * y) % 5];
SHA3_PI.push(2 * (5 * y + x));
// Rotational
SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
// Iota
let t = _0n;
for (let j = 0; j < 7; j++) {
R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;
if (R & _2n) t ^= _1n << ((_1n << BigInt(j)) - _1n);
}
_SHA3_IOTA.push(t);
}
const IOTAS = split(_SHA3_IOTA, true);
// `split(..., true)` keeps the local little-endian lane-word layout used by
// `state32`, so these `H` / `L` tables follow the file's first-word /
// second-word lane slots rather than `_u64.ts`'s usual high/low naming.
const SHA3_IOTA_H = IOTAS[0];
const SHA3_IOTA_L = IOTAS[1];
// Left rotation (without 0, 32, 64)
const rotlH = (h: number, l: number, s: number) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
const rotlL = (h: number, l: number, s: number) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
/**
* `keccakf1600` internal permutation, additionally allows adjusting the round count.
* @param s - 5x5 Keccak state encoded as 25 lanes split into 50 uint32 words
* in this file's local little-endian lane-word order
* @param rounds - number of rounds to execute
* @throws If `rounds` is outside the supported `1..24` range. {@link Error}
* @example
* Permute a Keccak state with the default 24 rounds.
* ```ts
* keccakP(new Uint32Array(50));
* ```
*/
export function keccakP(s: TArg<Uint32Array>, rounds: number = 24): void {
anumber(rounds, 'rounds');
// This implementation precomputes only the standard Keccak-f[1600] 24-round Iota table.
if (rounds < 1 || rounds > 24) throw new Error('"rounds" expected integer 1..24');
const B = new Uint32Array(5 * 2);
// NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
for (let round = 24 - rounds; round < 24; round++) {
// Theta θ
for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
for (let x = 0; x < 10; x += 2) {
const idx1 = (x + 8) % 10;
const idx0 = (x + 2) % 10;
const B0 = B[idx0];
const B1 = B[idx0 + 1];
const Th = rotlH(B0, B1, 1) ^ B[idx1];
const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
for (let y = 0; y < 50; y += 10) {
s[x + y] ^= Th;
s[x + y + 1] ^= Tl;
}
}
// Rho (ρ) and Pi (π)
let curH = s[2];
let curL = s[3];
for (let t = 0; t < 24; t++) {
const shift = SHA3_ROTL[t];
const Th = rotlH(curH, curL, shift);
const Tl = rotlL(curH, curL, shift);
const PI = SHA3_PI[t];
curH = s[PI];
curL = s[PI + 1];
s[PI] = Th;
s[PI + 1] = Tl;
}
// Chi (χ)
// Same as:
// for (let x = 0; x < 10; x++) B[x] = s[y + x];
// for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
for (let y = 0; y < 50; y += 10) {
const b0 = s[y],
b1 = s[y + 1],
b2 = s[y + 2],
b3 = s[y + 3];
s[y] ^= ~s[y + 2] & s[y + 4];
s[y + 1] ^= ~s[y + 3] & s[y + 5];
s[y + 2] ^= ~s[y + 4] & s[y + 6];
s[y + 3] ^= ~s[y + 5] & s[y + 7];
s[y + 4] ^= ~s[y + 6] & s[y + 8];
s[y + 5] ^= ~s[y + 7] & s[y + 9];
s[y + 6] ^= ~s[y + 8] & b0;
s[y + 7] ^= ~s[y + 9] & b1;
s[y + 8] ^= ~b0 & b2;
s[y + 9] ^= ~b1 & b3;
}
// Iota (ι)
s[0] ^= SHA3_IOTA_H[round];
s[1] ^= SHA3_IOTA_L[round];
}
clean(B);
}
/**
* Keccak sponge function.
* @param blockLen - absorb/squeeze rate in bytes
* @param suffix - domain separation suffix byte
* @param outputLen - default digest length in bytes. This base sponge only
* requires a non-negative integer; wrappers that need positive output
* lengths must enforce that themselves.
* @param enableXOF - whether XOF output is allowed
* @param rounds - number of Keccak-f rounds
* @example
* Build a sponge state, absorb bytes, then finalize a digest.
* ```ts
* const hash = new Keccak(136, 0x06, 32);
* hash.update(new Uint8Array([1, 2, 3]));
* hash.digest();
* ```
*/
export class Keccak implements Hash<Keccak>, HashXOF<Keccak> {
protected state: Uint8Array;
protected pos = 0;
protected posOut = 0;
protected finished = false;
protected state32: Uint32Array;
protected destroyed = false;
public blockLen: number;
public suffix: number;
public outputLen: number;
public canXOF: boolean;
protected enableXOF = false;
protected rounds: number;
// NOTE: we accept arguments in bytes instead of bits here.
constructor(
blockLen: number,
suffix: number,
outputLen: number,
enableXOF = false,
rounds: number = 24
) {
this.blockLen = blockLen;
this.suffix = suffix;
this.outputLen = outputLen;
this.enableXOF = enableXOF;
this.canXOF = enableXOF;
this.rounds = rounds;
// Can be passed from user as dkLen
anumber(outputLen, 'outputLen');
// 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
// 0 < blockLen < 200
if (!(0 < blockLen && blockLen < 200))
throw new Error('only keccak-f1600 function is supported');
this.state = new Uint8Array(200);
this.state32 = u32(this.state);
}
clone(): Keccak {
return this._cloneInto();
}
protected keccak(): void {
swap32IfBE(this.state32);
keccakP(this.state32, this.rounds);
swap32IfBE(this.state32);
this.posOut = 0;
this.pos = 0;
}
update(data: TArg<Uint8Array>): this {
aexists(this);
abytes(data);
const { blockLen, state } = this;
const len = data.length;
for (let pos = 0; pos < len; ) {
const take = Math.min(blockLen - this.pos, len - pos);
for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++];
if (this.pos === blockLen) this.keccak();
}
return this;
}
protected finish(): void {
if (this.finished) return;
this.finished = true;
const { state, suffix, pos, blockLen } = this;
// FIPS 202 appends the SHA3/SHAKE domain-separation suffix before pad10*1.
// These byte values already include the first padding bit, while the
// final `0x80` below supplies the closing `1` bit in the last rate byte.
state[pos] ^= suffix;
// If that combined suffix lands in the last rate byte and already sets
// bit 7, absorb it first so the final pad10*1 bit can be xored into a
// fresh block.
if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak();
state[blockLen - 1] ^= 0x80;
this.keccak();
}
protected writeInto(out: TArg<Uint8Array>): TRet<Uint8Array> {
aexists(this, false);
abytes(out);
this.finish();
const bufferOut = this.state;
const { blockLen } = this;
for (let pos = 0, len = out.length; pos < len; ) {
if (this.posOut >= blockLen) this.keccak();
const take = Math.min(blockLen - this.posOut, len - pos);
out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
this.posOut += take;
pos += take;
}
return out as TRet<Uint8Array>;
}
xofInto(out: TArg<Uint8Array>): TRet<Uint8Array> {
// Plain SHA3/Keccak usage with XOF is probably a mistake, but this base
// class is also reused by SHAKE/cSHAKE/KMAC/TupleHash/ParallelHash/
// TurboSHAKE/KangarooTwelve wrappers that intentionally enable XOF.
if (!this.enableXOF) throw new Error('XOF is not possible for this instance');
return this.writeInto(out);
}
xof(bytes: number): TRet<Uint8Array> {
anumber(bytes);
return this.xofInto(new Uint8Array(bytes));
}
digestInto(out: TArg<Uint8Array>): void {
aoutput(out, this);
if (this.finished) throw new Error('digest() was already called');
// `aoutput(...)` allows oversized buffers; digestInto() must fill only the advertised digest.
this.writeInto(out.subarray(0, this.outputLen));
this.destroy();
}
digest(): TRet<Uint8Array> {
const out = new Uint8Array(this.outputLen);
this.digestInto(out);
return out as TRet<Uint8Array>;
}
destroy(): void {
this.destroyed = true;
clean(this.state);
}
_cloneInto(to?: Keccak): Keccak {
const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);
// Reused destinations can come from a different rate/capacity variant, so clone must rewrite
// the sponge geometry as well as the state words.
to.blockLen = blockLen;
to.state32.set(this.state32);
to.pos = this.pos;
to.posOut = this.posOut;
to.finished = this.finished;
to.rounds = rounds;
// Suffix can change in cSHAKE
to.suffix = suffix;
to.outputLen = outputLen;
to.enableXOF = enableXOF;
// Clones must preserve the public capability bit too; `_KMAC` reuses this path and deep clone
// tests compare instance fields directly, so leaving `canXOF` behind makes the clone lie.
to.canXOF = this.canXOF;
to.destroyed = this.destroyed;
return to;
}
}
const genKeccak = (
suffix: number,
blockLen: number,
outputLen: number,
info: TArg<HashInfo> = {}
) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
/**
* SHA3-224 hash function.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with SHA3-224.
* ```ts
* sha3_224(new Uint8Array([97, 98, 99]));
* ```
*/
export const sha3_224: TRet<CHash> = /* @__PURE__ */ genKeccak(
0x06,
144,
28,
/* @__PURE__ */ oidNist(0x07)
);
/**
* SHA3-256 hash function. Different from keccak-256.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with SHA3-256.
* ```ts
* sha3_256(new Uint8Array([97, 98, 99]));
* ```
*/
export const sha3_256: TRet<CHash> = /* @__PURE__ */ genKeccak(
0x06,
136,
32,
/* @__PURE__ */ oidNist(0x08)
);
/**
* SHA3-384 hash function.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with SHA3-384.
* ```ts
* sha3_384(new Uint8Array([97, 98, 99]));
* ```
*/
export const sha3_384: TRet<CHash> = /* @__PURE__ */ genKeccak(
0x06,
104,
48,
/* @__PURE__ */ oidNist(0x09)
);
/**
* SHA3-512 hash function.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with SHA3-512.
* ```ts
* sha3_512(new Uint8Array([97, 98, 99]));
* ```
*/
export const sha3_512: TRet<CHash> = /* @__PURE__ */ genKeccak(
0x06,
72,
64,
/* @__PURE__ */ oidNist(0x0a)
);
/**
* Keccak-224 hash function.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with Keccak-224.
* ```ts
* keccak_224(new Uint8Array([97, 98, 99]));
* ```
*/
export const keccak_224: TRet<CHash> = /* @__PURE__ */ genKeccak(0x01, 144, 28);
/**
* Keccak-256 hash function. Different from SHA3-256.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with Keccak-256.
* ```ts
* keccak_256(new Uint8Array([97, 98, 99]));
* ```
*/
export const keccak_256: TRet<CHash> = /* @__PURE__ */ genKeccak(0x01, 136, 32);
/**
* Keccak-384 hash function.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with Keccak-384.
* ```ts
* keccak_384(new Uint8Array([97, 98, 99]));
* ```
*/
export const keccak_384: TRet<CHash> = /* @__PURE__ */ genKeccak(0x01, 104, 48);
/**
* Keccak-512 hash function.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with Keccak-512.
* ```ts
* keccak_512(new Uint8Array([97, 98, 99]));
* ```
*/
export const keccak_512: TRet<CHash> = /* @__PURE__ */ genKeccak(0x01, 72, 64);
/** Options for SHAKE XOF. */
export type ShakeOpts = {
/** Desired number of output bytes. */
dkLen?: number;
};
const genShake = (suffix: number, blockLen: number, outputLen: number, info: TArg<HashInfo> = {}) =>
createHasher<Keccak, ShakeOpts>(
(opts: ShakeOpts = {}) =>
new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true),
info
);
/**
* SHAKE128 XOF with 128-bit security and a 16-byte default output.
* @param msg - message bytes to hash
* @param opts - Optional output-length override. See {@link ShakeOpts}.
* @returns Digest bytes.
* @example
* Hash a message with SHAKE128.
* ```ts
* shake128(new Uint8Array([97, 98, 99]), { dkLen: 32 });
* ```
*/
export const shake128: TRet<CHashXOF<Keccak, ShakeOpts>> =
/* @__PURE__ */
genShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b));
/**
* SHAKE256 XOF with 256-bit security and a 32-byte default output.
* @param msg - message bytes to hash
* @param opts - Optional output-length override. See {@link ShakeOpts}.
* @returns Digest bytes.
* @example
* Hash a message with SHAKE256.
* ```ts
* shake256(new Uint8Array([97, 98, 99]), { dkLen: 64 });
* ```
*/
export const shake256: TRet<CHashXOF<Keccak, ShakeOpts>> =
/* @__PURE__ */
genShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));
/**
* SHAKE128 XOF with 256-bit output (NIST version).
* @param msg - message bytes to hash
* @param opts - Optional output-length override. See {@link ShakeOpts}.
* @returns Digest bytes.
* @example
* Hash a message with SHAKE128 using a 32-byte default output.
* ```ts
* shake128_32(new Uint8Array([97, 98, 99]), { dkLen: 32 });
* ```
*/
export const shake128_32: TRet<CHashXOF<Keccak, ShakeOpts>> =
/* @__PURE__ */
genShake(0x1f, 168, 32, /* @__PURE__ */ oidNist(0x0b));
/**
* SHAKE256 XOF with 512-bit output (NIST version).
* @param msg - message bytes to hash
* @param opts - Optional output-length override. See {@link ShakeOpts}.
* @returns Digest bytes.
* @example
* Hash a message with SHAKE256 using a 64-byte default output.
* ```ts
* shake256_64(new Uint8Array([97, 98, 99]), { dkLen: 64 });
* ```
*/
export const shake256_64: TRet<CHashXOF<Keccak, ShakeOpts>> =
/* @__PURE__ */
genShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c));
@@ -0,0 +1 @@
{"version":3,"file":"gestures.mjs","sources":["../../../../src/motion/features/gestures.ts"],"sourcesContent":["import { HoverGesture } from \"../../gestures/hover\"\nimport { FocusGesture } from \"../../gestures/focus\"\nimport { PressGesture } from \"../../gestures/press\"\nimport { InViewFeature } from \"./viewport\"\nimport { FeaturePackages } from \"./types\"\n\nexport const gestureAnimations: FeaturePackages = {\n inView: {\n Feature: InViewFeature,\n },\n tap: {\n Feature: PressGesture,\n },\n focus: {\n Feature: FocusGesture,\n },\n hover: {\n Feature: HoverGesture,\n },\n}\n"],"names":[],"mappings":";;;;;AAMO,MAAM,iBAAiB,GAAoB;AAC9C,IAAA,MAAM,EAAE;AACJ,QAAA,OAAO,EAAE,aAAa;AACzB,KAAA;AACD,IAAA,GAAG,EAAE;AACD,QAAA,OAAO,EAAE,YAAY;AACxB,KAAA;AACD,IAAA,KAAK,EAAE;AACH,QAAA,OAAO,EAAE,YAAY;AACxB,KAAA;AACD,IAAA,KAAK,EAAE;AACH,QAAA,OAAO,EAAE,YAAY;AACxB,KAAA;;;;;"}
@@ -0,0 +1,124 @@
import type { $ZodStringFormats } from "../core/checks.js";
import type * as errors from "../core/errors.js";
import * as util from "../core/util.js";
const error: () => errors.$ZodErrorMap = () => {
const Sizable: Record<string, { unit: string; verb: string }> = {
string: { unit: "តួអក្សរ", verb: "គួរមាន" },
file: { unit: "បៃ", verb: "គួរមាន" },
array: { unit: "ធាតុ", verb: "គួរមាន" },
set: { unit: "ធាតុ", verb: "គួរមាន" },
map: { unit: "ធាតុ", verb: "គួរមាន" },
};
function getSizing(origin: string): { unit: string; verb: string } | null {
return Sizable[origin] ?? null;
}
const FormatDictionary: {
[k in $ZodStringFormats | (string & {})]?: string;
} = {
regex: "ទិន្នន័យបញ្ចូល",
email: "អាសយដ្ឋានអ៊ីមែល",
url: "URL",
emoji: "សញ្ញាអារម្មណ៍",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "កាលបរិច្ឆេទ និងម៉ោង ISO",
date: "កាលបរិច្ឆេទ ISO",
time: "ម៉ោង ISO",
duration: "រយៈពេល ISO",
ipv4: "អាសយដ្ឋាន IPv4",
ipv6: "អាសយដ្ឋាន IPv6",
mac: "អាសយដ្ឋាន MAC",
cidrv4: "ដែនអាសយដ្ឋាន IPv4",
cidrv6: "ដែនអាសយដ្ឋាន IPv6",
base64: "ខ្សែអក្សរអ៊ិកូដ base64",
base64url: "ខ្សែអក្សរអ៊ិកូដ base64url",
json_string: "ខ្សែអក្សរ JSON",
e164: "លេខ E.164",
credit_card: "លេខប័ណ្ណឥណទាន",
currency_code: "កូដរូបិយប័ណ្ណ",
iban: "IBAN",
jwt: "JWT",
template_literal: "ទិន្នន័យបញ្ចូល",
};
const TypeDictionary: {
[k in errors.$ZodInvalidTypeExpected | (string & {})]?: string;
} = {
nan: "NaN",
number: "លេខ",
array: "អារេ (Array)",
null: "គ្មានតម្លៃ (null)",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (/^[A-Z]/.test(issue.expected)) {
return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${issue.expected} ប៉ុន្តែទទួលបាន ${received}`;
}
return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${expected} ប៉ុន្តែទទួលបាន ${received}`;
}
case "invalid_value":
if (issue.values.length === 1) return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${util.stringifyPrimitive(issue.values[0])}`;
return `ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `ធំពេក៖ ត្រូវការ ${issue.origin ?? "តម្លៃ"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "ធាតុ"}`;
return `ធំពេក៖ ត្រូវការ ${issue.origin ?? "តម្លៃ"} ${adj} ${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()} ${sizing.unit}`;
}
return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue as errors.$ZodStringFormatIssues;
if (_issue.format === "starts_with") {
return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${_issue.prefix}"`;
}
if (_issue.format === "ends_with") return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${_issue.suffix}"`;
if (_issue.format === "includes") return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${_issue.includes}"`;
if (_issue.format === "regex") return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${_issue.pattern}`;
return `មិនត្រឹមត្រូវ៖ ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${issue.divisor}`;
case "unrecognized_keys":
return `រកឃើញសោមិនស្គាល់៖ ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `សោមិនត្រឹមត្រូវនៅក្នុង ${issue.origin}`;
case "invalid_union":
return `ទិន្នន័យមិនត្រឹមត្រូវ`;
case "invalid_element":
return `ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${issue.origin}`;
default:
return `ទិន្នន័យមិនត្រឹមត្រូវ`;
}
};
};
export default function (): { localeError: errors.$ZodErrorMap } {
return {
localeError: error(),
};
}
@@ -0,0 +1 @@
{"version":3,"file":"defaults.mjs","sources":["../../../../../src/value/types/maps/defaults.ts"],"sourcesContent":["import { color } from \"../color\"\nimport { filter } from \"../complex/filter\"\nimport { mask } from \"../complex/mask\"\nimport { numberValueTypes } from \"./number\"\nimport { ValueTypeMap } from \"./types\"\n\n/**\n * A map of default value types for common values\n */\nexport const defaultValueTypes: ValueTypeMap = {\n ...numberValueTypes,\n\n // Color props\n color,\n backgroundColor: color,\n outlineColor: color,\n fill: color,\n stroke: color,\n\n // Border props\n borderColor: color,\n borderTopColor: color,\n borderRightColor: color,\n borderBottomColor: color,\n borderLeftColor: color,\n filter,\n WebkitFilter: filter,\n mask,\n WebkitMask: mask,\n}\n\n/**\n * Gets the default ValueType for the provided value key\n */\nexport const getDefaultValueType = (key: string) => defaultValueTypes[key]\n"],"names":[],"mappings":";;;;;AAMA;;AAEG;AACI,MAAM,iBAAiB,GAAiB;AAC3C,IAAA,GAAG,gBAAgB;;IAGnB,KAAK;AACL,IAAA,eAAe,EAAE,KAAK;AACtB,IAAA,YAAY,EAAE,KAAK;AACnB,IAAA,IAAI,EAAE,KAAK;AACX,IAAA,MAAM,EAAE,KAAK;;AAGb,IAAA,WAAW,EAAE,KAAK;AAClB,IAAA,cAAc,EAAE,KAAK;AACrB,IAAA,gBAAgB,EAAE,KAAK;AACvB,IAAA,iBAAiB,EAAE,KAAK;AACxB,IAAA,eAAe,EAAE,KAAK;IACtB,MAAM;AACN,IAAA,YAAY,EAAE,MAAM;IACpB,IAAI;AACJ,IAAA,UAAU,EAAE,IAAI;;AAGpB;;AAEG;AACI,MAAM,mBAAmB,GAAG,CAAC,GAAW,KAAK,iBAAiB,CAAC,GAAG;;;;"}
@@ -0,0 +1,19 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const DatabaseZap = createLucideIcon("DatabaseZap", [
["ellipse", { cx: "12", cy: "5", rx: "9", ry: "3", key: "msslwz" }],
["path", { d: "M3 5V19A9 3 0 0 0 15 21.84", key: "14ibmq" }],
["path", { d: "M21 5V8", key: "1marbg" }],
["path", { d: "M21 12L18 17H22L19 22", key: "zafso" }],
["path", { d: "M3 12A9 3 0 0 0 14.59 14.87", key: "1y4wr8" }]
]);
export { DatabaseZap as default };
//# sourceMappingURL=database-zap.js.map
@@ -0,0 +1,241 @@
import { buildRankedDictionary } from './utils/helper'
import {
TranslationKeys,
OptionsType,
OptionsDictionary,
OptionsL33tTable,
OptionsGraph,
RankedDictionaries,
Matchers,
Matcher,
UserInputsOptions,
RankedDictionary,
TimeEstimationValues,
} from './types'
import l33tTable from './data/l33tTable'
import translationKeys from './data/translationKeys'
import TrieNode from './matcher/dictionary/variants/matching/unmunger/TrieNode'
import l33tTableToTrieNode from './matcher/dictionary/variants/matching/unmunger/l33tTableToTrieNode'
import {
checkTimeEstimationValues,
timeEstimationValuesDefaults,
} from './TimeEstimates'
export default class Options {
public matchers: Matchers = {}
public l33tTable: OptionsL33tTable = l33tTable
public trieNodeRoot: TrieNode = l33tTableToTrieNode(l33tTable, new TrieNode())
public dictionary: OptionsDictionary = {
userInputs: [],
}
public rankedDictionaries: RankedDictionaries = {}
public rankedDictionariesMaxWordSize: Record<string, number> = {}
public translations: TranslationKeys = translationKeys
public graphs: OptionsGraph = {}
public useLevenshteinDistance = false
public levenshteinThreshold = 2
public l33tMaxSubstitutions = 100
public maxLength = 256
public wordSequenceNames = [
'cardinalNumbers',
'ordinalNumbers',
'daysOfWeek',
'months',
'seasons',
'timePeriods',
'rainbowColors',
'directions',
'intermediateDirections',
'sizeProgression',
'militaryAlphabet',
'planets',
'zodiacSigns',
'chineseZodiac',
]
timeEstimationValues: TimeEstimationValues = {
scoring: {
...timeEstimationValuesDefaults.scoring,
},
attackTime: {
...timeEstimationValuesDefaults.attackTime,
},
}
constructor(
options: OptionsType = {},
customMatchers: Record<string, Matcher> = {},
) {
this.setOptions(options)
Object.entries(customMatchers).forEach(([name, matcher]) => {
this.addMatcher(name, matcher)
})
}
public isWordSequence(key: string) {
return this.wordSequenceNames.some(
(name) => key === name || key.startsWith(`${name}-`),
)
}
// eslint-disable-next-line max-statements,complexity
private setOptions(options: OptionsType = {}) {
if (options.l33tTable) {
this.l33tTable = options.l33tTable
this.trieNodeRoot = l33tTableToTrieNode(options.l33tTable, new TrieNode())
}
if (options.dictionary) {
this.dictionary = options.dictionary
this.setRankedDictionaries()
}
if (options.translations) {
this.setTranslations(options.translations)
}
if (options.graphs) {
this.graphs = options.graphs
}
if (options.useLevenshteinDistance !== undefined) {
this.useLevenshteinDistance = options.useLevenshteinDistance
}
if (options.levenshteinThreshold !== undefined) {
this.levenshteinThreshold = options.levenshteinThreshold
}
if (options.l33tMaxSubstitutions !== undefined) {
this.l33tMaxSubstitutions = options.l33tMaxSubstitutions
}
if (options.maxLength !== undefined) {
this.maxLength = options.maxLength
}
if (options.timeEstimationValues !== undefined) {
checkTimeEstimationValues(options.timeEstimationValues)
this.timeEstimationValues = {
scoring: {
...options.timeEstimationValues.scoring,
},
attackTime: {
...options.timeEstimationValues.attackTime,
},
}
}
}
private setTranslations(translations: TranslationKeys) {
if (this.checkCustomTranslations(translations)) {
this.translations = translations
} else {
throw new Error('Invalid translations object fallback to keys')
}
}
private checkCustomTranslations(translations: TranslationKeys) {
let valid = true
Object.keys(translationKeys).forEach((type) => {
if (type in translations) {
const translationType = type as keyof typeof translationKeys
Object.keys(translationKeys[translationType]).forEach((key) => {
if (!(key in translations[translationType])) {
valid = false
}
const translation = (translations[translationType] as any)[key]
if (
typeof translation !== 'string' &&
typeof translation !== 'function'
) {
valid = false
}
})
} else {
valid = false
}
})
return valid
}
private setRankedDictionaries() {
const rankedDictionaries: RankedDictionaries = {}
const rankedDictionariesMaxWorkSize: Record<string, number> = {}
Object.keys(this.dictionary).forEach((name) => {
rankedDictionaries[name] = buildRankedDictionary(this.dictionary[name])
rankedDictionariesMaxWorkSize[name] =
this.getRankedDictionariesMaxWordSize(this.dictionary[name])
})
this.rankedDictionaries = rankedDictionaries
this.rankedDictionariesMaxWordSize = rankedDictionariesMaxWorkSize
}
private getRankedDictionariesMaxWordSize(list: (string | number)[]) {
const data = list.map((el) => {
if (typeof el !== 'string') {
return el.toString().length
}
return el.length
})
// do not use Math.max(...data) because it can result in max stack size error because every entry will be used as an argument
if (data.length === 0) {
return 0
}
return data.reduce((a, b) => Math.max(a, b), -Infinity)
}
private buildSanitizedRankedDictionary(list: (string | number)[]) {
const sanitizedInputs: string[] = []
list.forEach((input: string | number | boolean) => {
const inputType = typeof input
if (
inputType === 'string' ||
inputType === 'number' ||
inputType === 'boolean'
) {
sanitizedInputs.push(input.toString().toLowerCase())
}
})
return buildRankedDictionary(sanitizedInputs)
}
public getUserInputsOptions(
dictionary?: (string | number)[],
): UserInputsOptions {
let rankedDictionary: RankedDictionary = {}
let rankedDictionaryMaxWordSize = 0
if (dictionary) {
rankedDictionary = this.buildSanitizedRankedDictionary(dictionary)
rankedDictionaryMaxWordSize =
this.getRankedDictionariesMaxWordSize(dictionary)
}
return {
rankedDictionary,
rankedDictionaryMaxWordSize,
}
}
private addMatcher(name: string, matcher: Matcher) {
if (this.matchers[name]) {
console.info(`Matcher ${name} already exists`)
} else {
this.matchers[name] = matcher
}
}
}
@@ -0,0 +1 @@
{"version":3,"file":"clapperboard.js","sources":["../../../src/icons/clapperboard.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Clapperboard\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMjAuMiA2IDMgMTFsLS45LTIuNGMtLjMtMS4xLjMtMi4yIDEuMy0yLjVsMTMuNS00YzEuMS0uMyAyLjIuMyAyLjUgMS4zWiIgLz4KICA8cGF0aCBkPSJtNi4yIDUuMyAzLjEgMy45IiAvPgogIDxwYXRoIGQ9Im0xMi40IDMuNCAzLjEgNCIgLz4KICA8cGF0aCBkPSJNMyAxMWgxOHY4YTIgMiAwIDAgMS0yIDJINWEyIDIgMCAwIDEtMi0yWiIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/clapperboard\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst Clapperboard = createLucideIcon('Clapperboard', [\n [\n 'path',\n { d: 'M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3Z', key: '1tn4o7' },\n ],\n ['path', { d: 'm6.2 5.3 3.1 3.9', key: 'iuk76l' }],\n ['path', { d: 'm12.4 3.4 3.1 4', key: '6hsd6n' }],\n ['path', { d: 'M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z', key: 'ltgou9' }],\n]);\n\nexport default Clapperboard;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAe,iBAAiB,cAAgB,CAAA,CAAA,CAAA;AAAA,CACpD,CAAA,CAAA;AAAA,CAAA,CAAA,CAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACA,CAAA,CAAA,CAAA,CAAA,CAAE,CAAA,CAAG,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAA2E,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,QAAS,CAAA,CAAA;AAAA,CAChG,CAAA,CAAA,CAAA;AAAA,CAAA,CACA,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAoB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACjD,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAmB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAChD,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAA6C,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC5E,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,17 @@
//#region src/jsx/children.ts
const toArray = (children) => Array.isArray(children) ? children : [children];
const Children = {
map: (children, fn) => toArray(children).map(fn),
forEach: (children, fn) => {
toArray(children).forEach(fn);
},
count: (children) => toArray(children).length,
only: (_children) => {
const children = toArray(_children);
if (children.length !== 1) throw new Error("Children.only() expects only one child");
return children[0];
},
toArray
};
//#endregion
export { Children, toArray };
@@ -0,0 +1,607 @@
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Handle version information related to Visual Stuio."""
import errno
import glob
import os
import re
import subprocess
import sys
def JoinPath(*args):
return os.path.normpath(os.path.join(*args))
class VisualStudioVersion:
"""Information regarding a version of Visual Studio."""
def __init__(
self,
short_name,
description,
solution_version,
project_version,
flat_sln,
uses_vcxproj,
path,
sdk_based,
default_toolset=None,
compatible_sdks=None,
):
self.short_name = short_name
self.description = description
self.solution_version = solution_version
self.project_version = project_version
self.flat_sln = flat_sln
self.uses_vcxproj = uses_vcxproj
self.path = path
self.sdk_based = sdk_based
self.default_toolset = default_toolset
compatible_sdks = compatible_sdks or []
compatible_sdks.sort(key=lambda v: float(v.replace("v", "")), reverse=True)
self.compatible_sdks = compatible_sdks
def ShortName(self):
return self.short_name
def Description(self):
"""Get the full description of the version."""
return self.description
def SolutionVersion(self):
"""Get the version number of the sln files."""
return self.solution_version
def ProjectVersion(self):
"""Get the version number of the vcproj or vcxproj files."""
return self.project_version
def FlatSolution(self):
return self.flat_sln
def UsesVcxproj(self):
"""Returns true if this version uses a vcxproj file."""
return self.uses_vcxproj
def ProjectExtension(self):
"""Returns the file extension for the project."""
return (self.uses_vcxproj and ".vcxproj") or ".vcproj"
def Path(self):
"""Returns the path to Visual Studio installation."""
return self.path
def ToolPath(self, tool):
"""Returns the path to a given compiler tool."""
return os.path.normpath(os.path.join(self.path, "VC/bin", tool))
def DefaultToolset(self):
"""Returns the msbuild toolset version that will be used in the absence
of a user override."""
return self.default_toolset
def _SetupScriptInternal(self, target_arch):
"""Returns a command (with arguments) to be used to set up the
environment."""
assert target_arch in ("x86", "x64", "arm64"), "target_arch not supported"
# If WindowsSDKDir is set and SetEnv.Cmd exists then we are using the
# depot_tools build tools and should run SetEnv.Cmd to set up the
# environment. The check for WindowsSDKDir alone is not sufficient because
# this is set by running vcvarsall.bat.
sdk_dir = os.environ.get("WindowsSDKDir", "")
setup_path = JoinPath(sdk_dir, "Bin", "SetEnv.Cmd")
if self.sdk_based and sdk_dir and os.path.exists(setup_path):
return [setup_path, "/" + target_arch]
is_host_arch_x64 = (
os.environ.get("PROCESSOR_ARCHITECTURE") == "AMD64"
or os.environ.get("PROCESSOR_ARCHITEW6432") == "AMD64"
)
# For VS2017 (and newer) it's fairly easy
if self.short_name >= "2017":
script_path = JoinPath(
self.path, "VC", "Auxiliary", "Build", "vcvarsall.bat"
)
# Always use a native executable, cross-compiling if necessary.
host_arch = (
"amd64"
if is_host_arch_x64
else (
"arm64"
if os.environ.get("PROCESSOR_ARCHITECTURE") == "ARM64"
else "x86"
)
)
msvc_target_arch = {"x64": "amd64"}.get(target_arch, target_arch)
arg = host_arch
if host_arch != msvc_target_arch:
arg += "_" + msvc_target_arch
return [script_path, arg]
# We try to find the best version of the env setup batch.
vcvarsall = JoinPath(self.path, "VC", "vcvarsall.bat")
if target_arch == "x86":
if (
self.short_name >= "2013"
and self.short_name[-1] != "e"
and is_host_arch_x64
):
# VS2013 and later, non-Express have a x64-x86 cross that we want
# to prefer.
return [vcvarsall, "amd64_x86"]
else:
# Otherwise, the standard x86 compiler. We don't use VC/vcvarsall.bat
# for x86 because vcvarsall calls vcvars32, which it can only find if
# VS??COMNTOOLS is set, which isn't guaranteed.
return [JoinPath(self.path, "Common7", "Tools", "vsvars32.bat")]
elif target_arch == "x64":
arg = "x86_amd64"
# Use the 64-on-64 compiler if we're not using an express edition and
# we're running on a 64bit OS.
if self.short_name[-1] != "e" and is_host_arch_x64:
arg = "amd64"
return [vcvarsall, arg]
def SetupScript(self, target_arch):
script_data = self._SetupScriptInternal(target_arch)
script_path = script_data[0]
if not os.path.exists(script_path):
raise Exception(
"%s is missing - make sure VC++ tools are installed." % script_path
)
return script_data
def _RegistryQueryBase(sysdir, key, value):
"""Use reg.exe to read a particular key.
While ideally we might use the win32 module, we would like gyp to be
python neutral, so for instance cygwin python lacks this module.
Arguments:
sysdir: The system subdirectory to attempt to launch reg.exe from.
key: The registry key to read from.
value: The particular value to read.
Return:
stdout from reg.exe, or None for failure.
"""
# Skip if not on Windows or Python Win32 setup issue
if sys.platform not in ("win32", "cygwin"):
return None
# Setup params to pass to and attempt to launch reg.exe
cmd = [os.path.join(os.environ.get("WINDIR", ""), sysdir, "reg.exe"), "query", key]
if value:
cmd.extend(["/v", value])
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Obtain the stdout from reg.exe, reading to the end so p.returncode is valid
# Note that the error text may be in [1] in some cases
text = p.communicate()[0].decode("utf-8")
# Check return code from reg.exe; officially 0==success and 1==error
if p.returncode:
return None
return text
def _RegistryQuery(key, value=None):
r"""Use reg.exe to read a particular key through _RegistryQueryBase.
First tries to launch from %WinDir%\Sysnative to avoid WoW64 redirection. If
that fails, it falls back to System32. Sysnative is available on Vista and
up and available on Windows Server 2003 and XP through KB patch 942589. Note
that Sysnative will always fail if using 64-bit python due to it being a
virtual directory and System32 will work correctly in the first place.
KB 942589 - http://support.microsoft.com/kb/942589/en-us.
Arguments:
key: The registry key.
value: The particular registry value to read (optional).
Return:
stdout from reg.exe, or None for failure.
"""
text = None
try:
text = _RegistryQueryBase("Sysnative", key, value)
except OSError as e:
if e.errno == errno.ENOENT:
text = _RegistryQueryBase("System32", key, value)
else:
raise
return text
def _RegistryGetValueUsingWinReg(key, value):
"""Use the _winreg module to obtain the value of a registry key.
Args:
key: The registry key.
value: The particular registry value to read.
Return:
contents of the registry key's value, or None on failure. Throws
ImportError if winreg is unavailable.
"""
from winreg import HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx # noqa: PLC0415
try:
root, subkey = key.split("\\", 1)
assert root == "HKLM" # Only need HKLM for now.
with OpenKey(HKEY_LOCAL_MACHINE, subkey) as hkey:
return QueryValueEx(hkey, value)[0]
except OSError:
return None
def _RegistryGetValue(key, value):
"""Use _winreg or reg.exe to obtain the value of a registry key.
Using _winreg is preferable because it solves an issue on some corporate
environments where access to reg.exe is locked down. However, we still need
to fallback to reg.exe for the case where the _winreg module is not available
(for example in cygwin python).
Args:
key: The registry key.
value: The particular registry value to read.
Return:
contents of the registry key's value, or None on failure.
"""
try:
return _RegistryGetValueUsingWinReg(key, value)
except ImportError:
pass
# Fallback to reg.exe if we fail to import _winreg.
text = _RegistryQuery(key, value)
if not text:
return None
# Extract value.
match = re.search(r"REG_\w+\s+([^\r]+)\r\n", text)
if not match:
return None
return match.group(1)
def _CreateVersion(name, path, sdk_based=False):
"""Sets up MSVS project generation.
Setup is based off the GYP_MSVS_VERSION environment variable or whatever is
autodetected if GYP_MSVS_VERSION is not explicitly specified. If a version is
passed in that doesn't match a value in versions python will throw a error.
"""
if path:
path = os.path.normpath(path)
versions = {
"2026": VisualStudioVersion(
"2026",
"Visual Studio 2026",
solution_version="12.00",
project_version="18.0",
flat_sln=False,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based,
default_toolset="v145",
compatible_sdks=["v8.1", "v10.0"],
),
"2022": VisualStudioVersion(
"2022",
"Visual Studio 2022",
solution_version="12.00",
project_version="17.0",
flat_sln=False,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based,
default_toolset="v143",
compatible_sdks=["v8.1", "v10.0"],
),
"2019": VisualStudioVersion(
"2019",
"Visual Studio 2019",
solution_version="12.00",
project_version="16.0",
flat_sln=False,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based,
default_toolset="v142",
compatible_sdks=["v8.1", "v10.0"],
),
"2017": VisualStudioVersion(
"2017",
"Visual Studio 2017",
solution_version="12.00",
project_version="15.0",
flat_sln=False,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based,
default_toolset="v141",
compatible_sdks=["v8.1", "v10.0"],
),
"2015": VisualStudioVersion(
"2015",
"Visual Studio 2015",
solution_version="12.00",
project_version="14.0",
flat_sln=False,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based,
default_toolset="v140",
),
"2013": VisualStudioVersion(
"2013",
"Visual Studio 2013",
solution_version="13.00",
project_version="12.0",
flat_sln=False,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based,
default_toolset="v120",
),
"2013e": VisualStudioVersion(
"2013e",
"Visual Studio 2013",
solution_version="13.00",
project_version="12.0",
flat_sln=True,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based,
default_toolset="v120",
),
"2012": VisualStudioVersion(
"2012",
"Visual Studio 2012",
solution_version="12.00",
project_version="4.0",
flat_sln=False,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based,
default_toolset="v110",
),
"2012e": VisualStudioVersion(
"2012e",
"Visual Studio 2012",
solution_version="12.00",
project_version="4.0",
flat_sln=True,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based,
default_toolset="v110",
),
"2010": VisualStudioVersion(
"2010",
"Visual Studio 2010",
solution_version="11.00",
project_version="4.0",
flat_sln=False,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based,
),
"2010e": VisualStudioVersion(
"2010e",
"Visual C++ Express 2010",
solution_version="11.00",
project_version="4.0",
flat_sln=True,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based,
),
"2008": VisualStudioVersion(
"2008",
"Visual Studio 2008",
solution_version="10.00",
project_version="9.00",
flat_sln=False,
uses_vcxproj=False,
path=path,
sdk_based=sdk_based,
),
"2008e": VisualStudioVersion(
"2008e",
"Visual Studio 2008",
solution_version="10.00",
project_version="9.00",
flat_sln=True,
uses_vcxproj=False,
path=path,
sdk_based=sdk_based,
),
"2005": VisualStudioVersion(
"2005",
"Visual Studio 2005",
solution_version="9.00",
project_version="8.00",
flat_sln=False,
uses_vcxproj=False,
path=path,
sdk_based=sdk_based,
),
"2005e": VisualStudioVersion(
"2005e",
"Visual Studio 2005",
solution_version="9.00",
project_version="8.00",
flat_sln=True,
uses_vcxproj=False,
path=path,
sdk_based=sdk_based,
),
}
return versions[str(name)]
def _ConvertToCygpath(path):
"""Convert to cygwin path if we are using cygwin."""
if sys.platform == "cygwin":
p = subprocess.Popen(["cygpath", path], stdout=subprocess.PIPE)
path = p.communicate()[0].decode("utf-8").strip()
return path
def _DetectVisualStudioVersions(versions_to_check, force_express):
"""Collect the list of installed visual studio versions.
Returns:
A list of visual studio versions installed in descending order of
usage preference.
Base this on the registry and a quick check if devenv.exe exists.
Possibilities are:
2005(e) - Visual Studio 2005 (8)
2008(e) - Visual Studio 2008 (9)
2010(e) - Visual Studio 2010 (10)
2012(e) - Visual Studio 2012 (11)
2013(e) - Visual Studio 2013 (12)
2015 - Visual Studio 2015 (14)
2017 - Visual Studio 2017 (15)
2019 - Visual Studio 2019 (16)
2022 - Visual Studio 2022 (17)
Where (e) is e for express editions of MSVS and blank otherwise.
"""
version_to_year = {
"8.0": "2005",
"9.0": "2008",
"10.0": "2010",
"11.0": "2012",
"12.0": "2013",
"14.0": "2015",
"15.0": "2017",
"16.0": "2019",
"17.0": "2022",
"18.0": "2026",
}
versions = []
for version in versions_to_check:
# Old method of searching for which VS version is installed
# We don't use the 2010-encouraged-way because we also want to get the
# path to the binaries, which it doesn't offer.
keys = [
r"HKLM\Software\Microsoft\VisualStudio\%s" % version,
r"HKLM\Software\Wow6432Node\Microsoft\VisualStudio\%s" % version,
r"HKLM\Software\Microsoft\VCExpress\%s" % version,
r"HKLM\Software\Wow6432Node\Microsoft\VCExpress\%s" % version,
]
for index in range(len(keys)):
path = _RegistryGetValue(keys[index], "InstallDir")
if not path:
continue
path = _ConvertToCygpath(path)
# Check for full.
full_path = os.path.join(path, "devenv.exe")
express_path = os.path.join(path, "*express.exe")
if not force_express and os.path.exists(full_path):
# Add this one.
versions.append(
_CreateVersion(
version_to_year[version], os.path.join(path, "..", "..")
)
)
# Check for express.
elif glob.glob(express_path):
# Add this one.
versions.append(
_CreateVersion(
version_to_year[version] + "e", os.path.join(path, "..", "..")
)
)
# The old method above does not work when only SDK is installed.
keys = [
r"HKLM\Software\Microsoft\VisualStudio\SxS\VC7",
r"HKLM\Software\Wow6432Node\Microsoft\VisualStudio\SxS\VC7",
r"HKLM\Software\Microsoft\VisualStudio\SxS\VS7",
r"HKLM\Software\Wow6432Node\Microsoft\VisualStudio\SxS\VS7",
]
for index in range(len(keys)):
path = _RegistryGetValue(keys[index], version)
if not path:
continue
path = _ConvertToCygpath(path)
if version == "15.0":
if os.path.exists(path):
versions.append(_CreateVersion("2017", path))
elif version != "14.0": # There is no Express edition for 2015.
versions.append(
_CreateVersion(
version_to_year[version] + "e",
os.path.join(path, ".."),
sdk_based=True,
)
)
return versions
def SelectVisualStudioVersion(version="auto", allow_fallback=True):
"""Select which version of Visual Studio projects to generate.
Arguments:
version: Hook to allow caller to force a particular version (vs auto).
Returns:
An object representing a visual studio project format version.
"""
# In auto mode, check environment variable for override.
if version == "auto":
version = os.environ.get("GYP_MSVS_VERSION", "auto")
version_map = {
"auto": (
"18.0",
"17.0",
"16.0",
"15.0",
"14.0",
"12.0",
"10.0",
"9.0",
"8.0",
"11.0",
),
"2005": ("8.0",),
"2005e": ("8.0",),
"2008": ("9.0",),
"2008e": ("9.0",),
"2010": ("10.0",),
"2010e": ("10.0",),
"2012": ("11.0",),
"2012e": ("11.0",),
"2013": ("12.0",),
"2013e": ("12.0",),
"2015": ("14.0",),
"2017": ("15.0",),
"2019": ("16.0",),
"2022": ("17.0",),
"2026": ("18.0",),
}
if override_path := os.environ.get("GYP_MSVS_OVERRIDE_PATH"):
msvs_version = os.environ.get("GYP_MSVS_VERSION")
if not msvs_version:
raise ValueError(
"GYP_MSVS_OVERRIDE_PATH requires GYP_MSVS_VERSION to be "
"set to a particular version (e.g. 2010e)."
)
return _CreateVersion(msvs_version, override_path, sdk_based=True)
version = str(version)
versions = _DetectVisualStudioVersions(version_map[version], "e" in version)
if not versions:
if not allow_fallback:
raise ValueError("Could not locate Visual Studio installation.")
if version == "auto":
# Default to 2005 if we couldn't find anything
return _CreateVersion("2005", None)
else:
return _CreateVersion(version, None)
return versions[0]
@@ -0,0 +1 @@
{"version":3,"file":"arrow-left-from-line.js","sources":["../../../src/icons/arrow-left-from-line.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name ArrowLeftFromLine\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJtOSA2LTYgNiA2IDYiIC8+CiAgPHBhdGggZD0iTTMgMTJoMTQiIC8+CiAgPHBhdGggZD0iTTIxIDE5VjUiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/arrow-left-from-line\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst ArrowLeftFromLine = createLucideIcon('ArrowLeftFromLine', [\n ['path', { d: 'm9 6-6 6 6 6', key: '7v63n9' }],\n ['path', { d: 'M3 12h14', key: '13k4hi' }],\n ['path', { d: 'M21 19V5', key: 'b4bplr' }],\n]);\n\nexport default ArrowLeftFromLine;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAoB,iBAAiB,mBAAqB,CAAA,CAAA,CAAA;AAAA,CAAA,CAC9D,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAgB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC7C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAY,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACzC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAY,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC3C,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,11 @@
import { a as Debugger, i as DebugOptions, n as enabled, o as Formatters, r as namespaces, s as InspectOptions, t as disable } from "./core.js";
//#region src/browser.d.ts
declare function createDebug(namespace: string, options?: DebugOptions): Debugger;
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*/
declare function enable(namespaces: string): void;
//#endregion
export { DebugOptions, Debugger, Formatters, InspectOptions, createDebug, disable, enable, enabled, namespaces };
@@ -0,0 +1 @@
{"version":3,"file":"paintbrush-vertical.js","sources":["../../../src/icons/paintbrush-vertical.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name PaintbrushVertical\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMTAgMnYyIiAvPgogIDxwYXRoIGQ9Ik0xNCAydjQiIC8+CiAgPHBhdGggZD0iTTE3IDJhMSAxIDAgMCAxIDEgMXY5SDZWM2ExIDEgMCAwIDEgMS0xeiIgLz4KICA8cGF0aCBkPSJNNiAxMmExIDEgMCAwIDAtMSAxdjFhMiAyIDAgMCAwIDIgMmgyYTEgMSAwIDAgMSAxIDF2Mi45YTIgMiAwIDEgMCA0IDBWMTdhMSAxIDAgMCAxIDEtMWgyYTIgMiAwIDAgMCAyLTJ2LTFhMSAxIDAgMCAwLTEtMSIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/paintbrush-vertical\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst PaintbrushVertical = createLucideIcon('PaintbrushVertical', [\n ['path', { d: 'M10 2v2', key: '7u0qdc' }],\n ['path', { d: 'M14 2v4', key: 'qmzblu' }],\n ['path', { d: 'M17 2a1 1 0 0 1 1 1v9H6V3a1 1 0 0 1 1-1z', key: 'ycvu00' }],\n [\n 'path',\n {\n d: 'M6 12a1 1 0 0 0-1 1v1a2 2 0 0 0 2 2h2a1 1 0 0 1 1 1v2.9a2 2 0 1 0 4 0V17a1 1 0 0 1 1-1h2a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1',\n key: 'iw4wnp',\n },\n ],\n]);\n\nexport default PaintbrushVertical;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAqB,iBAAiB,oBAAsB,CAAA,CAAA,CAAA;AAAA,CAAA,CAChE,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACxC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACxC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAA4C,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CACzE,CAAA,CAAA;AAAA,CAAA,CAAA,CAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACA,CAAA,CAAA,CAAA,CAAA;AAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACH,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACP,CAAA,CAAA,CAAA,CAAA;AAAA,CACF,CAAA,CAAA;AACF,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,25 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const Truck = createLucideIcon("Truck", [
["path", { d: "M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2", key: "wrbu53" }],
["path", { d: "M15 18H9", key: "1lyqi6" }],
[
"path",
{
d: "M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",
key: "lysw3i"
}
],
["circle", { cx: "17", cy: "18", r: "2", key: "332jqn" }],
["circle", { cx: "7", cy: "18", r: "2", key: "19iecd" }]
]);
export { Truck as default };
//# sourceMappingURL=truck.js.map
@@ -0,0 +1,16 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const Briefcase = createLucideIcon("Briefcase", [
["path", { d: "M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16", key: "jecpp" }],
["rect", { width: "20", height: "14", x: "2", y: "6", rx: "2", key: "i6l2r4" }]
]);
export { Briefcase as default };
//# sourceMappingURL=briefcase.js.map
@@ -0,0 +1,22 @@
/*
@license
Rollup.js v4.60.4
Thu, 14 May 2026 17:52:21 GMT - commit d311a84b0bb4d4a6f50d19ffd2c29cca28660c88
https://github.com/rollup/rollup
Released under the MIT License.
*/
'use strict';
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
require('./native.js');
const parseAst_js = require('./shared/parseAst.js');
require('node:path');
exports.parseAst = parseAst_js.parseAst;
exports.parseAstAsync = parseAst_js.parseAstAsync;
//# sourceMappingURL=parseAst.js.map
@@ -0,0 +1 @@
{"version":3,"file":"calc-child-stagger.mjs","sources":["../../../../src/animation/utils/calc-child-stagger.ts"],"sourcesContent":["import type { DynamicOption } from \"../types\"\nimport type { VisualElement } from \"../../render/VisualElement\"\n\nexport function calcChildStagger(\n children: Set<VisualElement>,\n child: VisualElement,\n delayChildren?: number | DynamicOption<number>,\n staggerChildren: number = 0,\n staggerDirection: number = 1\n): number {\n const index = Array.from(children)\n .sort((a, b) => a.sortNodePosition(b))\n .indexOf(child)\n const numChildren = children.size\n const maxStaggerDuration = (numChildren - 1) * staggerChildren\n const delayIsFunction = typeof delayChildren === \"function\"\n\n return delayIsFunction\n ? delayChildren(index, numChildren)\n : staggerDirection === 1\n ? index * staggerChildren\n : maxStaggerDuration - index * staggerChildren\n}\n"],"names":[],"mappings":"AAGM,SAAU,gBAAgB,CAC5B,QAA4B,EAC5B,KAAoB,EACpB,aAA8C,EAC9C,eAAA,GAA0B,CAAC,EAC3B,mBAA2B,CAAC,EAAA;AAE5B,IAAA,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,QAAQ;AAC5B,SAAA,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC;SACpC,OAAO,CAAC,KAAK,CAAC;AACnB,IAAA,MAAM,WAAW,GAAG,QAAQ,CAAC,IAAI;IACjC,MAAM,kBAAkB,GAAG,CAAC,WAAW,GAAG,CAAC,IAAI,eAAe;AAC9D,IAAA,MAAM,eAAe,GAAG,OAAO,aAAa,KAAK,UAAU;AAE3D,IAAA,OAAO;AACH,UAAE,aAAa,CAAC,KAAK,EAAE,WAAW;UAChC,gBAAgB,KAAK;cACrB,KAAK,GAAG;AACV,cAAE,kBAAkB,GAAG,KAAK,GAAG,eAAe;AACtD;;;;"}
@@ -0,0 +1,47 @@
import type { NavigateOptions, ToOptions } from './link'
import type { ParsedLocation } from './location'
import type { RoutePaths } from './routeInfo'
import type { RegisteredRouter, ViewTransitionOptions } from './router'
export interface MatchLocation {
to?: string | number | null
fuzzy?: boolean
caseSensitive?: boolean
from?: string
}
export interface CommitLocationOptions {
replace?: boolean
resetScroll?: boolean
hashScrollIntoView?: boolean | ScrollIntoViewOptions
viewTransition?: boolean | ViewTransitionOptions
/**
* @deprecated All navigations use transitions under the hood now
**/
startTransition?: boolean
ignoreBlocker?: boolean
}
export type NavigateFn = <
TRouter extends RegisteredRouter,
TTo extends string | undefined,
TFrom extends RoutePaths<TRouter['routeTree']> | string = string,
TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,
TMaskTo extends string = '',
>(
opts: NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
) => Promise<void>
export type BuildLocationFn = <
TRouter extends RegisteredRouter,
TTo extends string | undefined,
TFrom extends RoutePaths<TRouter['routeTree']> | string = string,
TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,
TMaskTo extends string = '',
>(
opts: ToOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {
leaveParams?: boolean
_includeValidateSearch?: boolean
_isNavigate?: boolean
},
) => ParsedLocation
@@ -0,0 +1 @@
{"version":3,"file":"align-vertical-distribute-end.js","sources":["../../../src/icons/align-vertical-distribute-end.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name AlignVerticalDistributeEnd\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cmVjdCB3aWR0aD0iMTQiIGhlaWdodD0iNiIgeD0iNSIgeT0iMTQiIHJ4PSIyIiAvPgogIDxyZWN0IHdpZHRoPSIxMCIgaGVpZ2h0PSI2IiB4PSI3IiB5PSI0IiByeD0iMiIgLz4KICA8cGF0aCBkPSJNMiAyMGgyMCIgLz4KICA8cGF0aCBkPSJNMiAxMGgyMCIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/align-vertical-distribute-end\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst AlignVerticalDistributeEnd = createLucideIcon('AlignVerticalDistributeEnd', [\n ['rect', { width: '14', height: '6', x: '5', y: '14', rx: '2', key: 'jmoj9s' }],\n ['rect', { width: '10', height: '6', x: '7', y: '4', rx: '2', key: 'aza5on' }],\n ['path', { d: 'M2 20h20', key: 'owomy5' }],\n ['path', { d: 'M2 10h20', key: '1ir3d8' }],\n]);\n\nexport default AlignVerticalDistributeEnd;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAA6B,iBAAiB,4BAA8B,CAAA,CAAA,CAAA;AAAA,CAAA,CAChF,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAO,MAAM,CAAQ,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,CAAG,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,GAAG,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAI,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC9E,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAO,MAAM,CAAQ,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,CAAG,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,GAAG,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAI,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC7E,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAY,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACzC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAY,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC3C,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,5 @@
declare function getProto<O extends object>(object: O): object | null;
declare const x: typeof getProto | null;
export = x;
@@ -0,0 +1 @@
{"version":3,"file":"cookie.js","sources":["../../../src/icons/cookie.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Cookie\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMTIgMmExMCAxMCAwIDEgMCAxMCAxMCA0IDQgMCAwIDEtNS01IDQgNCAwIDAgMS01LTUiIC8+CiAgPHBhdGggZD0iTTguNSA4LjV2LjAxIiAvPgogIDxwYXRoIGQ9Ik0xNiAxNS41di4wMSIgLz4KICA8cGF0aCBkPSJNMTIgMTJ2LjAxIiAvPgogIDxwYXRoIGQ9Ik0xMSAxN3YuMDEiIC8+CiAgPHBhdGggZD0iTTcgMTR2LjAxIiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/cookie\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst Cookie = createLucideIcon('Cookie', [\n ['path', { d: 'M12 2a10 10 0 1 0 10 10 4 4 0 0 1-5-5 4 4 0 0 1-5-5', key: 'laymnq' }],\n ['path', { d: 'M8.5 8.5v.01', key: 'ue8clq' }],\n ['path', { d: 'M16 15.5v.01', key: '14dtrp' }],\n ['path', { d: 'M12 12v.01', key: 'u5ubse' }],\n ['path', { d: 'M11 17v.01', key: '1hyl5a' }],\n ['path', { d: 'M7 14v.01', key: 'uct60s' }],\n]);\n\nexport default Cookie;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAS,iBAAiB,QAAU,CAAA,CAAA,CAAA;AAAA,CAAA,CACxC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAuD,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACpF,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAgB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC7C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAgB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC7C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAc,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC3C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAc,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC3C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAa,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC5C,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,491 @@
---
name: router-core/ssr
description: >-
Non-streaming and streaming SSR, RouterClient/RouterServer,
renderRouterToString/renderRouterToStream, createRequestHandler,
defaultRenderHandler/defaultStreamHandler, HeadContent/Scripts
components, head route option (meta/links/styles/scripts),
ScriptOnce, automatic loader dehydration/hydration, memory
history on server, data serialization, document head management.
type: sub-skill
library: tanstack-router
library_version: '1.166.2'
requires:
- router-core
- router-core/data-loading
sources:
- TanStack/router:docs/router/guide/ssr.md
- TanStack/router:docs/router/guide/document-head-management.md
- TanStack/router:docs/router/how-to/setup-ssr.md
---
# SSR (Server-Side Rendering)
> **WARNING**: SSR APIs are experimental. They share internal implementations with TanStack Start and may change. **TanStack Start is the recommended way to do SSR in production** — use manual SSR setup only when integrating with an existing server.
> **CRITICAL**: TanStack Router is CLIENT-FIRST. Loaders run on the client by default. With SSR enabled, loaders run on BOTH client AND server. They are NOT server-only like Remix/Next.js loaders. See [router-core/data-loading](../data-loading/SKILL.md).
> **CRITICAL**: Do not generate Next.js patterns (`getServerSideProps`, App Router, server components) or Remix patterns (server-only loader exports). TanStack Router has its own SSR API.
## Concepts
There are two SSR flavors:
- **Non-streaming**: Full page rendered on server, sent as one HTML response, then hydrated on client.
- **Streaming**: Critical first paint sent immediately; remaining content streamed incrementally as it resolves.
Key behaviors:
- Memory history is used automatically on the server (no `window`).
- Loader data is automatically dehydrated on the server and hydrated on the client.
- Data serialization supports `Date`, `Error`, `FormData`, and `undefined` out of the box.
## Setup: Shared Router Factory
The router must be created identically on server and client. Export a factory function from a shared file:
```tsx
// src/router.tsx
import { createRouter as createTanstackRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
export function createRouter() {
return createTanstackRouter({ routeTree })
}
declare module '@tanstack/react-router' {
interface Register {
router: ReturnType<typeof createRouter>
}
}
```
## Non-Streaming SSR
### Server Entry (using `defaultRenderHandler`)
```tsx
// src/entry-server.tsx
import {
createRequestHandler,
defaultRenderHandler,
} from '@tanstack/react-router/ssr/server'
import { createRouter } from './router'
export async function render({ request }: { request: Request }) {
const handler = createRequestHandler({ request, createRouter })
return await handler(defaultRenderHandler)
}
```
### Server Entry (using `renderRouterToString` for custom wrappers)
```tsx
// src/entry-server.tsx
import {
createRequestHandler,
renderRouterToString,
RouterServer,
} from '@tanstack/react-router/ssr/server'
import { createRouter } from './router'
export function render({ request }: { request: Request }) {
const handler = createRequestHandler({ request, createRouter })
return handler(({ responseHeaders, router }) =>
renderRouterToString({
responseHeaders,
router,
children: <RouterServer router={router} />,
}),
)
}
```
### Client Entry
```tsx
// src/entry-client.tsx
import { hydrateRoot } from 'react-dom/client'
import { RouterClient } from '@tanstack/react-router/ssr/client'
import { createRouter } from './router'
const router = createRouter()
hydrateRoot(document, <RouterClient router={router} />)
```
## Streaming SSR
### Server Entry (using `defaultStreamHandler`)
```tsx
// src/entry-server.tsx
import {
createRequestHandler,
defaultStreamHandler,
} from '@tanstack/react-router/ssr/server'
import { createRouter } from './router'
export async function render({ request }: { request: Request }) {
const handler = createRequestHandler({ request, createRouter })
return await handler(defaultStreamHandler)
}
```
### Server Entry (using `renderRouterToStream` for custom wrappers)
```tsx
// src/entry-server.tsx
import {
createRequestHandler,
renderRouterToStream,
RouterServer,
} from '@tanstack/react-router/ssr/server'
import { createRouter } from './router'
export function render({ request }: { request: Request }) {
const handler = createRequestHandler({ request, createRouter })
return handler(({ request, responseHeaders, router }) =>
renderRouterToStream({
request,
responseHeaders,
router,
children: <RouterServer router={router} />,
}),
)
}
```
Streaming is automatic — deferred data (unawaited promises from loaders) and streamed markup just work when using `defaultStreamHandler` or `renderRouterToStream`.
## Document Head Management
Use the `head` route option to manage `<title>`, `<meta>`, `<link>`, and `<style>` tags. Render `<HeadContent />` in `<head>` and `<Scripts />` in `<body>`.
### Root Route with Head
```tsx
// src/routes/__root.tsx
import {
createRootRoute,
HeadContent,
Outlet,
Scripts,
} from '@tanstack/react-router'
export const Route = createRootRoute({
head: () => ({
meta: [
{ charSet: 'UTF-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1.0' },
{ title: 'My App' },
],
links: [{ rel: 'icon', href: '/favicon.ico' }],
}),
component: RootComponent,
})
function RootComponent() {
return (
<html lang="en">
<head>
<HeadContent />
</head>
<body>
<Outlet />
<Scripts />
</body>
</html>
)
}
```
### Per-Route Head (Nested Deduplication)
Child route `title` and `meta` tags override parent tags with the same `name`/`property`:
```tsx
// src/routes/posts/$postId.tsx
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/posts/$postId')({
loader: async ({ params }) => {
const post = await fetchPost(params.postId)
return { post }
},
head: ({ loaderData }) => ({
meta: [
{ title: loaderData.post.title },
{ name: 'description', content: loaderData.post.excerpt },
],
}),
component: PostPage,
})
function PostPage() {
const { post } = Route.useLoaderData()
return <article>{post.content}</article>
}
```
### SPA Head (No Full HTML Control)
For SPAs without server-rendered HTML, render `<HeadContent />` at the top of the component tree:
```tsx
import { createRootRoute, HeadContent, Outlet } from '@tanstack/react-router'
const rootRoute = createRootRoute({
head: () => ({
meta: [{ title: 'My SPA' }],
}),
component: () => (
<>
<HeadContent />
<Outlet />
</>
),
})
```
## Body Scripts
Use `scripts` (separate from `head.scripts`) to inject scripts into `<body>` before the app entry point:
```tsx
export const Route = createRootRoute({
scripts: () => [{ children: 'console.log("runs before hydration")' }],
})
```
The `<Scripts />` component renders these. Place it at the end of `<body>`.
## ScriptOnce for Pre-Hydration Scripts
`ScriptOnce` renders a `<script>` during SSR that executes immediately and self-removes. On client navigation, it does nothing (no duplicate execution).
```tsx
import { ScriptOnce } from '@tanstack/react-router'
const themeScript = `(function() {
try {
const theme = localStorage.getItem('theme') || 'auto';
const resolved = theme === 'auto'
? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
: theme;
document.documentElement.classList.add(resolved);
} catch (e) {}
})();`
function ThemeProvider({ children }: { children: React.ReactNode }) {
return (
<>
<ScriptOnce children={themeScript} />
{children}
</>
)
}
```
If the script modifies the DOM (e.g., adds a class to `<html>`), use `suppressHydrationWarning` on the element:
```tsx
<html lang="en" suppressHydrationWarning>
```
## Express Integration Example
`createRequestHandler` expects a Web API `Request` and returns a Web API `Response`. For Express, convert between formats:
```tsx
// src/entry-server.tsx
import { pipeline } from 'node:stream/promises'
import {
RouterServer,
createRequestHandler,
renderRouterToString,
} from '@tanstack/react-router/ssr/server'
import { createRouter } from './router'
import type express from 'express'
export async function render({
req,
res,
}: {
req: express.Request
res: express.Response
}) {
const protocol = req.get('x-forwarded-proto') ?? req.protocol
const host = req.get('x-forwarded-host') ?? req.get('host')
const url = new URL(req.originalUrl || req.url, `${protocol}://${host}`).href
const request = new Request(url, {
method: req.method,
headers: (() => {
const headers = new Headers()
for (const [key, value] of Object.entries(req.headers)) {
headers.set(key, value as any)
}
return headers
})(),
})
const handler = createRequestHandler({ request, createRouter })
const response = await handler(({ responseHeaders, router }) =>
renderRouterToString({
responseHeaders,
router,
children: <RouterServer router={router} />,
}),
)
res.status(response.status)
response.headers.forEach((value, name) => {
res.setHeader(name, value)
})
return pipeline(response.body as any, res)
}
```
## Common Mistakes
### 1. HIGH: Using browser APIs in loaders without environment check
Loaders run on BOTH client and server with SSR. Browser-only APIs (`window`, `document`, `localStorage`) throw on the server.
```tsx
// WRONG — crashes on server
loader: async () => {
const token = localStorage.getItem('token')
return fetchData(token)
}
// CORRECT — guard with environment check
loader: async () => {
const token =
typeof window !== 'undefined' ? localStorage.getItem('token') : null
return fetchData(token)
}
```
### 2. MEDIUM: Using hash fragments for server-rendered content
Hash fragments (`#section`) are never sent to the server. Conditional rendering based on hash causes hydration mismatches.
```tsx
// WRONG — server has no hash, client does → mismatch
component: () => {
const hash = window.location.hash
return hash === '#admin' ? <AdminPanel /> : <UserPanel />
}
// CORRECT — use search params for server-visible state
validateSearch: z.object({ view: fallback(z.enum(['admin', 'user']), 'user') }),
component: () => {
const { view } = Route.useSearch()
return view === 'admin' ? <AdminPanel /> : <UserPanel />
}
```
### 3. CRITICAL: Generating Next.js, Remix, or React Router DOM patterns
TanStack Router does NOT use `getServerSideProps`, `getStaticProps`, App Router `page.tsx`, Remix-style server-only `loader` exports, or anything from `react-router-dom`.
#### Wrong file structures
```text
WRONG (Next.js Pages Router):
src/pages/index.tsx
src/pages/_app.tsx
src/pages/posts/[id].tsx
WRONG (Next.js App Router):
app/layout.tsx
app/page.tsx
app/posts/[id]/page.tsx
WRONG (Next.js custom App):
_app/index.tsx
pages/_app.tsx, pages/_document.tsx
CORRECT (TanStack Router file-based routing):
src/routes/__root.tsx
src/routes/index.tsx
src/routes/posts/$postId.tsx
```
#### Wrong imports
```tsx
// WRONG — react-router-dom is a different library
import {
Link,
useNavigate,
BrowserRouter,
Route,
Routes,
} from 'react-router-dom'
// WRONG — Next.js Link/router
import Link from 'next/link'
import { useRouter } from 'next/router' // Pages Router
import { useRouter } from 'next/navigation' // App Router
// CORRECT — everything routing-related lives in @tanstack/react-router
import {
Link,
useNavigate,
useRouter,
useLocation,
redirect,
} from '@tanstack/react-router'
```
#### Wrong loader/data-fetching patterns
```tsx
// WRONG — Next.js Pages Router
export async function getServerSideProps() {
return { props: { data: await fetchData() } }
}
// WRONG — Remix
export async function loader({ request }: LoaderFunctionArgs) {
return json({ data: await fetchData() })
}
// CORRECT — TanStack Router
export const Route = createFileRoute('/data')({
loader: async () => {
const data = await fetchData()
return { data }
},
component: DataPage,
})
function DataPage() {
const { data } = Route.useLoaderData()
return <div>{data}</div>
}
```
If you see `src/pages/`, `app/layout.tsx`, `react-router-dom`, or any of the above in agent output, the agent is generating for the wrong framework. The build will either fail or produce duplicate `/` routes that conflict at runtime.
## Tension: Client-First Loaders vs SSR
TanStack Router loaders are client-first by design. When SSR is enabled, they run in both environments. This means:
- Browser APIs work by default (client-only) but break under SSR
- Database access does NOT belong in loaders (unlike Remix/Next) — use API routes
- For server-only data logic with SSR, use TanStack Start's server functions
See [router-core/data-loading](../data-loading/SKILL.md) for loader fundamentals.
## Cross-References
- [router-core/data-loading](../data-loading/SKILL.md) — SSR changes where loaders execute
- [compositions/router-query](../../../../react-router/skills/compositions/router-query/SKILL.md) — SSR dehydration/hydration with TanStack Query
@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseMapDef = void 0;
const parseDef_js_1 = require("../parseDef.js");
const record_js_1 = require("./record.js");
const any_js_1 = require("./any.js");
function parseMapDef(def, refs) {
if (refs.mapStrategy === "record") {
return (0, record_js_1.parseRecordDef)(def, refs);
}
const keys = (0, parseDef_js_1.parseDef)(def.keyType._def, {
...refs,
currentPath: [...refs.currentPath, "items", "items", "0"],
}) || (0, any_js_1.parseAnyDef)(refs);
const values = (0, parseDef_js_1.parseDef)(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "items", "items", "1"],
}) || (0, any_js_1.parseAnyDef)(refs);
return {
type: "array",
maxItems: 125,
items: {
type: "array",
items: [keys, values],
minItems: 2,
maxItems: 2,
},
};
}
exports.parseMapDef = parseMapDef;
@@ -0,0 +1,117 @@
/**
* Internal helpers for u64.
* BigUint64Array is too slow as per 2026, so we implement it using
* Uint32Array.
* @privateRemarks TODO: re-check {@link https://issues.chromium.org/issues/42212588}
* @module
*/
import type { TRet } from './utils.ts';
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high
// }` to match little-endian word order rather than the property names.
function fromBig(
n: bigint,
le = false
): {
h: number;
l: number;
} {
if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array
// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.
function split(lst: bigint[], le = false): TRet<Uint32Array[]> {
const len = lst.length;
let Ah = new Uint32Array(len);
let Al = new Uint32Array(len);
for (let i = 0; i < len; i++) {
const { h, l } = fromBig(lst[i], le);
[Ah[i], Al[i]] = [h, l];
}
return [Ah, Al] as TRet<Uint32Array[]>;
}
// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS
// bitwise results back to uint32 first, and little-endian callers must swap.
const toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.
const shrSH = (h: number, _l: number, s: number): number => h >>> s;
// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.
const shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);
// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.
const rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));
// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.
const rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);
// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
const rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));
// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
const rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));
// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.
const rotr32H = (_h: number, l: number): number => l;
// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.
const rotr32L = (h: number, _l: number): number => h;
// High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.
const rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));
// Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.
const rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));
// High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
const rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));
// Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
const rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));
// Add two split 64-bit words and return the split `{ h, l }` sum.
// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out
// of the low sum and instead use division.
function add(
Ah: number,
Al: number,
Bh: number,
Bl: number
): {
h: number;
l: number;
} {
const l = (Al >>> 0) + (Bl >>> 0);
return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.
const add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.
const add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>
(Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.
const add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>
(Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.
const add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>
(Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.
const add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>
(Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.
const add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>
(Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
// prettier-ignore
export {
add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig
};
// Canonical grouped namespace for callers that prefer one object.
// Named exports stay for direct imports.
// prettier-ignore
const u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {
fromBig, split, toBig,
shrSH, shrSL,
rotrSH, rotrSL, rotrBH, rotrBL,
rotr32H, rotr32L,
rotlSH, rotlSL, rotlBH, rotlBL,
add, add3L, add3H, add4L, add4H, add5H, add5L,
};
// Default export mirrors named `u64` for compatibility with object-style imports.
export default u64;
@@ -0,0 +1,18 @@
import { HtmlEscapedString } from "../utils/html.js";
import { PropsWithChildren } from "./types.js";
import { Child, FC } from "./base.js";
//#region src/jsx/components.d.ts
export declare const childrenToString: (children: Child[]) => Promise<HtmlEscapedString[]>;
export type ErrorHandler = (error: Error) => void;
export type FallbackRender = (error: Error) => Child;
/**
* @experimental
* `ErrorBoundary` is an experimental feature.
* The API might be changed.
*/
export declare const ErrorBoundary: FC<PropsWithChildren<{
fallback?: Child;
fallbackRender?: FallbackRender;
onError?: ErrorHandler;
}>>;
//#endregion
@@ -0,0 +1,93 @@
# media-typer
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][npm-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
Simple RFC 6838 media type parser.
This module will parse a given media type into it's component parts, like type,
subtype, and suffix. A formatter is also provided to put them back together and
the two can be combined to normalize media types into a canonical form.
If you are looking to parse the string that represents a media type and it's
parameters in HTTP (for example, the `Content-Type` header), use the
[content-type module](https://www.npmjs.com/package/content-type).
## Installation
This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
```sh
$ npm install media-typer
```
## API
<!-- eslint-disable no-unused-vars -->
```js
var typer = require('media-typer')
```
### typer.parse(string)
<!-- eslint-disable no-undef, no-unused-vars -->
```js
var obj = typer.parse('image/svg+xml')
```
Parse a media type string. This will return an object with the following
properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`):
- `type`: The type of the media type (always lower case). Example: `'image'`
- `subtype`: The subtype of the media type (always lower case). Example: `'svg'`
- `suffix`: The suffix of the media type (always lower case). Example: `'xml'`
If the given type string is invalid, then a `TypeError` is thrown.
### typer.format(obj)
<!-- eslint-disable no-undef, no-unused-vars -->
```js
var obj = typer.format({ type: 'image', subtype: 'svg', suffix: 'xml' })
```
Format an object into a media type string. This will return a string of the
mime type for the given object. For the properties of the object, see the
documentation for `typer.parse(string)`.
If any of the given object values are invalid, then a `TypeError` is thrown.
### typer.test(string)
<!-- eslint-disable no-undef, no-unused-vars -->
```js
var valid = typer.test('image/svg+xml')
```
Validate a media type string. This will return `true` is the string is a well-
formatted media type, or `false` otherwise.
## License
[MIT](LICENSE)
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/media-typer/master
[coveralls-url]: https://coveralls.io/r/jshttp/media-typer?branch=master
[node-version-image]: https://badgen.net/npm/node/media-typer
[node-version-url]: https://nodejs.org/en/download
[npm-downloads-image]: https://badgen.net/npm/dm/media-typer
[npm-url]: https://npmjs.org/package/media-typer
[npm-version-image]: https://badgen.net/npm/v/media-typer
[travis-image]: https://badgen.net/travis/jshttp/media-typer/master
[travis-url]: https://travis-ci.org/jshttp/media-typer
@@ -0,0 +1,9 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
export { default } from './square-check.js';
//# sourceMappingURL=check-square-2.js.map
@@ -0,0 +1,421 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OperatorPrecedence = void 0;
exports.getOperatorPrecedenceForNode = getOperatorPrecedenceForNode;
exports.getOperatorPrecedence = getOperatorPrecedence;
exports.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence;
const utils_1 = require("@typescript-eslint/utils");
const typescript_1 = require("typescript");
var OperatorPrecedence;
(function (OperatorPrecedence) {
// Expression:
// AssignmentExpression
// Expression `,` AssignmentExpression
OperatorPrecedence[OperatorPrecedence["Comma"] = 0] = "Comma";
// NOTE: `Spread` is higher than `Comma` due to how it is parsed in |ElementList|
// SpreadElement:
// `...` AssignmentExpression
OperatorPrecedence[OperatorPrecedence["Spread"] = 1] = "Spread";
// AssignmentExpression:
// ConditionalExpression
// YieldExpression
// ArrowFunction
// AsyncArrowFunction
// LeftHandSideExpression `=` AssignmentExpression
// LeftHandSideExpression AssignmentOperator AssignmentExpression
//
// NOTE: AssignmentExpression is broken down into several precedences due to the requirements
// of the parenthesize rules.
// AssignmentExpression: YieldExpression
// YieldExpression:
// `yield`
// `yield` AssignmentExpression
// `yield` `*` AssignmentExpression
OperatorPrecedence[OperatorPrecedence["Yield"] = 2] = "Yield";
// AssignmentExpression: LeftHandSideExpression `=` AssignmentExpression
// AssignmentExpression: LeftHandSideExpression AssignmentOperator AssignmentExpression
// AssignmentOperator: one of
// `*=` `/=` `%=` `+=` `-=` `<<=` `>>=` `>>>=` `&=` `^=` `|=` `**=`
OperatorPrecedence[OperatorPrecedence["Assignment"] = 3] = "Assignment";
// NOTE: `Conditional` is considered higher than `Assignment` here, but in reality they have
// the same precedence.
// AssignmentExpression: ConditionalExpression
// ConditionalExpression:
// ShortCircuitExpression
// ShortCircuitExpression `?` AssignmentExpression `:` AssignmentExpression
// ShortCircuitExpression:
// LogicalORExpression
// CoalesceExpression
OperatorPrecedence[OperatorPrecedence["Conditional"] = 4] = "Conditional";
// CoalesceExpression:
// CoalesceExpressionHead `??` BitwiseORExpression
// CoalesceExpressionHead:
// CoalesceExpression
// BitwiseORExpression
OperatorPrecedence[OperatorPrecedence["Coalesce"] = 4] = "Coalesce";
// LogicalORExpression:
// LogicalANDExpression
// LogicalORExpression `||` LogicalANDExpression
OperatorPrecedence[OperatorPrecedence["LogicalOR"] = 5] = "LogicalOR";
// LogicalANDExpression:
// BitwiseORExpression
// LogicalANDExpression `&&` BitwiseORExpression
OperatorPrecedence[OperatorPrecedence["LogicalAND"] = 6] = "LogicalAND";
// BitwiseORExpression:
// BitwiseXORExpression
// BitwiseORExpression `^` BitwiseXORExpression
OperatorPrecedence[OperatorPrecedence["BitwiseOR"] = 7] = "BitwiseOR";
// BitwiseXORExpression:
// BitwiseANDExpression
// BitwiseXORExpression `^` BitwiseANDExpression
OperatorPrecedence[OperatorPrecedence["BitwiseXOR"] = 8] = "BitwiseXOR";
// BitwiseANDExpression:
// EqualityExpression
// BitwiseANDExpression `^` EqualityExpression
OperatorPrecedence[OperatorPrecedence["BitwiseAND"] = 9] = "BitwiseAND";
// EqualityExpression:
// RelationalExpression
// EqualityExpression `==` RelationalExpression
// EqualityExpression `!=` RelationalExpression
// EqualityExpression `===` RelationalExpression
// EqualityExpression `!==` RelationalExpression
OperatorPrecedence[OperatorPrecedence["Equality"] = 10] = "Equality";
// RelationalExpression:
// ShiftExpression
// RelationalExpression `<` ShiftExpression
// RelationalExpression `>` ShiftExpression
// RelationalExpression `<=` ShiftExpression
// RelationalExpression `>=` ShiftExpression
// RelationalExpression `instanceof` ShiftExpression
// RelationalExpression `in` ShiftExpression
// [+TypeScript] RelationalExpression `as` Type
OperatorPrecedence[OperatorPrecedence["Relational"] = 11] = "Relational";
// ShiftExpression:
// AdditiveExpression
// ShiftExpression `<<` AdditiveExpression
// ShiftExpression `>>` AdditiveExpression
// ShiftExpression `>>>` AdditiveExpression
OperatorPrecedence[OperatorPrecedence["Shift"] = 12] = "Shift";
// AdditiveExpression:
// MultiplicativeExpression
// AdditiveExpression `+` MultiplicativeExpression
// AdditiveExpression `-` MultiplicativeExpression
OperatorPrecedence[OperatorPrecedence["Additive"] = 13] = "Additive";
// MultiplicativeExpression:
// ExponentiationExpression
// MultiplicativeExpression MultiplicativeOperator ExponentiationExpression
// MultiplicativeOperator: one of `*`, `/`, `%`
OperatorPrecedence[OperatorPrecedence["Multiplicative"] = 14] = "Multiplicative";
// ExponentiationExpression:
// UnaryExpression
// UpdateExpression `**` ExponentiationExpression
OperatorPrecedence[OperatorPrecedence["Exponentiation"] = 15] = "Exponentiation";
// UnaryExpression:
// UpdateExpression
// `delete` UnaryExpression
// `void` UnaryExpression
// `typeof` UnaryExpression
// `+` UnaryExpression
// `-` UnaryExpression
// `~` UnaryExpression
// `!` UnaryExpression
// AwaitExpression
// UpdateExpression: // TODO: Do we need to investigate the precedence here?
// `++` UnaryExpression
// `--` UnaryExpression
OperatorPrecedence[OperatorPrecedence["Unary"] = 16] = "Unary";
// UpdateExpression:
// LeftHandSideExpression
// LeftHandSideExpression `++`
// LeftHandSideExpression `--`
OperatorPrecedence[OperatorPrecedence["Update"] = 17] = "Update";
// LeftHandSideExpression:
// NewExpression
// CallExpression
// NewExpression:
// MemberExpression
// `new` NewExpression
OperatorPrecedence[OperatorPrecedence["LeftHandSide"] = 18] = "LeftHandSide";
// CallExpression:
// CoverCallExpressionAndAsyncArrowHead
// SuperCall
// ImportCall
// CallExpression Arguments
// CallExpression `[` Expression `]`
// CallExpression `.` IdentifierName
// CallExpression TemplateLiteral
// MemberExpression:
// PrimaryExpression
// MemberExpression `[` Expression `]`
// MemberExpression `.` IdentifierName
// MemberExpression TemplateLiteral
// SuperProperty
// MetaProperty
// `new` MemberExpression Arguments
OperatorPrecedence[OperatorPrecedence["Member"] = 19] = "Member";
// TODO: JSXElement?
// PrimaryExpression:
// `this`
// IdentifierReference
// Literal
// ArrayLiteral
// ObjectLiteral
// FunctionExpression
// ClassExpression
// GeneratorExpression
// AsyncFunctionExpression
// AsyncGeneratorExpression
// RegularExpressionLiteral
// TemplateLiteral
// CoverParenthesizedExpressionAndArrowParameterList
OperatorPrecedence[OperatorPrecedence["Primary"] = 20] = "Primary";
OperatorPrecedence[OperatorPrecedence["Highest"] = 20] = "Highest";
OperatorPrecedence[OperatorPrecedence["Lowest"] = 0] = "Lowest";
// -1 is lower than all other precedences. Returning it will cause binary expression
// parsing to stop.
OperatorPrecedence[OperatorPrecedence["Invalid"] = -1] = "Invalid";
})(OperatorPrecedence || (exports.OperatorPrecedence = OperatorPrecedence = {}));
/**
* Note that this does not take into account parenthesization. You should check
* for parenthesization separately if it's relevant to your usage.
*/
function getOperatorPrecedenceForNode(node) {
switch (node.type) {
case utils_1.AST_NODE_TYPES.SpreadElement:
case utils_1.AST_NODE_TYPES.RestElement:
return OperatorPrecedence.Spread;
case utils_1.AST_NODE_TYPES.YieldExpression:
case utils_1.AST_NODE_TYPES.ArrowFunctionExpression:
return OperatorPrecedence.Yield;
case utils_1.AST_NODE_TYPES.ConditionalExpression:
return OperatorPrecedence.Conditional;
case utils_1.AST_NODE_TYPES.SequenceExpression:
return OperatorPrecedence.Comma;
case utils_1.AST_NODE_TYPES.AssignmentExpression:
case utils_1.AST_NODE_TYPES.BinaryExpression:
case utils_1.AST_NODE_TYPES.LogicalExpression:
switch (node.operator) {
case '==':
case '+=':
case '-=':
case '**=':
case '*=':
case '/=':
case '%=':
case '<<=':
case '>>=':
case '>>>=':
case '&=':
case '^=':
case '|=':
case '||=':
case '&&=':
case '??=':
return OperatorPrecedence.Assignment;
default:
return getBinaryOperatorPrecedence(node.operator);
}
case utils_1.AST_NODE_TYPES.TSTypeAssertion:
case utils_1.AST_NODE_TYPES.TSNonNullExpression:
case utils_1.AST_NODE_TYPES.UnaryExpression:
case utils_1.AST_NODE_TYPES.AwaitExpression:
return OperatorPrecedence.Unary;
case utils_1.AST_NODE_TYPES.UpdateExpression:
// TODO: Should prefix `++` and `--` be moved to the `Update` precedence?
if (node.prefix) {
return OperatorPrecedence.Unary;
}
return OperatorPrecedence.Update;
case utils_1.AST_NODE_TYPES.ChainExpression:
return getOperatorPrecedenceForNode(node.expression);
case utils_1.AST_NODE_TYPES.CallExpression:
return OperatorPrecedence.LeftHandSide;
case utils_1.AST_NODE_TYPES.NewExpression:
return node.arguments.length > 0
? OperatorPrecedence.Member
: OperatorPrecedence.LeftHandSide;
case utils_1.AST_NODE_TYPES.TaggedTemplateExpression:
case utils_1.AST_NODE_TYPES.MemberExpression:
case utils_1.AST_NODE_TYPES.MetaProperty:
return OperatorPrecedence.Member;
case utils_1.AST_NODE_TYPES.TSAsExpression:
return OperatorPrecedence.Relational;
case utils_1.AST_NODE_TYPES.ThisExpression:
case utils_1.AST_NODE_TYPES.Super:
case utils_1.AST_NODE_TYPES.Identifier:
case utils_1.AST_NODE_TYPES.PrivateIdentifier:
case utils_1.AST_NODE_TYPES.Literal:
case utils_1.AST_NODE_TYPES.ArrayExpression:
case utils_1.AST_NODE_TYPES.ObjectExpression:
case utils_1.AST_NODE_TYPES.FunctionExpression:
case utils_1.AST_NODE_TYPES.ClassExpression:
case utils_1.AST_NODE_TYPES.TemplateLiteral:
case utils_1.AST_NODE_TYPES.JSXElement:
case utils_1.AST_NODE_TYPES.JSXFragment:
// we don't have nodes for these cases
// case SyntaxKind.ParenthesizedExpression:
// case SyntaxKind.OmittedExpression:
return OperatorPrecedence.Primary;
default:
return OperatorPrecedence.Invalid;
}
}
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
// A list of comma-separated expressions. This node is only created by transformations.
case typescript_1.SyntaxKind.CommaListExpression:
return OperatorPrecedence.Comma;
case typescript_1.SyntaxKind.SpreadElement:
return OperatorPrecedence.Spread;
case typescript_1.SyntaxKind.YieldExpression:
return OperatorPrecedence.Yield;
case typescript_1.SyntaxKind.ConditionalExpression:
return OperatorPrecedence.Conditional;
case typescript_1.SyntaxKind.BinaryExpression:
switch (operatorKind) {
case typescript_1.SyntaxKind.AmpersandAmpersandEqualsToken:
case typescript_1.SyntaxKind.AmpersandEqualsToken:
case typescript_1.SyntaxKind.AsteriskAsteriskEqualsToken:
case typescript_1.SyntaxKind.AsteriskEqualsToken:
case typescript_1.SyntaxKind.BarBarEqualsToken:
case typescript_1.SyntaxKind.BarEqualsToken:
case typescript_1.SyntaxKind.CaretEqualsToken:
case typescript_1.SyntaxKind.EqualsToken:
case typescript_1.SyntaxKind.GreaterThanGreaterThanEqualsToken:
case typescript_1.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken:
case typescript_1.SyntaxKind.LessThanLessThanEqualsToken:
case typescript_1.SyntaxKind.MinusEqualsToken:
case typescript_1.SyntaxKind.PercentEqualsToken:
case typescript_1.SyntaxKind.PlusEqualsToken:
case typescript_1.SyntaxKind.QuestionQuestionEqualsToken:
case typescript_1.SyntaxKind.SlashEqualsToken:
return OperatorPrecedence.Assignment;
case typescript_1.SyntaxKind.CommaToken:
return OperatorPrecedence.Comma;
default:
return getBinaryOperatorPrecedence(operatorKind);
}
// TODO: Should prefix `++` and `--` be moved to the `Update` precedence?
case typescript_1.SyntaxKind.TypeAssertionExpression:
case typescript_1.SyntaxKind.NonNullExpression:
case typescript_1.SyntaxKind.PrefixUnaryExpression:
case typescript_1.SyntaxKind.TypeOfExpression:
case typescript_1.SyntaxKind.VoidExpression:
case typescript_1.SyntaxKind.DeleteExpression:
case typescript_1.SyntaxKind.AwaitExpression:
return OperatorPrecedence.Unary;
case typescript_1.SyntaxKind.PostfixUnaryExpression:
return OperatorPrecedence.Update;
case typescript_1.SyntaxKind.CallExpression:
return OperatorPrecedence.LeftHandSide;
case typescript_1.SyntaxKind.NewExpression:
return hasArguments
? OperatorPrecedence.Member
: OperatorPrecedence.LeftHandSide;
case typescript_1.SyntaxKind.TaggedTemplateExpression:
case typescript_1.SyntaxKind.PropertyAccessExpression:
case typescript_1.SyntaxKind.ElementAccessExpression:
case typescript_1.SyntaxKind.MetaProperty:
return OperatorPrecedence.Member;
case typescript_1.SyntaxKind.AsExpression:
case typescript_1.SyntaxKind.SatisfiesExpression:
return OperatorPrecedence.Relational;
case typescript_1.SyntaxKind.ThisKeyword:
case typescript_1.SyntaxKind.SuperKeyword:
case typescript_1.SyntaxKind.Identifier:
case typescript_1.SyntaxKind.PrivateIdentifier:
case typescript_1.SyntaxKind.NullKeyword:
case typescript_1.SyntaxKind.TrueKeyword:
case typescript_1.SyntaxKind.FalseKeyword:
case typescript_1.SyntaxKind.NumericLiteral:
case typescript_1.SyntaxKind.BigIntLiteral:
case typescript_1.SyntaxKind.StringLiteral:
case typescript_1.SyntaxKind.ArrayLiteralExpression:
case typescript_1.SyntaxKind.ObjectLiteralExpression:
case typescript_1.SyntaxKind.FunctionExpression:
case typescript_1.SyntaxKind.ArrowFunction:
case typescript_1.SyntaxKind.ClassExpression:
case typescript_1.SyntaxKind.RegularExpressionLiteral:
case typescript_1.SyntaxKind.NoSubstitutionTemplateLiteral:
case typescript_1.SyntaxKind.TemplateExpression:
case typescript_1.SyntaxKind.ParenthesizedExpression:
case typescript_1.SyntaxKind.OmittedExpression:
case typescript_1.SyntaxKind.JsxElement:
case typescript_1.SyntaxKind.JsxSelfClosingElement:
case typescript_1.SyntaxKind.JsxFragment:
return OperatorPrecedence.Primary;
default:
return OperatorPrecedence.Invalid;
}
}
function getBinaryOperatorPrecedence(kind) {
switch (kind) {
case '-':
case '+':
case typescript_1.SyntaxKind.MinusToken:
case typescript_1.SyntaxKind.PlusToken:
return OperatorPrecedence.Additive;
case '!=':
case '!==':
case '==':
case '===':
case typescript_1.SyntaxKind.EqualsEqualsEqualsToken:
case typescript_1.SyntaxKind.EqualsEqualsToken:
case typescript_1.SyntaxKind.ExclamationEqualsEqualsToken:
case typescript_1.SyntaxKind.ExclamationEqualsToken:
return OperatorPrecedence.Equality;
case '??':
case typescript_1.SyntaxKind.QuestionQuestionToken:
return OperatorPrecedence.Coalesce;
case '*':
case '/':
case '%':
case typescript_1.SyntaxKind.AsteriskToken:
case typescript_1.SyntaxKind.PercentToken:
case typescript_1.SyntaxKind.SlashToken:
return OperatorPrecedence.Multiplicative;
case '**':
case typescript_1.SyntaxKind.AsteriskAsteriskToken:
return OperatorPrecedence.Exponentiation;
case '&':
case typescript_1.SyntaxKind.AmpersandToken:
return OperatorPrecedence.BitwiseAND;
case '&&':
case typescript_1.SyntaxKind.AmpersandAmpersandToken:
return OperatorPrecedence.LogicalAND;
case '^':
case typescript_1.SyntaxKind.CaretToken:
return OperatorPrecedence.BitwiseXOR;
case '<':
case '<=':
case '>':
case '>=':
case 'in':
case 'instanceof':
case typescript_1.SyntaxKind.AsKeyword:
case typescript_1.SyntaxKind.GreaterThanEqualsToken:
case typescript_1.SyntaxKind.GreaterThanToken:
case typescript_1.SyntaxKind.InKeyword:
case typescript_1.SyntaxKind.InstanceOfKeyword:
case typescript_1.SyntaxKind.LessThanEqualsToken:
case typescript_1.SyntaxKind.LessThanToken:
// case 'as': -- we don't have a token for this
return OperatorPrecedence.Relational;
case '<<':
case '>>':
case '>>>':
case typescript_1.SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
case typescript_1.SyntaxKind.GreaterThanGreaterThanToken:
case typescript_1.SyntaxKind.LessThanLessThanToken:
return OperatorPrecedence.Shift;
case '|':
case typescript_1.SyntaxKind.BarToken:
return OperatorPrecedence.BitwiseOR;
case '||':
case typescript_1.SyntaxKind.BarBarToken:
return OperatorPrecedence.LogicalOR;
}
// -1 is lower than all other precedences. Returning it will cause binary expression
// parsing to stop.
return -1;
}
@@ -0,0 +1,5 @@
/**
* Common parser code for TypeScript and Flow.
*/
export declare function typedParseConditional(noIn: boolean): void;
export declare function typedParseParenItem(): void;
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"_E"},B:{"2":"_I","2052":"_K"},C:{"2":"_2C","1028":"_CF","1060":"_3Q"},D:{"2":"_iJ","226":"_wK _ME _5E","2052":"_qF"},E:{"2":"_5C","772":"_KF","804":"_BP","1316":"PD"},F:{"2":"_RK","226":"_aQ 0B","2052":"_MF"},G:{"2":"_EB","292":"_9B"},H:{"2":"1D"},I:{"1":"I","2":"_G"},J:{"2":"_B"},K:{"2":"_D","2052":"H"},L:{"2052":"I"},M:{"1028":"YC"},N:{"2":"_A"},O:{"2052":"bC"},P:{"2":"_3B","2052":"_xB"},Q:{"2052":"JE"},R:{"2052":"KE"},S:{"1028":"_C"}},B:4,C:"text-decoration styling",D:true};