diff --git a/tools/ui/node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api/dist/util.js.map b/tools/ui/node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api/dist/util.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b144056d90b6dbe245110c66a77e2b773d558685 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api/dist/util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"util.js","names":["_getRole","_interopRequireWildcard","require","exports","getLocalName","_getRequireWildcardCache","nodeInterop","WeakMap","cacheBabelInterop","cacheNodeInterop","obj","__esModule","_typeof","default","cache","has","get","newObj","hasPropertyDescriptor","Object","defineProperty","getOwnPropertyDescriptor","key","prototype","hasOwnProperty","call","desc","set","presentationRoles","isElement","node","nodeType","ELEMENT_NODE","isHTMLTableCaptionElement","isHTMLInputElement","isHTMLOptGroupElement","isHTMLSelectElement","isHTMLTableElement","isHTMLTextAreaElement","safeWindow","_ref","ownerDocument","defaultView","TypeError","isHTMLFieldSetElement","isHTMLLegendElement","isHTMLSlotElement","isSVGElement","ownerSVGElement","undefined","isSVGSVGElement","isSVGTitleElement","queryIdRefs","attributeName","hasAttribute","ids","getAttribute","split","root","getRootNode","map","id","getElementById","filter","element","hasAnyConcreteRoles","roles","indexOf","getRole"],"sources":["../sources/util.ts"],"sourcesContent":["export { getLocalName } from \"./getRole\";\nimport getRole, { getLocalName } from \"./getRole\";\n\nexport const presentationRoles = [\"presentation\", \"none\"];\n\nexport function isElement(node: Node | null): node is Element {\n\treturn node !== null && node.nodeType === node.ELEMENT_NODE;\n}\n\nexport function isHTMLTableCaptionElement(\n\tnode: Node | null,\n): node is HTMLTableCaptionElement {\n\treturn isElement(node) && getLocalName(node) === \"caption\";\n}\n\nexport function isHTMLInputElement(\n\tnode: Node | null,\n): node is HTMLInputElement {\n\treturn isElement(node) && getLocalName(node) === \"input\";\n}\n\nexport function isHTMLOptGroupElement(\n\tnode: Node | null,\n): node is HTMLOptGroupElement {\n\treturn isElement(node) && getLocalName(node) === \"optgroup\";\n}\n\nexport function isHTMLSelectElement(\n\tnode: Node | null,\n): node is HTMLSelectElement {\n\treturn isElement(node) && getLocalName(node) === \"select\";\n}\n\nexport function isHTMLTableElement(\n\tnode: Node | null,\n): node is HTMLTableElement {\n\treturn isElement(node) && getLocalName(node) === \"table\";\n}\n\nexport function isHTMLTextAreaElement(\n\tnode: Node | null,\n): node is HTMLTextAreaElement {\n\treturn isElement(node) && getLocalName(node) === \"textarea\";\n}\n\nexport function safeWindow(node: Node): Window {\n\tconst { defaultView } =\n\t\tnode.ownerDocument === null ? (node as Document) : node.ownerDocument;\n\n\tif (defaultView === null) {\n\t\tthrow new TypeError(\"no window available\");\n\t}\n\treturn defaultView;\n}\n\nexport function isHTMLFieldSetElement(\n\tnode: Node | null,\n): node is HTMLFieldSetElement {\n\treturn isElement(node) && getLocalName(node) === \"fieldset\";\n}\n\nexport function isHTMLLegendElement(\n\tnode: Node | null,\n): node is HTMLLegendElement {\n\treturn isElement(node) && getLocalName(node) === \"legend\";\n}\n\nexport function isHTMLSlotElement(node: Node | null): node is HTMLSlotElement {\n\treturn isElement(node) && getLocalName(node) === \"slot\";\n}\n\nexport function isSVGElement(node: Node | null): node is SVGElement {\n\treturn isElement(node) && (node as SVGElement).ownerSVGElement !== undefined;\n}\n\nexport function isSVGSVGElement(node: Node | null): node is SVGSVGElement {\n\treturn isElement(node) && getLocalName(node) === \"svg\";\n}\n\nexport function isSVGTitleElement(node: Node | null): node is SVGTitleElement {\n\treturn isSVGElement(node) && getLocalName(node) === \"title\";\n}\n\n/**\n *\n * @param {Node} node -\n * @param {string} attributeName -\n * @returns {Element[]} -\n */\nexport function queryIdRefs(node: Node, attributeName: string): Element[] {\n\tif (isElement(node) && node.hasAttribute(attributeName)) {\n\t\t// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- safe due to hasAttribute check\n\t\tconst ids = node.getAttribute(attributeName)!.split(\" \");\n\n\t\t// Browsers that don't support shadow DOM won't have getRootNode\n\t\tconst root = node.getRootNode\n\t\t\t? (node.getRootNode() as Document | ShadowRoot)\n\t\t\t: node.ownerDocument;\n\n\t\treturn ids\n\t\t\t.map((id) => root.getElementById(id))\n\t\t\t.filter(\n\t\t\t\t(element: Element | null): element is Element => element !== null,\n\t\t\t\t// TODO: why does this not narrow?\n\t\t\t) as Element[];\n\t}\n\n\treturn [];\n}\n\nexport function hasAnyConcreteRoles(\n\tnode: Node,\n\troles: Array,\n): node is Element {\n\tif (isElement(node)) {\n\t\treturn roles.indexOf(getRole(node)) !== -1;\n\t}\n\treturn false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,QAAA,GAAAC,uBAAA,CAAAC,OAAA;AAAyCC,OAAA,CAAAC,YAAA,GAAAJ,QAAA,CAAAI,YAAA;AAAA,SAAAC,yBAAAC,WAAA,eAAAC,OAAA,kCAAAC,iBAAA,OAAAD,OAAA,QAAAE,gBAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,yBAAAC,WAAA,WAAAA,WAAA,GAAAG,gBAAA,GAAAD,iBAAA,KAAAF,WAAA;AAAA,SAAAL,wBAAAS,GAAA,EAAAJ,WAAA,SAAAA,WAAA,IAAAI,GAAA,IAAAA,GAAA,CAAAC,UAAA,WAAAD,GAAA,QAAAA,GAAA,aAAAE,OAAA,CAAAF,GAAA,yBAAAA,GAAA,4BAAAG,OAAA,EAAAH,GAAA,UAAAI,KAAA,GAAAT,wBAAA,CAAAC,WAAA,OAAAQ,KAAA,IAAAA,KAAA,CAAAC,GAAA,CAAAL,GAAA,YAAAI,KAAA,CAAAE,GAAA,CAAAN,GAAA,SAAAO,MAAA,WAAAC,qBAAA,GAAAC,MAAA,CAAAC,cAAA,IAAAD,MAAA,CAAAE,wBAAA,WAAAC,GAAA,IAAAZ,GAAA,QAAAY,GAAA,kBAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAf,GAAA,EAAAY,GAAA,SAAAI,IAAA,GAAAR,qBAAA,GAAAC,MAAA,CAAAE,wBAAA,CAAAX,GAAA,EAAAY,GAAA,cAAAI,IAAA,KAAAA,IAAA,CAAAV,GAAA,IAAAU,IAAA,CAAAC,GAAA,KAAAR,MAAA,CAAAC,cAAA,CAAAH,MAAA,EAAAK,GAAA,EAAAI,IAAA,YAAAT,MAAA,CAAAK,GAAA,IAAAZ,GAAA,CAAAY,GAAA,SAAAL,MAAA,CAAAJ,OAAA,GAAAH,GAAA,MAAAI,KAAA,IAAAA,KAAA,CAAAa,GAAA,CAAAjB,GAAA,EAAAO,MAAA,YAAAA,MAAA;AAGlC,IAAMW,iBAAiB,GAAG,CAAC,cAAc,EAAE,MAAM,CAAC;AAACzB,OAAA,CAAAyB,iBAAA,GAAAA,iBAAA;AAEnD,SAASC,SAASA,CAACC,IAAiB,EAAmB;EAC7D,OAAOA,IAAI,KAAK,IAAI,IAAIA,IAAI,CAACC,QAAQ,KAAKD,IAAI,CAACE,YAAY;AAC5D;AAEO,SAASC,yBAAyBA,CACxCH,IAAiB,EACiB;EAClC,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAI,IAAA1B,qBAAY,EAAC0B,IAAI,CAAC,KAAK,SAAS;AAC3D;AAEO,SAASI,kBAAkBA,CACjCJ,IAAiB,EACU;EAC3B,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAI,IAAA1B,qBAAY,EAAC0B,IAAI,CAAC,KAAK,OAAO;AACzD;AAEO,SAASK,qBAAqBA,CACpCL,IAAiB,EACa;EAC9B,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAI,IAAA1B,qBAAY,EAAC0B,IAAI,CAAC,KAAK,UAAU;AAC5D;AAEO,SAASM,mBAAmBA,CAClCN,IAAiB,EACW;EAC5B,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAI,IAAA1B,qBAAY,EAAC0B,IAAI,CAAC,KAAK,QAAQ;AAC1D;AAEO,SAASO,kBAAkBA,CACjCP,IAAiB,EACU;EAC3B,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAI,IAAA1B,qBAAY,EAAC0B,IAAI,CAAC,KAAK,OAAO;AACzD;AAEO,SAASQ,qBAAqBA,CACpCR,IAAiB,EACa;EAC9B,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAI,IAAA1B,qBAAY,EAAC0B,IAAI,CAAC,KAAK,UAAU;AAC5D;AAEO,SAASS,UAAUA,CAACT,IAAU,EAAU;EAC9C,IAAAU,IAAA,GACCV,IAAI,CAACW,aAAa,KAAK,IAAI,GAAIX,IAAI,GAAgBA,IAAI,CAACW,aAAa;IAD9DC,WAAW,GAAAF,IAAA,CAAXE,WAAW;EAGnB,IAAIA,WAAW,KAAK,IAAI,EAAE;IACzB,MAAM,IAAIC,SAAS,CAAC,qBAAqB,CAAC;EAC3C;EACA,OAAOD,WAAW;AACnB;AAEO,SAASE,qBAAqBA,CACpCd,IAAiB,EACa;EAC9B,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAI,IAAA1B,qBAAY,EAAC0B,IAAI,CAAC,KAAK,UAAU;AAC5D;AAEO,SAASe,mBAAmBA,CAClCf,IAAiB,EACW;EAC5B,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAI,IAAA1B,qBAAY,EAAC0B,IAAI,CAAC,KAAK,QAAQ;AAC1D;AAEO,SAASgB,iBAAiBA,CAAChB,IAAiB,EAA2B;EAC7E,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAI,IAAA1B,qBAAY,EAAC0B,IAAI,CAAC,KAAK,MAAM;AACxD;AAEO,SAASiB,YAAYA,CAACjB,IAAiB,EAAsB;EACnE,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAKA,IAAI,CAAgBkB,eAAe,KAAKC,SAAS;AAC7E;AAEO,SAASC,eAAeA,CAACpB,IAAiB,EAAyB;EACzE,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAI,IAAA1B,qBAAY,EAAC0B,IAAI,CAAC,KAAK,KAAK;AACvD;AAEO,SAASqB,iBAAiBA,CAACrB,IAAiB,EAA2B;EAC7E,OAAOiB,YAAY,CAACjB,IAAI,CAAC,IAAI,IAAA1B,qBAAY,EAAC0B,IAAI,CAAC,KAAK,OAAO;AAC5D;;AAEA;AACA;AACA;AACA;AACA;AACA;AACO,SAASsB,WAAWA,CAACtB,IAAU,EAAEuB,aAAqB,EAAa;EACzE,IAAIxB,SAAS,CAACC,IAAI,CAAC,IAAIA,IAAI,CAACwB,YAAY,CAACD,aAAa,CAAC,EAAE;IACxD;IACA,IAAME,GAAG,GAAGzB,IAAI,CAAC0B,YAAY,CAACH,aAAa,CAAC,CAAEI,KAAK,CAAC,GAAG,CAAC;;IAExD;IACA,IAAMC,IAAI,GAAG5B,IAAI,CAAC6B,WAAW,GACzB7B,IAAI,CAAC6B,WAAW,CAAC,CAAC,GACnB7B,IAAI,CAACW,aAAa;IAErB,OAAOc,GAAG,CACRK,GAAG,CAAC,UAACC,EAAE;MAAA,OAAKH,IAAI,CAACI,cAAc,CAACD,EAAE,CAAC;IAAA,EAAC,CACpCE,MAAM,CACN,UAACC,OAAuB;MAAA,OAAyBA,OAAO,KAAK,IAAI;IAAA;IACjE;IACD,CAAC;EACH;;EAEA,OAAO,EAAE;AACV;AAEO,SAASC,mBAAmBA,CAClCnC,IAAU,EACVoC,KAA2B,EACT;EAClB,IAAIrC,SAAS,CAACC,IAAI,CAAC,EAAE;IACpB,OAAOoC,KAAK,CAACC,OAAO,CAAC,IAAAC,gBAAO,EAACtC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC;EAC3C;EACA,OAAO,KAAK;AACb"} \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api/dist/util.mjs b/tools/ui/node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api/dist/util.mjs new file mode 100644 index 0000000000000000000000000000000000000000..98cacbb5e2aafb19eaf5b481f661b7ff7781a272 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api/dist/util.mjs @@ -0,0 +1,82 @@ +export { getLocalName } from "./getRole.mjs"; +import getRole, { getLocalName } from "./getRole.mjs"; +export var presentationRoles = ["presentation", "none"]; +export function isElement(node) { + return node !== null && node.nodeType === node.ELEMENT_NODE; +} +export function isHTMLTableCaptionElement(node) { + return isElement(node) && getLocalName(node) === "caption"; +} +export function isHTMLInputElement(node) { + return isElement(node) && getLocalName(node) === "input"; +} +export function isHTMLOptGroupElement(node) { + return isElement(node) && getLocalName(node) === "optgroup"; +} +export function isHTMLSelectElement(node) { + return isElement(node) && getLocalName(node) === "select"; +} +export function isHTMLTableElement(node) { + return isElement(node) && getLocalName(node) === "table"; +} +export function isHTMLTextAreaElement(node) { + return isElement(node) && getLocalName(node) === "textarea"; +} +export function safeWindow(node) { + var _ref = node.ownerDocument === null ? node : node.ownerDocument, + defaultView = _ref.defaultView; + if (defaultView === null) { + throw new TypeError("no window available"); + } + return defaultView; +} +export function isHTMLFieldSetElement(node) { + return isElement(node) && getLocalName(node) === "fieldset"; +} +export function isHTMLLegendElement(node) { + return isElement(node) && getLocalName(node) === "legend"; +} +export function isHTMLSlotElement(node) { + return isElement(node) && getLocalName(node) === "slot"; +} +export function isSVGElement(node) { + return isElement(node) && node.ownerSVGElement !== undefined; +} +export function isSVGSVGElement(node) { + return isElement(node) && getLocalName(node) === "svg"; +} +export function isSVGTitleElement(node) { + return isSVGElement(node) && getLocalName(node) === "title"; +} + +/** + * + * @param {Node} node - + * @param {string} attributeName - + * @returns {Element[]} - + */ +export function queryIdRefs(node, attributeName) { + if (isElement(node) && node.hasAttribute(attributeName)) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- safe due to hasAttribute check + var ids = node.getAttribute(attributeName).split(" "); + + // Browsers that don't support shadow DOM won't have getRootNode + var root = node.getRootNode ? node.getRootNode() : node.ownerDocument; + return ids.map(function (id) { + return root.getElementById(id); + }).filter(function (element) { + return element !== null; + } + // TODO: why does this not narrow? + ); + } + + return []; +} +export function hasAnyConcreteRoles(node, roles) { + if (isElement(node)) { + return roles.indexOf(getRole(node)) !== -1; + } + return false; +} +//# sourceMappingURL=util.mjs.map \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api/dist/util.mjs.map b/tools/ui/node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api/dist/util.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..b0f85e3331cde9c6387d5b588f2a9dc079ea3468 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api/dist/util.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"util.mjs","names":["getLocalName","getRole","presentationRoles","isElement","node","nodeType","ELEMENT_NODE","isHTMLTableCaptionElement","isHTMLInputElement","isHTMLOptGroupElement","isHTMLSelectElement","isHTMLTableElement","isHTMLTextAreaElement","safeWindow","_ref","ownerDocument","defaultView","TypeError","isHTMLFieldSetElement","isHTMLLegendElement","isHTMLSlotElement","isSVGElement","ownerSVGElement","undefined","isSVGSVGElement","isSVGTitleElement","queryIdRefs","attributeName","hasAttribute","ids","getAttribute","split","root","getRootNode","map","id","getElementById","filter","element","hasAnyConcreteRoles","roles","indexOf"],"sources":["../sources/util.ts"],"sourcesContent":["export { getLocalName } from \"./getRole\";\nimport getRole, { getLocalName } from \"./getRole\";\n\nexport const presentationRoles = [\"presentation\", \"none\"];\n\nexport function isElement(node: Node | null): node is Element {\n\treturn node !== null && node.nodeType === node.ELEMENT_NODE;\n}\n\nexport function isHTMLTableCaptionElement(\n\tnode: Node | null,\n): node is HTMLTableCaptionElement {\n\treturn isElement(node) && getLocalName(node) === \"caption\";\n}\n\nexport function isHTMLInputElement(\n\tnode: Node | null,\n): node is HTMLInputElement {\n\treturn isElement(node) && getLocalName(node) === \"input\";\n}\n\nexport function isHTMLOptGroupElement(\n\tnode: Node | null,\n): node is HTMLOptGroupElement {\n\treturn isElement(node) && getLocalName(node) === \"optgroup\";\n}\n\nexport function isHTMLSelectElement(\n\tnode: Node | null,\n): node is HTMLSelectElement {\n\treturn isElement(node) && getLocalName(node) === \"select\";\n}\n\nexport function isHTMLTableElement(\n\tnode: Node | null,\n): node is HTMLTableElement {\n\treturn isElement(node) && getLocalName(node) === \"table\";\n}\n\nexport function isHTMLTextAreaElement(\n\tnode: Node | null,\n): node is HTMLTextAreaElement {\n\treturn isElement(node) && getLocalName(node) === \"textarea\";\n}\n\nexport function safeWindow(node: Node): Window {\n\tconst { defaultView } =\n\t\tnode.ownerDocument === null ? (node as Document) : node.ownerDocument;\n\n\tif (defaultView === null) {\n\t\tthrow new TypeError(\"no window available\");\n\t}\n\treturn defaultView;\n}\n\nexport function isHTMLFieldSetElement(\n\tnode: Node | null,\n): node is HTMLFieldSetElement {\n\treturn isElement(node) && getLocalName(node) === \"fieldset\";\n}\n\nexport function isHTMLLegendElement(\n\tnode: Node | null,\n): node is HTMLLegendElement {\n\treturn isElement(node) && getLocalName(node) === \"legend\";\n}\n\nexport function isHTMLSlotElement(node: Node | null): node is HTMLSlotElement {\n\treturn isElement(node) && getLocalName(node) === \"slot\";\n}\n\nexport function isSVGElement(node: Node | null): node is SVGElement {\n\treturn isElement(node) && (node as SVGElement).ownerSVGElement !== undefined;\n}\n\nexport function isSVGSVGElement(node: Node | null): node is SVGSVGElement {\n\treturn isElement(node) && getLocalName(node) === \"svg\";\n}\n\nexport function isSVGTitleElement(node: Node | null): node is SVGTitleElement {\n\treturn isSVGElement(node) && getLocalName(node) === \"title\";\n}\n\n/**\n *\n * @param {Node} node -\n * @param {string} attributeName -\n * @returns {Element[]} -\n */\nexport function queryIdRefs(node: Node, attributeName: string): Element[] {\n\tif (isElement(node) && node.hasAttribute(attributeName)) {\n\t\t// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- safe due to hasAttribute check\n\t\tconst ids = node.getAttribute(attributeName)!.split(\" \");\n\n\t\t// Browsers that don't support shadow DOM won't have getRootNode\n\t\tconst root = node.getRootNode\n\t\t\t? (node.getRootNode() as Document | ShadowRoot)\n\t\t\t: node.ownerDocument;\n\n\t\treturn ids\n\t\t\t.map((id) => root.getElementById(id))\n\t\t\t.filter(\n\t\t\t\t(element: Element | null): element is Element => element !== null,\n\t\t\t\t// TODO: why does this not narrow?\n\t\t\t) as Element[];\n\t}\n\n\treturn [];\n}\n\nexport function hasAnyConcreteRoles(\n\tnode: Node,\n\troles: Array,\n): node is Element {\n\tif (isElement(node)) {\n\t\treturn roles.indexOf(getRole(node)) !== -1;\n\t}\n\treturn false;\n}\n"],"mappings":"AAAA,SAASA,YAAY,QAAQ,eAAW;AACxC,OAAOC,OAAO,IAAID,YAAY,QAAQ,eAAW;AAEjD,OAAO,IAAME,iBAAiB,GAAG,CAAC,cAAc,EAAE,MAAM,CAAC;AAEzD,OAAO,SAASC,SAASA,CAACC,IAAiB,EAAmB;EAC7D,OAAOA,IAAI,KAAK,IAAI,IAAIA,IAAI,CAACC,QAAQ,KAAKD,IAAI,CAACE,YAAY;AAC5D;AAEA,OAAO,SAASC,yBAAyBA,CACxCH,IAAiB,EACiB;EAClC,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAIJ,YAAY,CAACI,IAAI,CAAC,KAAK,SAAS;AAC3D;AAEA,OAAO,SAASI,kBAAkBA,CACjCJ,IAAiB,EACU;EAC3B,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAIJ,YAAY,CAACI,IAAI,CAAC,KAAK,OAAO;AACzD;AAEA,OAAO,SAASK,qBAAqBA,CACpCL,IAAiB,EACa;EAC9B,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAIJ,YAAY,CAACI,IAAI,CAAC,KAAK,UAAU;AAC5D;AAEA,OAAO,SAASM,mBAAmBA,CAClCN,IAAiB,EACW;EAC5B,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAIJ,YAAY,CAACI,IAAI,CAAC,KAAK,QAAQ;AAC1D;AAEA,OAAO,SAASO,kBAAkBA,CACjCP,IAAiB,EACU;EAC3B,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAIJ,YAAY,CAACI,IAAI,CAAC,KAAK,OAAO;AACzD;AAEA,OAAO,SAASQ,qBAAqBA,CACpCR,IAAiB,EACa;EAC9B,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAIJ,YAAY,CAACI,IAAI,CAAC,KAAK,UAAU;AAC5D;AAEA,OAAO,SAASS,UAAUA,CAACT,IAAU,EAAU;EAC9C,IAAAU,IAAA,GACCV,IAAI,CAACW,aAAa,KAAK,IAAI,GAAIX,IAAI,GAAgBA,IAAI,CAACW,aAAa;IAD9DC,WAAW,GAAAF,IAAA,CAAXE,WAAW;EAGnB,IAAIA,WAAW,KAAK,IAAI,EAAE;IACzB,MAAM,IAAIC,SAAS,CAAC,qBAAqB,CAAC;EAC3C;EACA,OAAOD,WAAW;AACnB;AAEA,OAAO,SAASE,qBAAqBA,CACpCd,IAAiB,EACa;EAC9B,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAIJ,YAAY,CAACI,IAAI,CAAC,KAAK,UAAU;AAC5D;AAEA,OAAO,SAASe,mBAAmBA,CAClCf,IAAiB,EACW;EAC5B,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAIJ,YAAY,CAACI,IAAI,CAAC,KAAK,QAAQ;AAC1D;AAEA,OAAO,SAASgB,iBAAiBA,CAAChB,IAAiB,EAA2B;EAC7E,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAIJ,YAAY,CAACI,IAAI,CAAC,KAAK,MAAM;AACxD;AAEA,OAAO,SAASiB,YAAYA,CAACjB,IAAiB,EAAsB;EACnE,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAKA,IAAI,CAAgBkB,eAAe,KAAKC,SAAS;AAC7E;AAEA,OAAO,SAASC,eAAeA,CAACpB,IAAiB,EAAyB;EACzE,OAAOD,SAAS,CAACC,IAAI,CAAC,IAAIJ,YAAY,CAACI,IAAI,CAAC,KAAK,KAAK;AACvD;AAEA,OAAO,SAASqB,iBAAiBA,CAACrB,IAAiB,EAA2B;EAC7E,OAAOiB,YAAY,CAACjB,IAAI,CAAC,IAAIJ,YAAY,CAACI,IAAI,CAAC,KAAK,OAAO;AAC5D;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASsB,WAAWA,CAACtB,IAAU,EAAEuB,aAAqB,EAAa;EACzE,IAAIxB,SAAS,CAACC,IAAI,CAAC,IAAIA,IAAI,CAACwB,YAAY,CAACD,aAAa,CAAC,EAAE;IACxD;IACA,IAAME,GAAG,GAAGzB,IAAI,CAAC0B,YAAY,CAACH,aAAa,CAAC,CAAEI,KAAK,CAAC,GAAG,CAAC;;IAExD;IACA,IAAMC,IAAI,GAAG5B,IAAI,CAAC6B,WAAW,GACzB7B,IAAI,CAAC6B,WAAW,CAAC,CAAC,GACnB7B,IAAI,CAACW,aAAa;IAErB,OAAOc,GAAG,CACRK,GAAG,CAAC,UAACC,EAAE;MAAA,OAAKH,IAAI,CAACI,cAAc,CAACD,EAAE,CAAC;IAAA,EAAC,CACpCE,MAAM,CACN,UAACC,OAAuB;MAAA,OAAyBA,OAAO,KAAK,IAAI;IAAA;IACjE;IACD,CAAC;EACH;;EAEA,OAAO,EAAE;AACV;AAEA,OAAO,SAASC,mBAAmBA,CAClCnC,IAAU,EACVoC,KAA2B,EACT;EAClB,IAAIrC,SAAS,CAACC,IAAI,CAAC,EAAE;IACpB,OAAOoC,KAAK,CAACC,OAAO,CAACxC,OAAO,CAACG,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC;EAC3C;EACA,OAAO,KAAK;AACb"} \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api/package.json b/tools/ui/node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8710f8af813bdfda103b6f4f6fbf6ffcf9823b71 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api/package.json @@ -0,0 +1,92 @@ +{ + "name": "dom-accessibility-api", + "description": "Implements https://w3c.github.io/accname/", + "version": "0.6.3", + "main": "dist/index.js", + "module": "dist/index.mjs", + "type": "commonjs", + "exports": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/eps1lon/dom-accessibility-api.git" + }, + "files": [ + "dist/" + ], + "scripts": { + "build": "yarn build:clean && yarn build:source && yarn build:source:cjs && yarn build:types", + "build:clean": "rimraf dist", + "build:source": "cross-env BABEL_ENV=esm babel sources --extensions \".ts\" --ignore \"**/__tests__/**/*\" --out-dir dist/ --out-file-extension=.mjs --source-maps", + "build:source:cjs": "cross-env BABEL_ENV=cjs babel sources --extensions \".ts\" --ignore \"**/__tests__/**/*\" --out-dir dist/ --out-file-extension=.js --source-maps", + "build:types": "tsc -p tsconfig.json --emitDeclarationOnly", + "format": "prettier \"**/*.{json,js,md,ts,yml}\" --write --ignore-path .prettierignore", + "lint": "eslint --report-unused-disable-directives \"{scripts,sources}/**/*.{js,ts}\"", + "release": "yarn build && yarn changeset publish", + "test": "jest --config scripts/jest/jest.config.js", + "test:ci": "jest --ci --config scripts/jest/jest.ci.config.js --runInBand", + "test:coverage": "jest --config scripts/jest/jest.coverage.config.js", + "test:types": "tsc -p tsconfig.json --noEmit", + "test:wpt:jsdom": "mocha tests/wpt-jsdom/run-wpts.js", + "test:wpt:browser": "concurrently --success first --kill-others \"yarn test:wpt:browser:run\" \"yarn test:wpt:browser:server\"", + "test:wpt:browser:run": "cypress run --project tests", + "test:wpt:browser:server": "serve tests/wpt", + "test:wpt:browser:open": "cypress open --project tests", + "wpt:init": "git submodule update --init --recursive", + "wpt:reset": "rimraf ./tests/wpt && yarn wpt:init", + "wpt:update": "git submodule update --recursive --remote && cd tests/wpt && python wpt.py manifest --path ../wpt-jsdom/wpt-manifest.json" + }, + "devDependencies": { + "@babel/cli": "^7.14.3", + "@babel/core": "^7.14.3", + "@babel/plugin-proposal-class-properties": "^7.13.0", + "@babel/preset-env": "^7.14.4", + "@babel/preset-typescript": "^7.13.0", + "@changesets/changelog-github": "^0.4.0", + "@changesets/cli": "^2.16.0", + "@testing-library/dom": "^9.0.0", + "@types/jest": "^29.0.0", + "@types/node": "18.17.17", + "@typescript-eslint/eslint-plugin": "^6.0.0", + "@typescript-eslint/parser": "^6.0.0", + "concurrently": "^8.0.0", + "cross-env": "^7.0.3", + "cypress": "^12.0.0", + "eslint": "^7.27.0", + "eslint-plugin-jest": "^27.0.0", + "jest": "^29.0.0", + "jest-diff": "^29.0.0", + "jest-environment-jsdom": "^29.0.0", + "jest-junit": "^16.0.0", + "js-yaml": "^4.1.0", + "jsdom": "^20.0.0", + "minimatch": "^9.0.0", + "mocha": "^10.0.0", + "mocha-sugar-free": "^1.4.0", + "prettier": "^3.0.0", + "q": "^1.5.1", + "request": "^2.88", + "request-promise-native": "^1.0.9", + "rimraf": "^5.0.0", + "serve": "^14.0.0", + "typescript": "^5.0.0" + }, + "resolutions": { + "@types/node": "18.17.17" + }, + "prettier": { + "useTabs": true + }, + "keywords": [ + "accessibility", + "ARIA", + "accname" + ], + "publishConfig": { + "access": "public" + } +} diff --git a/tools/ui/node_modules/@testing-library/jest-dom/package.json b/tools/ui/node_modules/@testing-library/jest-dom/package.json new file mode 100644 index 0000000000000000000000000000000000000000..815065b97fd4a7a706eb2a029242f37092e4259b --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/package.json @@ -0,0 +1,152 @@ +{ + "name": "@testing-library/jest-dom", + "version": "6.9.1", + "description": "Custom jest matchers to test the state of the DOM", + "main": "dist/index.js", + "module": "dist/index.mjs", + "exports": { + ".": { + "require": { + "types": "./types/index.d.ts", + "default": "./dist/index.js" + }, + "import": { + "types": "./types/index.d.ts", + "default": "./dist/index.mjs" + } + }, + "./jest-globals": { + "require": { + "types": "./types/jest-globals.d.ts", + "default": "./dist/jest-globals.js" + }, + "import": { + "types": "./types/jest-globals.d.ts", + "default": "./dist/jest-globals.mjs" + } + }, + "./matchers": { + "require": { + "types": "./types/matchers-standalone.d.ts", + "default": "./dist/matchers.js" + }, + "import": { + "types": "./types/matchers-standalone.d.ts", + "default": "./dist/matchers.mjs" + } + }, + "./vitest": { + "require": { + "types": "./types/vitest.d.ts", + "default": "./dist/vitest.js" + }, + "import": { + "types": "./types/vitest.d.ts", + "default": "./dist/vitest.mjs" + } + }, + "./package.json": "./package.json" + }, + "types": "types/index.d.ts", + "engines": { + "node": ">=14", + "npm": ">=6", + "yarn": ">=1" + }, + "scripts": { + "build": "rollup -c", + "format": "kcd-scripts format", + "lint": "kcd-scripts lint", + "setup": "npm install && npm run validate -s", + "test": "kcd-scripts test", + "test:update": "npm test -- --updateSnapshot --coverage", + "test:types": "tsc -p types/__tests__/jest && tsc -p types/__tests__/jest-globals && tsc -p types/__tests__/vitest && tsc -p types/__tests__/bun", + "validate": "kcd-scripts validate && npm run test:types" + }, + "files": [ + "dist", + "types", + "*.d.ts", + "jest-globals.js", + "matchers.js", + "vitest.js" + ], + "keywords": [ + "testing", + "dom", + "jest", + "jsdom" + ], + "author": "Ernesto Garcia (http://gnapse.github.io)", + "license": "MIT", + "dependencies": { + "@adobe/css-tools": "^4.4.0", + "aria-query": "^5.0.0", + "css.escape": "^1.5.1", + "dom-accessibility-api": "^0.6.3", + "picocolors": "^1.1.1", + "redent": "^3.0.0" + }, + "devDependencies": { + "@jest/globals": "^29.6.2", + "@rollup/plugin-commonjs": "^25.0.4", + "@types/bun": "latest", + "@types/web": "latest", + "expect": "^29.6.2", + "jest-environment-jsdom-sixteen": "^1.0.3", + "jest-watch-select-projects": "^2.0.0", + "jsdom": "^16.2.1", + "kcd-scripts": "^14.0.0", + "pretty-format": "^25.1.0", + "rollup": "^3.28.1", + "rollup-plugin-delete": "^2.0.0", + "typescript": "^5.1.6", + "vitest": "^0.34.1" + }, + "eslintConfig": { + "extends": "./node_modules/kcd-scripts/eslint.js", + "parserOptions": { + "sourceType": "module", + "ecmaVersion": 2020 + }, + "rules": { + "no-invalid-this": "off" + }, + "overrides": [ + { + "files": [ + "src/__tests__/*.js" + ], + "rules": { + "max-lines-per-function": "off" + } + }, + { + "files": [ + "**/*.d.ts" + ], + "rules": { + "@typescript-eslint/no-empty-interface": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-invalid-void-type": "off", + "@typescript-eslint/no-unused-vars": "off", + "@typescript-eslint/triple-slash-reference": "off" + } + } + ] + }, + "eslintIgnore": [ + "node_modules", + "coverage", + "dist", + "types/__tests__" + ], + "repository": { + "type": "git", + "url": "https://github.com/testing-library/jest-dom" + }, + "bugs": { + "url": "https://github.com/testing-library/jest-dom/issues" + }, + "homepage": "https://github.com/testing-library/jest-dom#readme" +} diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/bun/bun-custom-expect-types.test.ts b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/bun/bun-custom-expect-types.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1467e913526c0c75bd1e0623fcba2fb05b2f178c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/bun/bun-custom-expect-types.test.ts @@ -0,0 +1,100 @@ +/** + * File that tests whether the TypeScript typings work as expected. + */ + +/* eslint-disable @typescript-eslint/no-unsafe-call */ +/* eslint-disable @typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-unsafe-argument */ + +import {expect} from 'bun:test' +import * as matchersStandalone from '../../matchers-standalone' +import * as originalMatchers from '../../matchers' + +expect.extend(matchersStandalone) + +const element: HTMLElement = document.body + +function customExpect( + _actual: HTMLElement, +): + | originalMatchers.TestingLibraryMatchers + | originalMatchers.TestingLibraryMatchers> { + throw new Error('Method not implemented.') +} + +customExpect(element).toBeInTheDOM() +customExpect(element).toBeInTheDOM(document.body) +customExpect(element).toBeInTheDocument() +customExpect(element).toBeVisible() +customExpect(element).toBeEmpty() +customExpect(element).toBeDisabled() +customExpect(element).toBeEnabled() +customExpect(element).toBeInvalid() +customExpect(element).toBeRequired() +customExpect(element).toBeValid() +customExpect(element).toContainElement(document.body) +customExpect(element).toContainElement(null) +customExpect(element).toContainHTML('body') +customExpect(element).toHaveAttribute('attr') +customExpect(element).toHaveAttribute('attr', true) +customExpect(element).toHaveAttribute('attr', 'yes') +customExpect(element).toHaveClass() +customExpect(element).toHaveClass('cls1') +customExpect(element).toHaveClass('cls1', 'cls2', 'cls3', 'cls4') +customExpect(element).toHaveClass('cls1', {exact: true}) +customExpect(element).toHaveDisplayValue('str') +customExpect(element).toHaveDisplayValue(['str1', 'str2']) +customExpect(element).toHaveDisplayValue(/str/) +customExpect(element).toHaveDisplayValue([/str1/, 'str2']) +customExpect(element).toHaveFocus() +customExpect(element).toHaveFormValues({foo: 'bar', baz: 1}) +customExpect(element).toHaveStyle('display: block') +customExpect(element).toHaveStyle({display: 'block', width: 100}) +customExpect(element).toHaveTextContent('Text') +customExpect(element).toHaveTextContent(/Text/) +customExpect(element).toHaveTextContent('Text', {normalizeWhitespace: true}) +customExpect(element).toHaveTextContent(/Text/, {normalizeWhitespace: true}) +customExpect(element).toHaveValue() +customExpect(element).toHaveValue('str') +customExpect(element).toHaveValue(['str1', 'str2']) +customExpect(element).toHaveValue(1) +customExpect(element).toHaveValue(null) +customExpect(element).toBeChecked() +customExpect(element).toHaveDescription('some description') +customExpect(element).toHaveDescription(/some description/) +customExpect(element).toHaveDescription(expect.stringContaining('partial')) +customExpect(element).toHaveDescription() +customExpect(element).toHaveAccessibleDescription('some description') +customExpect(element).toHaveAccessibleDescription(/some description/) +customExpect(element).toHaveAccessibleDescription( + expect.stringContaining('partial'), +) +customExpect(element).toHaveAccessibleDescription() + +customExpect(element).toHaveAccessibleErrorMessage() +customExpect(element).toHaveAccessibleErrorMessage( + 'Invalid time: the time must be between 9:00 AM and 5:00 PM', +) +customExpect(element).toHaveAccessibleErrorMessage(/invalid time/i) +customExpect(element).toHaveAccessibleErrorMessage( + expect.stringContaining('Invalid time'), +) + +customExpect(element).toHaveAccessibleName('a label') +customExpect(element).toHaveAccessibleName(/a label/) +customExpect(element).toHaveAccessibleName( + expect.stringContaining('partial label'), +) +customExpect(element).toHaveAccessibleName() +customExpect(element).toHaveErrorMessage( + 'Invalid time: the time must be between 9:00 AM and 5:00 PM', +) +customExpect(element).toHaveErrorMessage(/invalid time/i) +customExpect(element).toHaveErrorMessage( + expect.stringContaining('Invalid time'), +) + +customExpect(element).toHaveRole('button') + +// @ts-expect-error The types accidentally allowed any property by falling back to "any" +customExpect(element).nonExistentProperty() diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/bun/bun-types.test.ts b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/bun/bun-types.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..432dd8675bd712b64d69a20478961a4ecfbee845 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/bun/bun-types.test.ts @@ -0,0 +1,120 @@ +/** + * File that tests whether the TypeScript typings for @types/jest work as expected. + */ + +/* eslint-disable @typescript-eslint/no-unsafe-call */ +/* eslint-disable @typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-unsafe-argument */ + +import {expect} from 'bun:test' +import '../../bun' + +const element: HTMLElement = document.body + +expect(element).toBeInTheDOM() +expect(element).toBeInTheDOM(document.body) +expect(element).toBeInTheDocument() +expect(element).toBeVisible() +expect(element).toBeEmpty() +expect(element).toBeDisabled() +expect(element).toBeEnabled() +expect(element).toBeInvalid() +expect(element).toBeRequired() +expect(element).toBeValid() +expect(element).toContainElement(document.body) +expect(element).toContainElement(null) +expect(element).toContainHTML('body') +expect(element).toHaveAttribute('attr') +expect(element).toHaveAttribute('attr', true) +expect(element).toHaveAttribute('attr', 'yes') +expect(element).toHaveClass() +expect(element).toHaveClass('cls1') +expect(element).toHaveClass('cls1', 'cls2', 'cls3', 'cls4') +expect(element).toHaveClass('cls1', {exact: true}) +expect(element).toHaveDisplayValue('str') +expect(element).toHaveDisplayValue(['str1', 'str2']) +expect(element).toHaveDisplayValue(/str/) +expect(element).toHaveDisplayValue([/str1/, 'str2']) +expect(element).toHaveFocus() +expect(element).toHaveFormValues({foo: 'bar', baz: 1}) +expect(element).toHaveStyle('display: block') +expect(element).toHaveStyle({display: 'block', width: 100}) +expect(element).toHaveTextContent('Text') +expect(element).toHaveTextContent(/Text/) +expect(element).toHaveTextContent('Text', {normalizeWhitespace: true}) +expect(element).toHaveTextContent(/Text/, {normalizeWhitespace: true}) +expect(element).toHaveValue() +expect(element).toHaveValue('str') +expect(element).toHaveValue(['str1', 'str2']) +expect(element).toHaveValue(1) +expect(element).toHaveValue(null) +expect(element).toBeChecked() +expect(element).toHaveDescription('some description') +expect(element).toHaveDescription(/some description/) +expect(element).toHaveDescription(expect.stringContaining('partial')) +expect(element).toHaveDescription() +expect(element).toHaveAccessibleDescription('some description') +expect(element).toHaveAccessibleDescription(/some description/) +expect(element).toHaveAccessibleDescription(expect.stringContaining('partial')) +expect(element).toHaveAccessibleDescription() +expect(element).toHaveAccessibleName('a label') +expect(element).toHaveAccessibleName(/a label/) +expect(element).toHaveAccessibleName(expect.stringContaining('partial label')) +expect(element).toHaveAccessibleName() +expect(element).toHaveErrorMessage( + 'Invalid time: the time must be between 9:00 AM and 5:00 PM', +) +expect(element).toHaveErrorMessage(/invalid time/i) +expect(element).toHaveErrorMessage(expect.stringContaining('Invalid time')) +expect(element).toHaveRole('button') + +expect(element).not.toBeInTheDOM() +expect(element).not.toBeInTheDOM(document.body) +expect(element).not.toBeInTheDocument() +expect(element).not.toBeVisible() +expect(element).not.toBeEmpty() +expect(element).not.toBeEmptyDOMElement() +expect(element).not.toBeDisabled() +expect(element).not.toBeEnabled() +expect(element).not.toBeInvalid() +expect(element).not.toBeRequired() +expect(element).not.toBeValid() +expect(element).not.toContainElement(document.body) +expect(element).not.toContainElement(null) +expect(element).not.toContainHTML('body') +expect(element).not.toHaveAttribute('attr') +expect(element).not.toHaveAttribute('attr', true) +expect(element).not.toHaveAttribute('attr', 'yes') +expect(element).not.toHaveClass() +expect(element).not.toHaveClass('cls1') +expect(element).not.toHaveClass('cls1', 'cls2', 'cls3', 'cls4') +expect(element).not.toHaveClass('cls1', {exact: true}) +expect(element).not.toHaveDisplayValue('str') +expect(element).not.toHaveDisplayValue(['str1', 'str2']) +expect(element).not.toHaveDisplayValue(/str/) +expect(element).not.toHaveDisplayValue([/str1/, 'str2']) +expect(element).not.toHaveFocus() +expect(element).not.toHaveFormValues({foo: 'bar', baz: 1}) +expect(element).not.toHaveStyle('display: block') +expect(element).not.toHaveTextContent('Text') +expect(element).not.toHaveTextContent(/Text/) +expect(element).not.toHaveTextContent('Text', {normalizeWhitespace: true}) +expect(element).not.toHaveTextContent(/Text/, {normalizeWhitespace: true}) +expect(element).not.toHaveValue() +expect(element).not.toHaveValue('str') +expect(element).not.toHaveValue(['str1', 'str2']) +expect(element).not.toHaveValue(1) +expect(element).not.toBeChecked() +expect(element).not.toHaveDescription('some description') +expect(element).not.toHaveDescription() +expect(element).not.toHaveAccessibleDescription('some description') +expect(element).not.toHaveAccessibleDescription() +expect(element).not.toHaveAccessibleName('a label') +expect(element).not.toHaveAccessibleName() +expect(element).not.toBePartiallyChecked() +expect(element).not.toHaveErrorMessage() +expect(element).not.toHaveErrorMessage('Pikachu!') +expect(element).not.toHaveRole('button') + +// @ts-expect-error The types accidentally allowed any property by falling back to "any" +expect(element).nonExistentProperty() diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/bun/tsconfig.json b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/bun/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..2a7ced012120dcb30d8d3970a3000388e386f4b5 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/bun/tsconfig.json @@ -0,0 +1,9 @@ +{ + "compilerOptions": { + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "types": ["bun", "web"] + }, + "include": ["*.ts"] +} diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest-globals/jest-globals-custom-expect-types.test.ts b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest-globals/jest-globals-custom-expect-types.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..96034dc1a75a474b97bf80cc463ea1e3c95fc9af --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest-globals/jest-globals-custom-expect-types.test.ts @@ -0,0 +1,97 @@ +/** + * File that tests whether the TypeScript typings work as expected. + */ + +/* eslint-disable @typescript-eslint/no-unsafe-call */ +/* eslint-disable @typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-unsafe-argument */ + +import {expect} from '@jest/globals' +import * as matchers from '../../matchers' + +expect.extend(matchers) + +const element: HTMLElement = document.body + +function customExpect( + _actual: HTMLElement, +): + | matchers.TestingLibraryMatchers + | matchers.TestingLibraryMatchers> { + throw new Error('Method not implemented.') +} + +customExpect(element).toBeInTheDOM() +customExpect(element).toBeInTheDOM(document.body) +customExpect(element).toBeInTheDocument() +customExpect(element).toBeVisible() +customExpect(element).toBeEmpty() +customExpect(element).toBeDisabled() +customExpect(element).toBeEnabled() +customExpect(element).toBeInvalid() +customExpect(element).toBeRequired() +customExpect(element).toBeValid() +customExpect(element).toContainElement(document.body) +customExpect(element).toContainElement(null) +customExpect(element).toContainHTML('body') +customExpect(element).toHaveAttribute('attr') +customExpect(element).toHaveAttribute('attr', true) +customExpect(element).toHaveAttribute('attr', 'yes') +customExpect(element).toHaveClass() +customExpect(element).toHaveClass('cls1') +customExpect(element).toHaveClass('cls1', 'cls2', 'cls3', 'cls4') +customExpect(element).toHaveClass('cls1', {exact: true}) +customExpect(element).toHaveDisplayValue('str') +customExpect(element).toHaveDisplayValue(['str1', 'str2']) +customExpect(element).toHaveDisplayValue(/str/) +customExpect(element).toHaveDisplayValue([/str1/, 'str2']) +customExpect(element).toHaveFocus() +customExpect(element).toHaveFormValues({foo: 'bar', baz: 1}) +customExpect(element).toHaveStyle('display: block') +customExpect(element).toHaveStyle({display: 'block', width: 100}) +customExpect(element).toHaveTextContent('Text') +customExpect(element).toHaveTextContent(/Text/) +customExpect(element).toHaveTextContent('Text', {normalizeWhitespace: true}) +customExpect(element).toHaveTextContent(/Text/, {normalizeWhitespace: true}) +customExpect(element).toHaveValue() +customExpect(element).toHaveValue('str') +customExpect(element).toHaveValue(['str1', 'str2']) +customExpect(element).toHaveValue(1) +customExpect(element).toHaveValue(null) +customExpect(element).toBeChecked() +customExpect(element).toHaveDescription('some description') +customExpect(element).toHaveDescription(/some description/) +customExpect(element).toHaveDescription(expect.stringContaining('partial')) +customExpect(element).toHaveDescription() +customExpect(element).toHaveAccessibleDescription('some description') +customExpect(element).toHaveAccessibleDescription(/some description/) +customExpect(element).toHaveAccessibleDescription( + expect.stringContaining('partial'), +) +customExpect(element).toHaveAccessibleDescription() + +customExpect(element).toHaveAccessibleErrorMessage() +customExpect(element).toHaveAccessibleErrorMessage( + 'Invalid time: the time must be between 9:00 AM and 5:00 PM', +) +customExpect(element).toHaveAccessibleErrorMessage(/invalid time/i) +customExpect(element).toHaveAccessibleErrorMessage( + expect.stringContaining('Invalid time'), +) + +customExpect(element).toHaveAccessibleName('a label') +customExpect(element).toHaveAccessibleName(/a label/) +customExpect(element).toHaveAccessibleName( + expect.stringContaining('partial label'), +) +customExpect(element).toHaveAccessibleName() +customExpect(element).toHaveErrorMessage( + 'Invalid time: the time must be between 9:00 AM and 5:00 PM', +) +customExpect(element).toHaveErrorMessage(/invalid time/i) +customExpect(element).toHaveErrorMessage( + expect.stringContaining('Invalid time'), +) + +// @ts-expect-error The types accidentally allowed any property by falling back to "any" +customExpect(element).nonExistentProperty() diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest-globals/jest-globals-types.test.ts b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest-globals/jest-globals-types.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..150f82507ad9f1097202bc847f0c0cb61fb597be --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest-globals/jest-globals-types.test.ts @@ -0,0 +1,120 @@ +/** + * File that tests whether the TypeScript typings for @types/jest work as expected. + */ + +/* eslint-disable @typescript-eslint/no-unsafe-call */ +/* eslint-disable @typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-unsafe-argument */ + +import {expect} from '@jest/globals' +import '../../jest-globals' + +const element: HTMLElement = document.body + +expect(element).toBeInTheDOM() +expect(element).toBeInTheDOM(document.body) +expect(element).toBeInTheDocument() +expect(element).toBeVisible() +expect(element).toBeEmpty() +expect(element).toBeDisabled() +expect(element).toBeEnabled() +expect(element).toBeInvalid() +expect(element).toBeRequired() +expect(element).toBeValid() +expect(element).toContainElement(document.body) +expect(element).toContainElement(null) +expect(element).toContainHTML('body') +expect(element).toHaveAttribute('attr') +expect(element).toHaveAttribute('attr', true) +expect(element).toHaveAttribute('attr', 'yes') +expect(element).toHaveClass() +expect(element).toHaveClass('cls1') +expect(element).toHaveClass('cls1', 'cls2', 'cls3', 'cls4') +expect(element).toHaveClass('cls1', {exact: true}) +expect(element).toHaveDisplayValue('str') +expect(element).toHaveDisplayValue(['str1', 'str2']) +expect(element).toHaveDisplayValue(/str/) +expect(element).toHaveDisplayValue([/str1/, 'str2']) +expect(element).toHaveFocus() +expect(element).toHaveFormValues({foo: 'bar', baz: 1}) +expect(element).toHaveStyle('display: block') +expect(element).toHaveStyle({display: 'block', width: 100}) +expect(element).toHaveTextContent('Text') +expect(element).toHaveTextContent(/Text/) +expect(element).toHaveTextContent('Text', {normalizeWhitespace: true}) +expect(element).toHaveTextContent(/Text/, {normalizeWhitespace: true}) +expect(element).toHaveValue() +expect(element).toHaveValue('str') +expect(element).toHaveValue(['str1', 'str2']) +expect(element).toHaveValue(1) +expect(element).toHaveValue(null) +expect(element).toBeChecked() +expect(element).toHaveDescription('some description') +expect(element).toHaveDescription(/some description/) +expect(element).toHaveDescription(expect.stringContaining('partial')) +expect(element).toHaveDescription() +expect(element).toHaveAccessibleDescription('some description') +expect(element).toHaveAccessibleDescription(/some description/) +expect(element).toHaveAccessibleDescription(expect.stringContaining('partial')) +expect(element).toHaveAccessibleDescription() +expect(element).toHaveAccessibleName('a label') +expect(element).toHaveAccessibleName(/a label/) +expect(element).toHaveAccessibleName(expect.stringContaining('partial label')) +expect(element).toHaveAccessibleName() +expect(element).toHaveErrorMessage( + 'Invalid time: the time must be between 9:00 AM and 5:00 PM', +) +expect(element).toHaveErrorMessage(/invalid time/i) +expect(element).toHaveErrorMessage(expect.stringContaining('Invalid time')) +expect(element).toHaveRole('button') + +expect(element).not.toBeInTheDOM() +expect(element).not.toBeInTheDOM(document.body) +expect(element).not.toBeInTheDocument() +expect(element).not.toBeVisible() +expect(element).not.toBeEmpty() +expect(element).not.toBeEmptyDOMElement() +expect(element).not.toBeDisabled() +expect(element).not.toBeEnabled() +expect(element).not.toBeInvalid() +expect(element).not.toBeRequired() +expect(element).not.toBeValid() +expect(element).not.toContainElement(document.body) +expect(element).not.toContainElement(null) +expect(element).not.toContainHTML('body') +expect(element).not.toHaveAttribute('attr') +expect(element).not.toHaveAttribute('attr', true) +expect(element).not.toHaveAttribute('attr', 'yes') +expect(element).not.toHaveClass() +expect(element).not.toHaveClass('cls1') +expect(element).not.toHaveClass('cls1', 'cls2', 'cls3', 'cls4') +expect(element).not.toHaveClass('cls1', {exact: true}) +expect(element).not.toHaveDisplayValue('str') +expect(element).not.toHaveDisplayValue(['str1', 'str2']) +expect(element).not.toHaveDisplayValue(/str/) +expect(element).not.toHaveDisplayValue([/str1/, 'str2']) +expect(element).not.toHaveFocus() +expect(element).not.toHaveFormValues({foo: 'bar', baz: 1}) +expect(element).not.toHaveStyle('display: block') +expect(element).not.toHaveTextContent('Text') +expect(element).not.toHaveTextContent(/Text/) +expect(element).not.toHaveTextContent('Text', {normalizeWhitespace: true}) +expect(element).not.toHaveTextContent(/Text/, {normalizeWhitespace: true}) +expect(element).not.toHaveValue() +expect(element).not.toHaveValue('str') +expect(element).not.toHaveValue(['str1', 'str2']) +expect(element).not.toHaveValue(1) +expect(element).not.toBeChecked() +expect(element).not.toHaveDescription('some description') +expect(element).not.toHaveDescription() +expect(element).not.toHaveAccessibleDescription('some description') +expect(element).not.toHaveAccessibleDescription() +expect(element).not.toHaveAccessibleName('a label') +expect(element).not.toHaveAccessibleName() +expect(element).not.toBePartiallyChecked() +expect(element).not.toHaveErrorMessage() +expect(element).not.toHaveErrorMessage('Pikachu!') +expect(element).not.toHaveRole('button') + +// @ts-expect-error The types accidentally allowed any property by falling back to "any" +expect(element).nonExistentProperty() diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest-globals/tsconfig.json b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest-globals/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..25a9cf272b9ba06c0d18c36a03ff76b3ea272f79 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest-globals/tsconfig.json @@ -0,0 +1,9 @@ +{ + "compilerOptions": { + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "types": [] + }, + "include": ["*.ts"] +} diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest/jest-custom-expect-types.test.ts b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest/jest-custom-expect-types.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b64b8e5cc19dbd9daaa9d24276dfd41bdc7056f --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest/jest-custom-expect-types.test.ts @@ -0,0 +1,100 @@ +/** + * File that tests whether the TypeScript typings work as expected. + */ + +/* eslint-disable @typescript-eslint/no-unsafe-call */ +/* eslint-disable @typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-unsafe-argument */ + +import * as matchers from '../../matchers' + +expect.extend(matchers) + +const element: HTMLElement = document.body + +function customExpect( + _actual: HTMLElement, +): + | matchers.TestingLibraryMatchers + | matchers.TestingLibraryMatchers> { + throw new Error('Method not implemented.') +} + +customExpect(element).toBeInTheDOM() +customExpect(element).toBeInTheDOM(document.body) +customExpect(element).toBeInTheDocument() +customExpect(element).toBeVisible() +customExpect(element).toBeEmpty() +customExpect(element).toBeDisabled() +customExpect(element).toBeEnabled() +customExpect(element).toBeInvalid() +customExpect(element).toBeRequired() +customExpect(element).toBeValid() +customExpect(element).toContainElement(document.body) +customExpect(element).toContainElement(null) +customExpect(element).toContainHTML('body') +customExpect(element).toHaveAttribute('attr') +customExpect(element).toHaveAttribute('attr', true) +customExpect(element).toHaveAttribute('attr', 'yes') +customExpect(element).toHaveClass() +customExpect(element).toHaveClass('cls1') +customExpect(element).toHaveClass(/cls/) +customExpect(element).toHaveClass('cls1', 'cls2', /cls(3|4)/) +customExpect(element).toHaveClass('cls1', {exact: true}) +customExpect(element).toHaveDisplayValue('str') +customExpect(element).toHaveDisplayValue(['str1', 'str2']) +customExpect(element).toHaveDisplayValue(/str/) +customExpect(element).toHaveDisplayValue([/str1/, 'str2']) +customExpect(element).toHaveFocus() +customExpect(element).toHaveFormValues({foo: 'bar', baz: 1}) +customExpect(element).toHaveStyle('display: block') +customExpect(element).toHaveStyle({display: 'block', width: 100}) +customExpect(element).toHaveTextContent('Text') +customExpect(element).toHaveTextContent(/Text/) +customExpect(element).toHaveTextContent('Text', {normalizeWhitespace: true}) +customExpect(element).toHaveTextContent(/Text/, {normalizeWhitespace: true}) +customExpect(element).toHaveValue() +customExpect(element).toHaveValue('str') +customExpect(element).toHaveValue(['str1', 'str2']) +customExpect(element).toHaveValue(1) +customExpect(element).toHaveValue(null) +customExpect(element).toBeChecked() +customExpect(element).toHaveDescription('some description') +customExpect(element).toHaveDescription(/some description/) +customExpect(element).toHaveDescription(expect.stringContaining('partial')) +customExpect(element).toHaveDescription() +customExpect(element).toHaveAccessibleDescription('some description') +customExpect(element).toHaveAccessibleDescription(/some description/) +customExpect(element).toHaveAccessibleDescription( + expect.stringContaining('partial'), +) +customExpect(element).toHaveAccessibleDescription() + +customExpect(element).toHaveAccessibleErrorMessage() +customExpect(element).toHaveAccessibleErrorMessage( + 'Invalid time: the time must be between 9:00 AM and 5:00 PM', +) +customExpect(element).toHaveAccessibleErrorMessage(/invalid time/i) +customExpect(element).toHaveAccessibleErrorMessage( + expect.stringContaining('Invalid time'), +) + +customExpect(element).toHaveAccessibleName('a label') +customExpect(element).toHaveAccessibleName(/a label/) +customExpect(element).toHaveAccessibleName( + expect.stringContaining('partial label'), +) +customExpect(element).toHaveAccessibleName() +customExpect(element).toHaveErrorMessage( + 'Invalid time: the time must be between 9:00 AM and 5:00 PM', +) +customExpect(element).toHaveErrorMessage(/invalid time/i) +customExpect(element).toHaveErrorMessage( + expect.stringContaining('Invalid time'), +) + +// @ts-expect-error The types accidentally allowed any property by falling back to "any" +customExpect(element).nonExistentProperty() + +// @ts-expect-error +customExpect(element).toHaveClass(/cls/, {exact: true}) diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest/jest-types.test.ts b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest/jest-types.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d9596c6700f3c92c6c03025b2af0e13c04958fef --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest/jest-types.test.ts @@ -0,0 +1,119 @@ +/** + * File that tests whether the TypeScript typings for @types/jest work as expected. + */ + +/* eslint-disable @typescript-eslint/no-unsafe-call */ +/* eslint-disable @typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-unsafe-argument */ + +import '../../jest' + +const element: HTMLElement = document.body + +expect(element).toBeInTheDOM() +expect(element).toBeInTheDOM(document.body) +expect(element).toBeInTheDocument() +expect(element).toBeVisible() +expect(element).toBeEmpty() +expect(element).toBeDisabled() +expect(element).toBeEnabled() +expect(element).toBeInvalid() +expect(element).toBeRequired() +expect(element).toBeValid() +expect(element).toContainElement(document.body) +expect(element).toContainElement(null) +expect(element).toContainHTML('body') +expect(element).toHaveAttribute('attr') +expect(element).toHaveAttribute('attr', true) +expect(element).toHaveAttribute('attr', 'yes') +expect(element).toHaveClass() +expect(element).toHaveClass('cls1') +expect(element).toHaveClass('cls1', 'cls2', 'cls3', 'cls4') +expect(element).toHaveClass('cls1', {exact: true}) +expect(element).toHaveDisplayValue('str') +expect(element).toHaveDisplayValue(['str1', 'str2']) +expect(element).toHaveDisplayValue(/str/) +expect(element).toHaveDisplayValue([/str1/, 'str2']) +expect(element).toHaveFocus() +expect(element).toHaveFormValues({foo: 'bar', baz: 1}) +expect(element).toHaveStyle('display: block') +expect(element).toHaveStyle({display: 'block', width: 100}) +expect(element).toHaveTextContent('Text') +expect(element).toHaveTextContent(/Text/) +expect(element).toHaveTextContent('Text', {normalizeWhitespace: true}) +expect(element).toHaveTextContent(/Text/, {normalizeWhitespace: true}) +expect(element).toHaveValue() +expect(element).toHaveValue('str') +expect(element).toHaveValue(['str1', 'str2']) +expect(element).toHaveValue(1) +expect(element).toHaveValue(null) +expect(element).toBeChecked() +expect(element).toHaveDescription('some description') +expect(element).toHaveDescription(/some description/) +expect(element).toHaveDescription(expect.stringContaining('partial')) +expect(element).toHaveDescription() +expect(element).toHaveAccessibleDescription('some description') +expect(element).toHaveAccessibleDescription(/some description/) +expect(element).toHaveAccessibleDescription(expect.stringContaining('partial')) +expect(element).toHaveAccessibleDescription() +expect(element).toHaveAccessibleName('a label') +expect(element).toHaveAccessibleName(/a label/) +expect(element).toHaveAccessibleName(expect.stringContaining('partial label')) +expect(element).toHaveAccessibleName() +expect(element).toHaveErrorMessage( + 'Invalid time: the time must be between 9:00 AM and 5:00 PM', +) +expect(element).toHaveErrorMessage(/invalid time/i) +expect(element).toHaveErrorMessage(expect.stringContaining('Invalid time')) +expect(element).toHaveRole('button') + +expect(element).not.toBeInTheDOM() +expect(element).not.toBeInTheDOM(document.body) +expect(element).not.toBeInTheDocument() +expect(element).not.toBeVisible() +expect(element).not.toBeEmpty() +expect(element).not.toBeEmptyDOMElement() +expect(element).not.toBeDisabled() +expect(element).not.toBeEnabled() +expect(element).not.toBeInvalid() +expect(element).not.toBeRequired() +expect(element).not.toBeValid() +expect(element).not.toContainElement(document.body) +expect(element).not.toContainElement(null) +expect(element).not.toContainHTML('body') +expect(element).not.toHaveAttribute('attr') +expect(element).not.toHaveAttribute('attr', true) +expect(element).not.toHaveAttribute('attr', 'yes') +expect(element).not.toHaveClass() +expect(element).not.toHaveClass('cls1') +expect(element).not.toHaveClass('cls1', 'cls2', 'cls3', 'cls4') +expect(element).not.toHaveClass('cls1', {exact: true}) +expect(element).not.toHaveDisplayValue('str') +expect(element).not.toHaveDisplayValue(['str1', 'str2']) +expect(element).not.toHaveDisplayValue(/str/) +expect(element).not.toHaveDisplayValue([/str1/, 'str2']) +expect(element).not.toHaveFocus() +expect(element).not.toHaveFormValues({foo: 'bar', baz: 1}) +expect(element).not.toHaveStyle('display: block') +expect(element).not.toHaveTextContent('Text') +expect(element).not.toHaveTextContent(/Text/) +expect(element).not.toHaveTextContent('Text', {normalizeWhitespace: true}) +expect(element).not.toHaveTextContent(/Text/, {normalizeWhitespace: true}) +expect(element).not.toHaveValue() +expect(element).not.toHaveValue('str') +expect(element).not.toHaveValue(['str1', 'str2']) +expect(element).not.toHaveValue(1) +expect(element).not.toBeChecked() +expect(element).not.toHaveDescription('some description') +expect(element).not.toHaveDescription() +expect(element).not.toHaveAccessibleDescription('some description') +expect(element).not.toHaveAccessibleDescription() +expect(element).not.toHaveAccessibleName('a label') +expect(element).not.toHaveAccessibleName() +expect(element).not.toBePartiallyChecked() +expect(element).not.toHaveErrorMessage() +expect(element).not.toHaveErrorMessage('Pikachu!') +expect(element).not.toHaveRole('button') + +// @ts-expect-error The types accidentally allowed any property by falling back to "any" +expect(element).nonExistentProperty() diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest/tsconfig.json b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..52ecd5d4fb74a834d53b1f114f28bba5f41903c4 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/jest/tsconfig.json @@ -0,0 +1,9 @@ +{ + "compilerOptions": { + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "types": ["jest"] + }, + "include": ["*.ts"] +} diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/vitest/tsconfig.json b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/vitest/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..25a9cf272b9ba06c0d18c36a03ff76b3ea272f79 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/vitest/tsconfig.json @@ -0,0 +1,9 @@ +{ + "compilerOptions": { + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "types": [] + }, + "include": ["*.ts"] +} diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/vitest/vitest-custom-expect-types.test.ts b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/vitest/vitest-custom-expect-types.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9008966c020bb4b6849732ee6e6f3b36a866c47 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/vitest/vitest-custom-expect-types.test.ts @@ -0,0 +1,97 @@ +/** + * File that tests whether the TypeScript typings work as expected. + */ + +/* eslint-disable @typescript-eslint/no-unsafe-call */ +/* eslint-disable @typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-unsafe-argument */ + +import {expect} from 'vitest' +import * as matchers from '../../matchers' + +expect.extend(matchers) + +const element: HTMLElement = document.body + +function customExpect( + _actual: HTMLElement, +): + | matchers.TestingLibraryMatchers + | matchers.TestingLibraryMatchers> { + throw new Error('Method not implemented.') +} + +customExpect(element).toBeInTheDOM() +customExpect(element).toBeInTheDOM(document.body) +customExpect(element).toBeInTheDocument() +customExpect(element).toBeVisible() +customExpect(element).toBeEmpty() +customExpect(element).toBeDisabled() +customExpect(element).toBeEnabled() +customExpect(element).toBeInvalid() +customExpect(element).toBeRequired() +customExpect(element).toBeValid() +customExpect(element).toContainElement(document.body) +customExpect(element).toContainElement(null) +customExpect(element).toContainHTML('body') +customExpect(element).toHaveAttribute('attr') +customExpect(element).toHaveAttribute('attr', true) +customExpect(element).toHaveAttribute('attr', 'yes') +customExpect(element).toHaveClass() +customExpect(element).toHaveClass('cls1') +customExpect(element).toHaveClass('cls1', 'cls2', 'cls3', 'cls4') +customExpect(element).toHaveClass('cls1', {exact: true}) +customExpect(element).toHaveDisplayValue('str') +customExpect(element).toHaveDisplayValue(['str1', 'str2']) +customExpect(element).toHaveDisplayValue(/str/) +customExpect(element).toHaveDisplayValue([/str1/, 'str2']) +customExpect(element).toHaveFocus() +customExpect(element).toHaveFormValues({foo: 'bar', baz: 1}) +customExpect(element).toHaveStyle('display: block') +customExpect(element).toHaveStyle({display: 'block', width: 100}) +customExpect(element).toHaveTextContent('Text') +customExpect(element).toHaveTextContent(/Text/) +customExpect(element).toHaveTextContent('Text', {normalizeWhitespace: true}) +customExpect(element).toHaveTextContent(/Text/, {normalizeWhitespace: true}) +customExpect(element).toHaveValue() +customExpect(element).toHaveValue('str') +customExpect(element).toHaveValue(['str1', 'str2']) +customExpect(element).toHaveValue(1) +customExpect(element).toHaveValue(null) +customExpect(element).toBeChecked() +customExpect(element).toHaveDescription('some description') +customExpect(element).toHaveDescription(/some description/) +customExpect(element).toHaveDescription(expect.stringContaining('partial')) +customExpect(element).toHaveDescription() +customExpect(element).toHaveAccessibleDescription('some description') +customExpect(element).toHaveAccessibleDescription(/some description/) +customExpect(element).toHaveAccessibleDescription( + expect.stringContaining('partial'), +) +customExpect(element).toHaveAccessibleDescription() + +customExpect(element).toHaveAccessibleErrorMessage() +customExpect(element).toHaveAccessibleErrorMessage( + 'Invalid time: the time must be between 9:00 AM and 5:00 PM', +) +customExpect(element).toHaveAccessibleErrorMessage(/invalid time/i) +customExpect(element).toHaveAccessibleErrorMessage( + expect.stringContaining('Invalid time'), +) + +customExpect(element).toHaveAccessibleName('a label') +customExpect(element).toHaveAccessibleName(/a label/) +customExpect(element).toHaveAccessibleName( + expect.stringContaining('partial label'), +) +customExpect(element).toHaveAccessibleName() +customExpect(element).toHaveErrorMessage( + 'Invalid time: the time must be between 9:00 AM and 5:00 PM', +) +customExpect(element).toHaveErrorMessage(/invalid time/i) +customExpect(element).toHaveErrorMessage( + expect.stringContaining('Invalid time'), +) + +// @ts-expect-error The types accidentally allowed any property by falling back to "any" +customExpect(element).nonExistentProperty() diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/vitest/vitest-types.test.ts b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/vitest/vitest-types.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..7a90be05211f228149420f49a52cd2e0a7bfc259 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/__tests__/vitest/vitest-types.test.ts @@ -0,0 +1,120 @@ +/** + * File that tests whether the TypeScript typings for @types/jest work as expected. + */ + +/* eslint-disable @typescript-eslint/no-unsafe-call */ +/* eslint-disable @typescript-eslint/no-floating-promises */ +/* eslint-disable @typescript-eslint/no-unsafe-argument */ + +import {expect} from 'vitest' +import '../../vitest' + +const element: HTMLElement = document.body + +expect(element).toBeInTheDOM() +expect(element).toBeInTheDOM(document.body) +expect(element).toBeInTheDocument() +expect(element).toBeVisible() +expect(element).toBeEmpty() +expect(element).toBeDisabled() +expect(element).toBeEnabled() +expect(element).toBeInvalid() +expect(element).toBeRequired() +expect(element).toBeValid() +expect(element).toContainElement(document.body) +expect(element).toContainElement(null) +expect(element).toContainHTML('body') +expect(element).toHaveAttribute('attr') +expect(element).toHaveAttribute('attr', true) +expect(element).toHaveAttribute('attr', 'yes') +expect(element).toHaveClass() +expect(element).toHaveClass('cls1') +expect(element).toHaveClass('cls1', 'cls2', 'cls3', 'cls4') +expect(element).toHaveClass('cls1', {exact: true}) +expect(element).toHaveDisplayValue('str') +expect(element).toHaveDisplayValue(['str1', 'str2']) +expect(element).toHaveDisplayValue(/str/) +expect(element).toHaveDisplayValue([/str1/, 'str2']) +expect(element).toHaveFocus() +expect(element).toHaveFormValues({foo: 'bar', baz: 1}) +expect(element).toHaveStyle('display: block') +expect(element).toHaveStyle({display: 'block', width: 100}) +expect(element).toHaveTextContent('Text') +expect(element).toHaveTextContent(/Text/) +expect(element).toHaveTextContent('Text', {normalizeWhitespace: true}) +expect(element).toHaveTextContent(/Text/, {normalizeWhitespace: true}) +expect(element).toHaveValue() +expect(element).toHaveValue('str') +expect(element).toHaveValue(['str1', 'str2']) +expect(element).toHaveValue(1) +expect(element).toHaveValue(null) +expect(element).toBeChecked() +expect(element).toHaveDescription('some description') +expect(element).toHaveDescription(/some description/) +expect(element).toHaveDescription(expect.stringContaining('partial')) +expect(element).toHaveDescription() +expect(element).toHaveAccessibleDescription('some description') +expect(element).toHaveAccessibleDescription(/some description/) +expect(element).toHaveAccessibleDescription(expect.stringContaining('partial')) +expect(element).toHaveAccessibleDescription() +expect(element).toHaveAccessibleName('a label') +expect(element).toHaveAccessibleName(/a label/) +expect(element).toHaveAccessibleName(expect.stringContaining('partial label')) +expect(element).toHaveAccessibleName() +expect(element).toHaveErrorMessage( + 'Invalid time: the time must be between 9:00 AM and 5:00 PM', +) +expect(element).toHaveErrorMessage(/invalid time/i) +expect(element).toHaveErrorMessage(expect.stringContaining('Invalid time')) +expect(element).toHaveRole('button') + +expect(element).not.toBeInTheDOM() +expect(element).not.toBeInTheDOM(document.body) +expect(element).not.toBeInTheDocument() +expect(element).not.toBeVisible() +expect(element).not.toBeEmpty() +expect(element).not.toBeEmptyDOMElement() +expect(element).not.toBeDisabled() +expect(element).not.toBeEnabled() +expect(element).not.toBeInvalid() +expect(element).not.toBeRequired() +expect(element).not.toBeValid() +expect(element).not.toContainElement(document.body) +expect(element).not.toContainElement(null) +expect(element).not.toContainHTML('body') +expect(element).not.toHaveAttribute('attr') +expect(element).not.toHaveAttribute('attr', true) +expect(element).not.toHaveAttribute('attr', 'yes') +expect(element).not.toHaveClass() +expect(element).not.toHaveClass('cls1') +expect(element).not.toHaveClass('cls1', 'cls2', 'cls3', 'cls4') +expect(element).not.toHaveClass('cls1', {exact: true}) +expect(element).not.toHaveDisplayValue('str') +expect(element).not.toHaveDisplayValue(['str1', 'str2']) +expect(element).not.toHaveDisplayValue(/str/) +expect(element).not.toHaveDisplayValue([/str1/, 'str2']) +expect(element).not.toHaveFocus() +expect(element).not.toHaveFormValues({foo: 'bar', baz: 1}) +expect(element).not.toHaveStyle('display: block') +expect(element).not.toHaveTextContent('Text') +expect(element).not.toHaveTextContent(/Text/) +expect(element).not.toHaveTextContent('Text', {normalizeWhitespace: true}) +expect(element).not.toHaveTextContent(/Text/, {normalizeWhitespace: true}) +expect(element).not.toHaveValue() +expect(element).not.toHaveValue('str') +expect(element).not.toHaveValue(['str1', 'str2']) +expect(element).not.toHaveValue(1) +expect(element).not.toBeChecked() +expect(element).not.toHaveDescription('some description') +expect(element).not.toHaveDescription() +expect(element).not.toHaveAccessibleDescription('some description') +expect(element).not.toHaveAccessibleDescription() +expect(element).not.toHaveAccessibleName('a label') +expect(element).not.toHaveAccessibleName() +expect(element).not.toBePartiallyChecked() +expect(element).not.toHaveErrorMessage() +expect(element).not.toHaveErrorMessage('Pikachu!') +expect(element).not.toHaveRole('button') + +// @ts-expect-error The types accidentally allowed any property by falling back to "any" +expect(element).nonExistentProperty() diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/bun.d.ts b/tools/ui/node_modules/@testing-library/jest-dom/types/bun.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..676a0ac380194fb2e091b71e6273c4344a52eb5a --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/bun.d.ts @@ -0,0 +1,11 @@ +import {type expect} from 'bun:test' +import {type TestingLibraryMatchers} from './matchers' + +export {} +declare module 'bun:test' { + interface Matchers + extends TestingLibraryMatchers< + ReturnType, + T + > {} +} diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/index.d.ts b/tools/ui/node_modules/@testing-library/jest-dom/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cebdd1afd72962fa9a197a675bf18112f705cb17 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/index.d.ts @@ -0,0 +1 @@ +/// diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/jest-globals.d.ts b/tools/ui/node_modules/@testing-library/jest-dom/types/jest-globals.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a6819079afe0717892ef711539ee8f13a4a13582 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/jest-globals.d.ts @@ -0,0 +1,11 @@ +import {type expect} from '@jest/globals' +import {type TestingLibraryMatchers} from './matchers' + +export {} +declare module '@jest/expect' { + export interface Matchers> + extends TestingLibraryMatchers< + ReturnType, + R + > {} +} diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/jest.d.ts b/tools/ui/node_modules/@testing-library/jest-dom/types/jest.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1daed629d6baa21b4d92d914b1679858b94fcff0 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/jest.d.ts @@ -0,0 +1,13 @@ +/// + +import {type TestingLibraryMatchers} from './matchers' + +declare global { + namespace jest { + interface Matchers + extends TestingLibraryMatchers< + ReturnType, + R + > {} + } +} diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/matchers-standalone.d.ts b/tools/ui/node_modules/@testing-library/jest-dom/types/matchers-standalone.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..175e91571296e7cc2d6432c3a648a03a7c0c620c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/matchers-standalone.d.ts @@ -0,0 +1,30 @@ +import {type TestingLibraryMatchers as _TLM} from './matchers' + +interface MatcherReturnType { + pass: boolean + message: () => string +} + +interface OverloadedMatchers { + toHaveClass(expected: any, ...rest: string[]) : MatcherReturnType + toHaveClass( + expected: any, + className: string, + options?: {exact: boolean}, + ) : MatcherReturnType +} + +declare namespace matchersStandalone { + type MatchersStandalone = { + [T in keyof _TLM]: ( + expected: any, + ...rest: Parameters<_TLM[T]> + ) => MatcherReturnType + } & OverloadedMatchers + + type TestingLibraryMatchers = _TLM +} + +declare const matchersStandalone: matchersStandalone.MatchersStandalone & + Record +export = matchersStandalone diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/matchers.d.ts b/tools/ui/node_modules/@testing-library/jest-dom/types/matchers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..82de01dc4c68e89e590a098b2b61b299c55b910a --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/matchers.d.ts @@ -0,0 +1,860 @@ +import {type ARIARole} from 'aria-query' + +declare namespace matchers { + interface TestingLibraryMatchers { + /** + * @deprecated + * since v1.9.0 + * @description + * Assert whether a value is a DOM element, or not. Contrary to what its name implies, this matcher only checks + * that you passed to it a valid DOM element. + * + * It does not have a clear definition of what "the DOM" is. Therefore, it does not check whether that element + * is contained anywhere. + * @see + * [testing-library/jest-dom#toBeInTheDom](https://github.com/testing-library/jest-dom#toBeInTheDom) + */ + toBeInTheDOM(container?: HTMLElement | SVGElement): R + /** + * @description + * Assert whether an element is present in the document or not. + * @example + * + * + * expect(queryByTestId('svg-element')).toBeInTheDocument() + * expect(queryByTestId('does-not-exist')).not.toBeInTheDocument() + * @see + * [testing-library/jest-dom#tobeinthedocument](https://github.com/testing-library/jest-dom#tobeinthedocument) + */ + toBeInTheDocument(): R + /** + * @description + * This allows you to check if an element is currently visible to the user. + * + * An element is visible if **all** the following conditions are met: + * * it does not have its css property display set to none + * * it does not have its css property visibility set to either hidden or collapse + * * it does not have its css property opacity set to 0 + * * its parent element is also visible (and so on up to the top of the DOM tree) + * * it does not have the hidden attribute + * * if `
` it has the open attribute + * @example + *
+ * Zero Opacity + *
+ * + *
Visible Example
+ * + * expect(getByTestId('zero-opacity')).not.toBeVisible() + * expect(getByTestId('visible')).toBeVisible() + * @see + * [testing-library/jest-dom#tobevisible](https://github.com/testing-library/jest-dom#tobevisible) + */ + toBeVisible(): R + /** + * @deprecated + * since v5.9.0 + * @description + * Assert whether an element has content or not. + * @example + * + * + * + * + * expect(getByTestId('empty')).toBeEmpty() + * expect(getByTestId('not-empty')).not.toBeEmpty() + * @see + * [testing-library/jest-dom#tobeempty](https://github.com/testing-library/jest-dom#tobeempty) + */ + toBeEmpty(): R + /** + * @description + * Assert whether an element has content or not. + * @example + * + * + * + * + * expect(getByTestId('empty')).toBeEmptyDOMElement() + * expect(getByTestId('not-empty')).not.toBeEmptyDOMElement() + * @see + * [testing-library/jest-dom#tobeemptydomelement](https://github.com/testing-library/jest-dom#tobeemptydomelement) + */ + toBeEmptyDOMElement(): R + /** + * @description + * Allows you to check whether an element is disabled from the user's perspective. + * + * Matches if the element is a form control and the `disabled` attribute is specified on this element or the + * element is a descendant of a form element with a `disabled` attribute. + * @example + * + * + * expect(getByTestId('button')).toBeDisabled() + * @see + * [testing-library/jest-dom#tobedisabled](https://github.com/testing-library/jest-dom#tobedisabled) + */ + toBeDisabled(): R + /** + * @description + * Allows you to check whether an element is not disabled from the user's perspective. + * + * Works like `not.toBeDisabled()`. + * + * Use this matcher to avoid double negation in your tests. + * @example + * + * + * expect(getByTestId('button')).toBeEnabled() + * @see + * [testing-library/jest-dom#tobeenabled](https://github.com/testing-library/jest-dom#tobeenabled) + */ + toBeEnabled(): R + /** + * @description + * Check if a form element, or the entire `form`, is currently invalid. + * + * An `input`, `select`, `textarea`, or `form` element is invalid if it has an `aria-invalid` attribute with no + * value or a value of "true", or if the result of `checkValidity()` is false. + * @example + * + * + *
+ * + *
+ * + * expect(getByTestId('no-aria-invalid')).not.toBeInvalid() + * expect(getByTestId('invalid-form')).toBeInvalid() + * @see + * [testing-library/jest-dom#tobeinvalid](https://github.com/testing-library/jest-dom#tobeinvalid) + */ + toBeInvalid(): R + /** + * @description + * This allows you to check if a form element is currently required. + * + * An element is required if it is having a `required` or `aria-required="true"` attribute. + * @example + * + *
+ * + * expect(getByTestId('required-input')).toBeRequired() + * expect(getByTestId('supported-role')).not.toBeRequired() + * @see + * [testing-library/jest-dom#toberequired](https://github.com/testing-library/jest-dom#toberequired) + */ + toBeRequired(): R + /** + * @description + * Allows you to check if a form element is currently required. + * + * An `input`, `select`, `textarea`, or `form` element is invalid if it has an `aria-invalid` attribute with no + * value or a value of "false", or if the result of `checkValidity()` is true. + * @example + * + * + *
+ * + *
+ * + * expect(getByTestId('no-aria-invalid')).not.toBeValid() + * expect(getByTestId('invalid-form')).toBeInvalid() + * @see + * [testing-library/jest-dom#tobevalid](https://github.com/testing-library/jest-dom#tobevalid) + */ + toBeValid(): R + /** + * @description + * Allows you to assert whether an element contains another element as a descendant or not. + * @example + * + * + * + * + * const ancestor = getByTestId('ancestor') + * const descendant = getByTestId('descendant') + * const nonExistantElement = getByTestId('does-not-exist') + * expect(ancestor).toContainElement(descendant) + * expect(descendant).not.toContainElement(ancestor) + * expect(ancestor).not.toContainElement(nonExistantElement) + * @see + * [testing-library/jest-dom#tocontainelement](https://github.com/testing-library/jest-dom#tocontainelement) + */ + toContainElement(element: HTMLElement | SVGElement | null): R + /** + * @description + * Assert whether a string representing a HTML element is contained in another element. + * @example + * + * + * expect(getByTestId('parent')).toContainHTML('') + * @see + * [testing-library/jest-dom#tocontainhtml](https://github.com/testing-library/jest-dom#tocontainhtml) + */ + toContainHTML(htmlText: string): R + /** + * @description + * Allows you to check if a given element has an attribute or not. + * + * You can also optionally check that the attribute has a specific expected value or partial match using + * [expect.stringContaining](https://jestjs.io/docs/en/expect.html#expectnotstringcontainingstring) or + * [expect.stringMatching](https://jestjs.io/docs/en/expect.html#expectstringmatchingstring-regexp). + * @example + * + * + * expect(button).toHaveAttribute('disabled') + * expect(button).toHaveAttribute('type', 'submit') + * expect(button).not.toHaveAttribute('type', 'button') + * @see + * [testing-library/jest-dom#tohaveattribute](https://github.com/testing-library/jest-dom#tohaveattribute) + */ + toHaveAttribute(attr: string, value?: unknown): R + /** + * @description + * Check whether the given element has certain classes within its `class` attribute. + * + * You must provide at least one class, unless you are asserting that an element does not have any classes. + * @example + * + * + *
no classes
+ * + * const deleteButton = getByTestId('delete-button') + * const noClasses = getByTestId('no-classes') + * expect(deleteButton).toHaveClass('btn') + * expect(deleteButton).toHaveClass('btn-danger xs') + * expect(deleteButton).toHaveClass(/danger/, 'xs') + * expect(deleteButton).toHaveClass('btn xs btn-danger', {exact: true}) + * expect(deleteButton).not.toHaveClass('btn xs btn-danger', {exact: true}) + * expect(noClasses).not.toHaveClass() + * @see + * [testing-library/jest-dom#tohaveclass](https://github.com/testing-library/jest-dom#tohaveclass) + */ + toHaveClass(...classNames: Array): R + toHaveClass(classNames: string, options?: {exact: boolean}): R + /** + * @description + * This allows you to check whether the given form element has the specified displayed value (the one the + * end user will see). It accepts , + * + * + * + * + * + * + * + * const input = screen.getByLabelText('First name') + * const textarea = screen.getByLabelText('Description') + * const selectSingle = screen.getByLabelText('Fruit') + * const selectMultiple = screen.getByLabelText('Fruits') + * + * expect(input).toHaveDisplayValue('Luca') + * expect(textarea).toHaveDisplayValue('An example description here.') + * expect(selectSingle).toHaveDisplayValue('Select a fruit...') + * expect(selectMultiple).toHaveDisplayValue(['Banana', 'Avocado']) + * + * @see + * [testing-library/jest-dom#tohavedisplayvalue](https://github.com/testing-library/jest-dom#tohavedisplayvalue) + */ + toHaveDisplayValue(value: string | RegExp | Array): R + /** + * @description + * Assert whether an element has focus or not. + * @example + *
+ * + *
+ * + * const input = getByTestId('element-to-focus') + * input.focus() + * expect(input).toHaveFocus() + * input.blur() + * expect(input).not.toHaveFocus() + * @see + * [testing-library/jest-dom#tohavefocus](https://github.com/testing-library/jest-dom#tohavefocus) + */ + toHaveFocus(): R + /** + * @description + * Check if a form or fieldset contains form controls for each given name, and having the specified value. + * + * Can only be invoked on a form or fieldset element. + * @example + *
+ * + * + * + * + *
+ * + * expect(getByTestId('login-form')).toHaveFormValues({ + * username: 'jane.doe', + * rememberMe: true, + * }) + * @see + * [testing-library/jest-dom#tohaveformvalues](https://github.com/testing-library/jest-dom#tohaveformvalues) + */ + toHaveFormValues(expectedValues: Record): R + /** + * @description + * Check if an element has specific css properties with specific values applied. + * + * Only matches if the element has *all* the expected properties applied, not just some of them. + * @example + * + * + * const button = getByTestId('submit-button') + * expect(button).toHaveStyle('background-color: green') + * expect(button).toHaveStyle({ + * 'background-color': 'green', + * display: 'none' + * }) + * @see + * [testing-library/jest-dom#tohavestyle](https://github.com/testing-library/jest-dom#tohavestyle) + */ + toHaveStyle(css: string | Record): R + /** + * @description + * Check whether the given element has a text content or not. + * + * When a string argument is passed through, it will perform a partial case-sensitive match to the element + * content. + * + * To perform a case-insensitive match, you can use a RegExp with the `/i` modifier. + * + * If you want to match the whole content, you can use a RegExp to do it. + * @example + * Text Content + * + * const element = getByTestId('text-content') + * expect(element).toHaveTextContent('Content') + * // to match the whole content + * expect(element).toHaveTextContent(/^Text Content$/) + * // to use case-insentive match + * expect(element).toHaveTextContent(/content$/i) + * expect(element).not.toHaveTextContent('content') + * @see + * [testing-library/jest-dom#tohavetextcontent](https://github.com/testing-library/jest-dom#tohavetextcontent) + */ + toHaveTextContent( + text: string | RegExp, + options?: {normalizeWhitespace: boolean}, + ): R + /** + * @description + * Check whether the given form element has the specified value. + * + * Accepts ``, ` + *

prev

+ *

text selected text

+ *

next

+ *
+ * + * getByTestId('text').setSelectionRange(5, 13) + * expect(getByTestId('text')).toHaveSelection('selected') + * + * getByTestId('textarea').setSelectionRange(0, 5) + * expect('textarea').toHaveSelection('text ') + * + * const selection = document.getSelection() + * const range = document.createRange() + * selection.removeAllRanges() + * selection.empty() + * selection.addRange(range) + * + * // selection of child applies to the parent as well + * range.selectNodeContents(getByTestId('child')) + * expect(getByTestId('child')).toHaveSelection('selected') + * expect(getByTestId('parent')).toHaveSelection('selected') + * + * // selection that applies from prev all, parent text before child, and part child. + * range.setStart(getByTestId('prev'), 0) + * range.setEnd(getByTestId('child').childNodes[0], 3) + * expect(queryByTestId('prev')).toHaveSelection('prev') + * expect(queryByTestId('child')).toHaveSelection('sel') + * expect(queryByTestId('parent')).toHaveSelection('text sel') + * expect(queryByTestId('next')).not.toHaveSelection() + * + * // selection that applies from part child, parent text after child and part next. + * range.setStart(getByTestId('child').childNodes[0], 3) + * range.setEnd(getByTestId('next').childNodes[0], 2) + * expect(queryByTestId('child')).toHaveSelection('ected') + * expect(queryByTestId('parent')).toHaveSelection('ected text') + * expect(queryByTestId('prev')).not.toHaveSelection() + * expect(queryByTestId('next')).toHaveSelection('ne') + * + * @see + * [testing-library/jest-dom#tohaveselection](https://github.com/testing-library/jest-dom#tohaveselection) + */ + toHaveSelection(selection?: string): R + /* + * @description + * This allows to check whether given element has been [pressed](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-pressed) + * + * It accepts elements with explicit or implicit `button` role and valid `aria-pressed` + * attribute of `"true"` or `"false"`. + * + * @example + * + * + * + * + * + * + * Pressed span + * Released span + * + * screen.getByRole('button', { name: 'Pressed' }).toBePressed(); + * screen.getByRole('button', { name: 'Released' }).not.toBePressed(); + * + * screen.getByRole('button', { name: 'Pressed input button' }).toBePressed(); + * screen.getByRole('button', { name: 'Released input button' }).not.toBePressed(); + * + * screen.getByRole('button', { name: 'Pressed span' }).toBePressed(); + * screen.getByRole('button', { name: 'Released span' }).not.toBePressed(); + * + * @see + * [testing-library/jest-dom#tobepressed](https://github.com/testing-library/jest-dom#tobepressed) + */ + toBePressed(): R + /* + * @description + * This allows to check whether given element has been [partially pressed](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-pressed) + * + * It accepts elements with explicit or implicit `button` role and valid `aria-pressed` of `"mixed"`. + * + * @example + * + * + * Partially pressed span + * + * screen.getByRole('button', { name: 'Partially Pressed' }).toBePartiallyPressed(); + * screen.getByRole('button', { name: 'Partially pressed input button' }).toBePartiallyPressed(); + * screen.getByRole('button', { name: 'Partially pressed span' }).toBePartiallyPressed(); + * + * @See + * [testing-library/jest-dom#tobepartiallypressed](https://github.com/testing-library/jest-dom#tobepartiallypressed) + */ + toBePartiallyPressed(): R + /* + * @description + * This checks if a given element appears before another element in the DOM tree, as per [`compareDocumentPosition()`](https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition). + * + * @example + *
+ * Text A + * Text B + *
+ * + * const textA = queryByTestId('text-a') + * const textB = queryByTestId('text-b') + * + * expect(textA).toAppearBefore(textB) + * expect(textB).not.toAppearBefore(textA) + * + * @See + * [testing-library/jest-dom#toappearbefore](https://github.com/testing-library/jest-dom#toappearbefore) + */ + toAppearBefore(element: HTMLElement | SVGElement): R + /* + * @description + * This checks if a given element appears after another element in the DOM tree, as per [`compareDocumentPosition()`](https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition). + * + * @example + *
+ * Text A + * Text B + *
+ * + * const textA = queryByTestId('text-a') + * const textB = queryByTestId('text-b') + * + * expect(textB).toAppearAfter(textA) + * expect(textA).not.toAppearAfter(textB) + * + * @See + * [testing-library/jest-dom#toappearafter](https://github.com/testing-library/jest-dom#toappearafter) + */ + toAppearAfter(element: HTMLElement | SVGElement): R + } +} + +// Needs to extend Record to be accepted by expect.extend() +// as it requires a string index signature. +declare const matchers: matchers.TestingLibraryMatchers & + Record +export = matchers diff --git a/tools/ui/node_modules/@testing-library/jest-dom/types/vitest.d.ts b/tools/ui/node_modules/@testing-library/jest-dom/types/vitest.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ee9eb2f35d3f94c22d74b0177e82d92db56a979 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/types/vitest.d.ts @@ -0,0 +1,15 @@ +import 'vitest' +import {type TestingLibraryMatchers} from './matchers' + +declare module 'vitest' { + interface Assertion + extends TestingLibraryMatchers< + any, + T + > {} + interface AsymmetricMatchersContaining + extends TestingLibraryMatchers< + any, + any + > {} +} diff --git a/tools/ui/node_modules/@testing-library/jest-dom/vitest.d.ts b/tools/ui/node_modules/@testing-library/jest-dom/vitest.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b17a0d4abb8dd35fa5afd9a5ced2ffb0d27d547 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/vitest.d.ts @@ -0,0 +1 @@ +/// diff --git a/tools/ui/node_modules/@testing-library/jest-dom/vitest.js b/tools/ui/node_modules/@testing-library/jest-dom/vitest.js new file mode 100644 index 0000000000000000000000000000000000000000..e1f318c548a126d5135d7da7e7eed0ce7d60b865 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/jest-dom/vitest.js @@ -0,0 +1,4 @@ +import {expect} from 'vitest' +import * as extensions from './dist/matchers' + +expect.extend(extensions) diff --git a/tools/ui/node_modules/@testing-library/svelte-core/LICENSE b/tools/ui/node_modules/@testing-library/svelte-core/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5ca280c49d98b25b336a186772e2cc75ce12f1aa --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Ben Monro (https://github.com/benmonro) + +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. diff --git a/tools/ui/node_modules/@testing-library/svelte-core/README.md b/tools/ui/node_modules/@testing-library/svelte-core/README.md new file mode 100644 index 0000000000000000000000000000000000000000..174399a08ff0a7739d385b6734cbf1db81ba849c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/README.md @@ -0,0 +1,184 @@ +# @testing-library/svelte-core + +Do you want to build your own Svelte testing library? You may want to use our +rendering core, which abstracts away differences in Svelte versions to provide a +simple API to render Svelte components into the document and clean them up +afterwards. + +## Table of Contents + +- [Example Usage](#example-usage) +- [API](#api) + - [`render`](#render) + - [`setup`](#setup) + - [`mount`](#mount) + - [`cleanup`](#cleanup) + - [`addCleanupTask`](#addcleanuptask) + - [`removeCleanupTask`](#removecleanuptask) + - [Utility types](#utility-types) + +## Example Usage + +```ts +import { beforeEach } from 'vitest' +import * as SvelteCore from '@testing-library/svelte-core' +import type { + Component, + Exports, + Rerender, +} from '@testing-library/svelte-core/types' + +import { bindQueries, type Queries } from './bring-your-own-queries.js' + +beforeEach(() => { + SvelteCore.cleanup() +}) + +export interface RenderResult extends Queries { + container: HTMLElement + component: Exports + rerender: Rerender + unmount: () => void +} + +export const render = ( + Component: SvelteCore.ComponentImport, + options: SvelteCore.ComponentOptions +): RenderResult => { + const { baseElement, component, container, rerender, unmount } = + SvelteCore.render(Component, options) + + const queries = bindQueries(baseElement) + + return { component, container, rerender, unmount, ...queries } +} +``` + +## API + +### `render` + +Set up the document and mount a component into that document. + +```ts +const { baseElement, container, component, rerender, unmount } = render( + Component, + componentOptions, + setupOptions +) +``` + +| Argument | Type | Description | +| ------------------ | ------------------------------------------------------- | --------------------------------------------- | +| `Component` | [Svelte component][svelte-component-docs] | An imported Svelte component | +| `componentOptions` | `Props` or partial [`mount` options][svelte-mount-docs] | Options for how the component will be mounted | +| `setupOptions` | `{ baseElement?: HTMLElement }` | Optionally override `baseElement` | + +| Result | Type | Description | Default | +| ------------- | ------------------------------------------ | ---------------------------------------- | ----------------------------------- | +| `baseElement` | `HTMLElement` | The base element | `document.body` | +| `container` | `HTMLElement` | The component's immediate parent element | `
` appended to `document.body` | +| `component` | [component exports][svelte-mount-docs] | The component's exports from `mount` | N/A | +| `rerender` | `(props: Partial) => Promise` | Update the component's props | N/A | +| `unmount` | `() => void` | Unmount the component from the document | N/A | + +> \[!TIP] +> Calling `render` is equivalent to calling [`setup`](#setup) followed by [`mount`](#mount) +> +> ```ts +> const { baseElement, container, mountOptions } = setup( +> componentOptions, +> setupOptions +> ) +> const { component, rerender, unmount } = mount(Component, mountOptions) +> ``` + +[svelte-component-docs]: https://svelte.dev/docs/svelte-components +[svelte-mount-docs]: https://svelte.dev/docs/svelte/imperative-component-api#mount + +### `setup` + +Validate options and prepare document elements for rendering. + +```ts +const { baseElement, container, mountOptions } = setup( + componentOptions, + setupOptions +) +``` + +| Argument | Type | Description | +| ------------------ | ------------------------------------------------------- | --------------------------------------------- | +| `componentOptions` | `Props` or partial [`mount` options][svelte-mount-docs] | Options for how the component will be mounted | +| `setupOptions` | `{ baseElement?: HTMLElement }` | Optionally override `baseElement` | + +| Result | Type | Description | Default | +| -------------- | ------------------------------------ | ---------------------------------------- | ----------------------------------- | +| `baseElement` | `HTMLElement` | The base element | `document.body` | +| `container` | `HTMLElement` | The component's immediate parent element | `
` appended to `document.body` | +| `mountOptions` | [`mount` options][svelte-mount-docs] | Validated options to pass to `mount` | `{ target, props: {} }` | + +### `mount` + +Mount a Svelte component into the document. + +```ts +const { component, unmount, rerender } = mount(Component, mountOptions) +``` + +| Argument | Type | Description | +| -------------- | ----------------------------------------- | -------------------------------------------- | +| `Component` | [Svelte component][svelte-component-docs] | An imported Svelte component | +| `mountOptions` | [component options][svelte-mount-docs] | Options to pass to Svelte's `mount` function | + +| Result | Type | Description | +| ----------- | ------------------------------------------ | --------------------------------------- | +| `component` | [component exports][svelte-mount-docs] | The component's exports from `mount` | +| `unmount` | `() => void` | Unmount the component from the document | +| `rerender` | `(props: Partial) => Promise` | Update the component's props | + +### `cleanup` + +Cleanup rendered components and added elements. Call this when your tests are +over. + +```ts +cleanup() +``` + +### `addCleanupTask` + +Add a custom cleanup task to be called with `cleanup()` + +```ts +addCleanupTask(() => { + // ...reset something +}) +``` + +### `removeCleanupTask` + +Remove a cleanup task from `cleanup()`. Useful if a cleanup task can only be run +once and may be run outside of `cleanup` + +```ts +const customCleanup = () => { + // ...reset something +} + +addCleanupTask(customCleanup) + +const manuallyCleanupEarly = () => { + customCleanup() + removeCleanupTask(customCleanup) +} +``` + +### Utility types + +This module exports various utility types from +`@testing-library/svelte-core/types`. They adapt to whatever Svelte version is +installed, and can be used to get type signatures for imported components, +props, exports, etc. + +See [`./types.d.ts`](./types.d.ts) for the full list of available types. diff --git a/tools/ui/node_modules/@testing-library/svelte-core/dist/cleanup.d.ts b/tools/ui/node_modules/@testing-library/svelte-core/dist/cleanup.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..efaa6ca2d11a4c272b57d478a03fdc9ed5519ee6 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/dist/cleanup.d.ts @@ -0,0 +1,15 @@ +/** + * Register later cleanup task + * + * @param {() => void} onCleanup + */ +export function addCleanupTask(onCleanup: () => void): () => void; +/** Clean up all components and elements added to the document. */ +export function cleanup(): void; +/** + * Remove a cleanup task without running it. + * + * @param {() => void} onCleanup + */ +export function removeCleanupTask(onCleanup: () => void): void; +//# sourceMappingURL=cleanup.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/svelte-core/dist/cleanup.d.ts.map b/tools/ui/node_modules/@testing-library/svelte-core/dist/cleanup.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..7a2c4e6a33e56f40ecfa3630b64fd0789e63e076 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/dist/cleanup.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cleanup.d.ts","sourceRoot":"","sources":["../src/cleanup.js"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,0CAFW,MAAM,IAAI,SAAJ,IAAI,CAKpB;AAWD,kEAAkE;AAClE,gCAMC;AAhBD;;;;GAIG;AACH,6CAFW,MAAM,IAAI,QAIpB"} \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/svelte-core/dist/index.d.ts b/tools/ui/node_modules/@testing-library/svelte-core/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f69003eba672a253dcf32f79f36681e268487605 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/dist/index.d.ts @@ -0,0 +1,5 @@ +export * from "./cleanup.js"; +export * from "./mount.js"; +export * from "./render.js"; +export * from "./setup.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/svelte-core/dist/index.d.ts.map b/tools/ui/node_modules/@testing-library/svelte-core/dist/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..6e08bd5495c420e31f4ecf347a80286d38a86c02 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/svelte-core/dist/mount.d.ts b/tools/ui/node_modules/@testing-library/svelte-core/dist/mount.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1d99331ec17062a24ddbd9760384846aa0d8280a --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/dist/mount.d.ts @@ -0,0 +1,10 @@ +/** + * Render a Svelte component into the document. + * + * @template {import('../types.js').Component} C + * @param {import('../types.js').ComponentImport} Component + * @param {import('../types.js').MountOptions} options + * @returns {import('../types.js').MountResult} + */ +export function mount(Component: import("../types.js").ComponentImport, options: import("../types.js").MountOptions): import("../types.js").MountResult; +//# sourceMappingURL=mount.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/svelte-core/dist/mount.d.ts.map b/tools/ui/node_modules/@testing-library/svelte-core/dist/mount.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..ffab5fc8ea0a464698e6a3e89d32621551c9d042 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/dist/mount.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mount.d.ts","sourceRoot":"","sources":["../src/mount.js"],"names":[],"mappings":"AA2EA;;;;;;;GAOG;AACH,sBAL+C,CAAC,SAAnC,OAAQ,aAAa,EAAE,SAAU,aACnC,OAAO,aAAa,EAAE,eAAe,CAAC,CAAC,CAAC,WACxC,OAAO,aAAa,EAAE,YAAY,CAAC,CAAC,CAAC,GACnC,OAAO,aAAa,EAAE,WAAW,CAAC,CAAC,CAAC,CAwBhD"} \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/svelte-core/dist/props.svelte.d.ts b/tools/ui/node_modules/@testing-library/svelte-core/dist/props.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..54bbb0854ecf58a43c31b3bb780b97bf3ee731fa --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/dist/props.svelte.d.ts @@ -0,0 +1,12 @@ +/** + * Create a shallowly reactive props object. + * + * This allows us to update props on `rerender` + * without turing `props` into a deep set of Proxy objects + * + * @template {Record} Props + * @param {Props} initialProps + * @returns {[Props, (nextProps: Partial) => void]} + */ +export function createProps>(initialProps?: Props): [Props, (nextProps: Partial) => void]; +//# sourceMappingURL=props.svelte.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/svelte-core/dist/props.svelte.d.ts.map b/tools/ui/node_modules/@testing-library/svelte-core/dist/props.svelte.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..31b845546dcc7c3f56bf150956dc5d2580b71c6e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/dist/props.svelte.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"props.svelte.d.ts","sourceRoot":"","sources":["../src/props.svelte.js"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,4BAJuC,KAAK,SAA9B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAE,iBAC3B,KAAK,GACH,CAAC,KAAK,EAAE,CAAC,SAAS,EAAE,OAAO,CAAC,KAAK,CAAC,KAAK,IAAI,CAAC,CA0BxD"} \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/svelte-core/dist/render.d.ts b/tools/ui/node_modules/@testing-library/svelte-core/dist/render.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b2f89395f18f9aa3dd6cc7f52643fe9d1f3c4e74 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/dist/render.d.ts @@ -0,0 +1,12 @@ +/** + * Render a component into the document. + * + * @template {import('../types.js').Component} C + * + * @param {import('../types.js').ComponentImport} Component - The component to render. + * @param {import('../types.js').ComponentOptions} componentOptions - Customize how Svelte renders the component. + * @param {import('../types.js').SetupOptions} setupOptions - Customize how the document is set up. + * @returns {import('../types.js').RenderResult} The rendered component. + */ +export function render(Component: import("../types.js").ComponentImport, componentOptions: import("../types.js").ComponentOptions, setupOptions?: import("../types.js").SetupOptions): import("../types.js").RenderResult; +//# sourceMappingURL=render.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/svelte-core/dist/render.d.ts.map b/tools/ui/node_modules/@testing-library/svelte-core/dist/render.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..6d52fb39017266dbf0c8307964b2f89749450bfa --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/dist/render.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"render.d.ts","sourceRoot":"","sources":["../src/render.js"],"names":[],"mappings":"AAGA;;;;;;;;;GASG;AACH,uBAP+C,CAAC,SAAnC,OAAQ,aAAa,EAAE,SAAU,aAEnC,OAAO,aAAa,EAAE,eAAe,CAAC,CAAC,CAAC,oBACxC,OAAO,aAAa,EAAE,gBAAgB,CAAC,CAAC,CAAC,iBACzC,OAAO,aAAa,EAAE,YAAY,GAChC,OAAO,aAAa,EAAE,YAAY,CAAC,CAAC,CAAC,CAOjD"} \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/svelte-core/dist/setup.d.ts b/tools/ui/node_modules/@testing-library/svelte-core/dist/setup.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1aeda9e050093af37750143c760116a7384ef8df --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/dist/setup.d.ts @@ -0,0 +1,13 @@ +/** + * Set up the document to render a component. + * + * @template {import('../types.js').Component} C + * @param {import('../types.js').ComponentOptions} componentOptions - props or mount options + * @param {import('../types.js').SetupOptions} setupOptions - base element of the document to bind any queries + * @returns {import('../types.js').SetupResult} + */ +export function setup(componentOptions: import("../types.js").ComponentOptions, setupOptions?: import("../types.js").SetupOptions): import("../types.js").SetupResult; +export class UnknownSvelteOptionsError extends TypeError { + constructor(unknownOptions: any); +} +//# sourceMappingURL=setup.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/svelte-core/dist/setup.d.ts.map b/tools/ui/node_modules/@testing-library/svelte-core/dist/setup.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..098ee955454b24e72f50dcfabf867f5e1e72f632 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/dist/setup.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"setup.d.ts","sourceRoot":"","sources":["../src/setup.js"],"names":[],"mappings":"AAsDA;;;;;;;GAOG;AACH,sBAL+C,CAAC,SAAnC,OAAQ,aAAa,EAAE,SAAU,oBACnC,OAAO,aAAa,EAAE,gBAAgB,CAAC,CAAC,CAAC,iBACzC,OAAO,aAAa,EAAE,YAAY,GAChC,OAAO,aAAa,EAAE,WAAW,CAAC,CAAC,CAAC,CAuBhD;AA1ED;IACE,iCAaC;CACF"} \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/svelte-core/dist/svelte-version.d.ts b/tools/ui/node_modules/@testing-library/svelte-core/dist/svelte-version.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..33d378cb0f0f7861bf4872c3ff1b13127434fc4e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/dist/svelte-version.d.ts @@ -0,0 +1,3 @@ +/** Whether we're using Svelte >= 5. */ +export const IS_MODERN_SVELTE: boolean; +//# sourceMappingURL=svelte-version.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/svelte-core/dist/svelte-version.d.ts.map b/tools/ui/node_modules/@testing-library/svelte-core/dist/svelte-version.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..aaea9a4228314a2f3e72aa8e16cf48866c26b6e1 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/dist/svelte-version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"svelte-version.d.ts","sourceRoot":"","sources":["../src/svelte-version.js"],"names":[],"mappings":"AAGA,uCAAuC;AACvC,uCAA2D"} \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/svelte-core/package.json b/tools/ui/node_modules/@testing-library/svelte-core/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b62b08844e53a9defcfbc91e1d3d9bd76ab7e95a --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/package.json @@ -0,0 +1,48 @@ +{ + "name": "@testing-library/svelte-core", + "version": "1.0.0", + "description": "Core rendering and cleanup logic for Svelte testing utilities.", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./src/index.js" + }, + "./types": { + "types": "./types.d.ts" + } + }, + "type": "module", + "license": "MIT", + "homepage": "https://github.com/testing-library/svelte-testing-library#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/testing-library/svelte-testing-library.git", + "directory": "packages/svelte-core" + }, + "bugs": { + "url": "https://github.com/testing-library/svelte-testing-library/issues" + }, + "engines": { + "node": ">=16" + }, + "keywords": [ + "tdd", + "svelte", + "ui", + "unit", + "component", + "functional" + ], + "files": [ + "dist", + "src", + "types.d.ts" + ], + "peerDependencies": { + "svelte": "^3 || ^4 || ^5 || ^5.0.0-next.0" + }, + "publishConfig": { + "access": "public", + "provenance": true + } +} \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/svelte-core/src/cleanup.js b/tools/ui/node_modules/@testing-library/svelte-core/src/cleanup.js new file mode 100644 index 0000000000000000000000000000000000000000..2aa70daa348cd85faad5c76ac23a4aae6c25757c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/src/cleanup.js @@ -0,0 +1,32 @@ +/** @type {Set<() => void>} */ +const cleanupTasks = new Set() + +/** + * Register later cleanup task + * + * @param {() => void} onCleanup + */ +const addCleanupTask = (onCleanup) => { + cleanupTasks.add(onCleanup) + return onCleanup +} + +/** + * Remove a cleanup task without running it. + * + * @param {() => void} onCleanup + */ +const removeCleanupTask = (onCleanup) => { + cleanupTasks.delete(onCleanup) +} + +/** Clean up all components and elements added to the document. */ +const cleanup = () => { + for (const handleCleanup of cleanupTasks.values()) { + handleCleanup() + } + + cleanupTasks.clear() +} + +export { addCleanupTask, cleanup, removeCleanupTask } diff --git a/tools/ui/node_modules/@testing-library/svelte-core/src/index.js b/tools/ui/node_modules/@testing-library/svelte-core/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ce20a679d830772219eeb8add63d87bf479925a1 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/src/index.js @@ -0,0 +1,11 @@ +/** + * Rendering core for svelte-testing-library. + * + * Defines how components are added to and removed from the DOM. + * Will switch to legacy, class-based mounting logic + * if it looks like we're in a Svelte <= 4 environment. + */ +export * from './cleanup.js' +export * from './mount.js' +export * from './render.js' +export * from './setup.js' diff --git a/tools/ui/node_modules/@testing-library/svelte-core/src/mount.js b/tools/ui/node_modules/@testing-library/svelte-core/src/mount.js new file mode 100644 index 0000000000000000000000000000000000000000..2927437f1ce825e0c47de3bf9ccbf4e595cc0778 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/src/mount.js @@ -0,0 +1,108 @@ +/** + * Component rendering core, with support for Svelte 3, 4, and 5 + */ +import * as Svelte from 'svelte' + +import { addCleanupTask, removeCleanupTask } from './cleanup.js' +import { createProps } from './props.svelte.js' +import { IS_MODERN_SVELTE } from './svelte-version.js' + +/** + * Mount a modern Svelte 5 component into the DOM. + * + * @template {import('../types.js').Component} C + * @param {import('../types.js').ComponentType} Component + * @param {import('../types.js').MountOptions} options + * @returns {import('../types.js').MountResult} + */ +const mountModern = (Component, options) => { + const [props, updateProps] = createProps(options.props) + const component = Svelte.mount(Component, { ...options, props }) + + /** Remove the component from the DOM. */ + const unmount = () => { + Svelte.flushSync(() => Svelte.unmount(component)) + removeCleanupTask(unmount) + } + + /** Update the component's props. */ + const rerender = (nextProps) => { + Svelte.flushSync(() => updateProps(nextProps)) + } + + addCleanupTask(unmount) + Svelte.flushSync() + + return { component, unmount, rerender } +} + +/** + * Mount a legacy Svelte 3 or 4 component into the DOM. + * + * @template {import('../types.js').LegacyComponent} C + * @param {import('../types.js').ComponentType} Component + * @param {import('../types.js').MountOptions} options + * @returns {import('../types.js').MountResult} + */ +const mountLegacy = (Component, options) => { + const component = new Component(options) + + /** Remove the component from the DOM. */ + const unmount = () => { + component.$destroy() + removeCleanupTask(unmount) + } + + /** Update the component's props. */ + const rerender = (nextProps) => { + component.$set(nextProps) + } + + // This `$$.on_destroy` listener is included for strict backwards compatibility + // with previous versions of `@testing-library/svelte`. + // It's unnecessary and will be removed in a future major version. + component.$$.on_destroy.push(() => { + removeCleanupTask(unmount) + }) + + addCleanupTask(unmount) + + return { component, unmount, rerender } +} + +/** The mount method in use. */ +const mountComponent = IS_MODERN_SVELTE ? mountModern : mountLegacy + +/** + * Render a Svelte component into the document. + * + * @template {import('../types.js').Component} C + * @param {import('../types.js').ComponentImport} Component + * @param {import('../types.js').MountOptions} options + * @returns {import('../types.js').MountResult} + */ +const mount = (Component, options) => { + const { component, unmount, rerender } = mountComponent( + 'default' in Component ? Component.default : Component, + options + ) + + return { + component, + unmount, + rerender: async (props) => { + if ('props' in props) { + console.warn( + 'rerender({ props: { ... } }) deprecated, use rerender({ ... }) instead' + ) + props = props.props + } + + rerender(props) + // Await the next tick for Svelte 3/4, which cannot flush changes synchronously + await Svelte.tick() + }, + } +} + +export { mount } diff --git a/tools/ui/node_modules/@testing-library/svelte-core/src/props.svelte.js b/tools/ui/node_modules/@testing-library/svelte-core/src/props.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..322d6e2e85dc46905978d99fa6d654c32c61bf50 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/src/props.svelte.js @@ -0,0 +1,37 @@ +/** + * Create a shallowly reactive props object. + * + * This allows us to update props on `rerender` + * without turing `props` into a deep set of Proxy objects + * + * @template {Record} Props + * @param {Props} initialProps + * @returns {[Props, (nextProps: Partial) => void]} + */ +const createProps = (initialProps = {}) => { + let currentProps = $state.raw(initialProps) + + const props = new Proxy(initialProps, { + get(_, key) { + return currentProps[key] + }, + set(_, key, value) { + currentProps[key] = value + return true + }, + has(_, key) { + return Reflect.has(currentProps, key) + }, + ownKeys() { + return Reflect.ownKeys(currentProps) + }, + }) + + const update = (nextProps) => { + currentProps = { ...currentProps, ...nextProps } + } + + return [props, update] +} + +export { createProps } diff --git a/tools/ui/node_modules/@testing-library/svelte-core/src/render.js b/tools/ui/node_modules/@testing-library/svelte-core/src/render.js new file mode 100644 index 0000000000000000000000000000000000000000..0c0ff28159746551f2dc76f2cf41af4655c0c607 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/src/render.js @@ -0,0 +1,21 @@ +import { mount } from './mount.js' +import { setup } from './setup.js' + +/** + * Render a component into the document. + * + * @template {import('../types.js').Component} C + * + * @param {import('../types.js').ComponentImport} Component - The component to render. + * @param {import('../types.js').ComponentOptions} componentOptions - Customize how Svelte renders the component. + * @param {import('../types.js').SetupOptions} setupOptions - Customize how the document is set up. + * @returns {import('../types.js').RenderResult} The rendered component. + */ +const render = (Component, componentOptions, setupOptions = {}) => { + const { mountOptions, ...setupResult } = setup(componentOptions, setupOptions) + const mountResult = mount(Component, mountOptions) + + return { ...setupResult, ...mountResult } +} + +export { render } diff --git a/tools/ui/node_modules/@testing-library/svelte-core/src/setup.js b/tools/ui/node_modules/@testing-library/svelte-core/src/setup.js new file mode 100644 index 0000000000000000000000000000000000000000..04c6c4f15b81db2b28acc69c8cfcd04151e6d281 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/src/setup.js @@ -0,0 +1,86 @@ +/** Set up the document to render a component. */ +import { addCleanupTask } from './cleanup.js' +import { IS_MODERN_SVELTE } from './svelte-version.js' + +/** Allowed options to the `mount` call or legacy component constructor. */ +const ALLOWED_MOUNT_OPTIONS = IS_MODERN_SVELTE + ? ['target', 'anchor', 'props', 'events', 'context', 'intro'] + : ['target', 'accessors', 'anchor', 'props', 'hydrate', 'intro', 'context'] + +class UnknownSvelteOptionsError extends TypeError { + constructor(unknownOptions) { + super(`Unknown options. + + Unknown: [ ${unknownOptions.join(', ')} ] + Allowed: [ ${ALLOWED_MOUNT_OPTIONS.join(', ')} ] + + To pass both Svelte options and props to a component, + or to use props that share a name with a Svelte option, + you must place all your props under the \`props\` key: + + render(Component, { props: { /** props here **/ } }) +`) + this.name = 'UnknownSvelteOptionsError' + } +} + +/** + * Validate a component's mount options. + * + * @template {import('../types.js').Component} C + * @param {import('../types.js').ComponentOptions} options - props or mount options + * @returns {Partial>} + */ +const validateOptions = (options) => { + const isProps = !Object.keys(options).some((option) => + ALLOWED_MOUNT_OPTIONS.includes(option) + ) + + if (isProps) { + return { props: options } + } + + // Check if any props and Svelte options were accidentally mixed. + const unknownOptions = Object.keys(options).filter( + (option) => !ALLOWED_MOUNT_OPTIONS.includes(option) + ) + + if (unknownOptions.length > 0) { + throw new UnknownSvelteOptionsError(unknownOptions) + } + + return options +} + +/** + * Set up the document to render a component. + * + * @template {import('../types.js').Component} C + * @param {import('../types.js').ComponentOptions} componentOptions - props or mount options + * @param {import('../types.js').SetupOptions} setupOptions - base element of the document to bind any queries + * @returns {import('../types.js').SetupResult} + */ +const setup = (componentOptions, setupOptions = {}) => { + const mountOptions = validateOptions(componentOptions) + + const baseElement = + setupOptions.baseElement ?? mountOptions.target ?? document.body + + const container = + mountOptions.target ?? + baseElement.appendChild(document.createElement('div')) + + addCleanupTask(() => { + if (container.parentNode === document.body) { + container.remove() + } + }) + + return { + baseElement, + container, + mountOptions: { ...mountOptions, target: container }, + } +} + +export { setup, UnknownSvelteOptionsError } diff --git a/tools/ui/node_modules/@testing-library/svelte-core/src/svelte-version.js b/tools/ui/node_modules/@testing-library/svelte-core/src/svelte-version.js new file mode 100644 index 0000000000000000000000000000000000000000..72f761ac9282d5e3df9e41965340210bac4cc68a --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/src/svelte-version.js @@ -0,0 +1,7 @@ +/** Detect which version of Svelte we're using */ +import * as Svelte from 'svelte' + +/** Whether we're using Svelte >= 5. */ +const IS_MODERN_SVELTE = typeof Svelte.mount === 'function' + +export { IS_MODERN_SVELTE } diff --git a/tools/ui/node_modules/@testing-library/svelte-core/types.d.ts b/tools/ui/node_modules/@testing-library/svelte-core/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a3b3ab780dacb59cbe356a0e576e21eecf8afdd --- /dev/null +++ b/tools/ui/node_modules/@testing-library/svelte-core/types.d.ts @@ -0,0 +1,131 @@ +/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-deprecated */ +/** + * Component and utility types. + * + * Supports components from Svelte 3, 4, and 5. + */ +import type { + Component as ModernComponent, + ComponentConstructorOptions as LegacyConstructorOptions, + ComponentProps, + EventDispatcher, + mount, + SvelteComponent as Svelte4LegacyComponent, + SvelteComponentTyped as Svelte3LegacyComponent, +} from 'svelte' + +type IS_MODERN_SVELTE = ModernComponent extends (...args: any[]) => any + ? true + : false + +type IS_LEGACY_SVELTE_4 = + EventDispatcher extends (...args: any[]) => any ? true : false + +/** A compiled, imported Svelte component. */ +export type Component< + P extends Record = any, + E extends Record = any, +> = IS_MODERN_SVELTE extends true + ? ModernComponent | LegacyComponent

+ : LegacyComponent

+ +/** A compiled, imported Svelte 3 or 4 component. */ +export type LegacyComponent

= any> = + IS_LEGACY_SVELTE_4 extends true + ? Svelte4LegacyComponent

+ : Svelte3LegacyComponent

+ +/** + * The "type" of an imported, compiled Svelte component. + * + * In Svelte 5, there is no difference between the + * imported component and its "type" - it's just a function. + * In Svelte 3/4, the imported component is a class. + */ +export type ComponentType = C extends LegacyComponent + ? new (...args: any[]) => C + : C + +/** + * A component import. + * + * A convenience type to allow dynamically `import(...)`'d + * components to be passed directly to `mount.` + */ +export type ComponentImport = + | ComponentType + | { default: ComponentType } + +/** The props of a component. */ +export type Props = ComponentProps + +/** + * The exported fields of a component. + * + * In Svelte 5, this is the set of variables marked as `export`'d. + * In Svelte 4, this is simply the instance of the component class. + */ +export type Exports = IS_MODERN_SVELTE extends true + ? C extends ModernComponent + ? E + : C & { $set: never; $on: never; $destroy: never } + : C + +/** + * Options that may be passed to `mount` when rendering the component. + * + * In Svelte 4, these are the options passed to the component constructor. + */ +export type MountOptions = IS_MODERN_SVELTE extends true + ? Parameters, Exports>>[1] + : LegacyConstructorOptions> + +/** A component's props or some of its mount options. */ +export type ComponentOptions = + | Props + | Partial> + +/** Update a component's props and trigger updates to the DOM. */ +export type Rerender = ( + props: Partial> +) => Promise + +/** The result of mounting a component into the document. */ +export interface MountResult { + /** The mounted component's exports. */ + component: Exports + /** Unmount the component. */ + unmount: () => void + /** Rerender the component. */ + rerender: Rerender +} + +/** Options for configuring the document. */ +export interface SetupOptions { + /** The base document element, `document.body` if unspecified. */ + baseElement?: HTMLElement +} + +/** The result of setting up the document for rendering. */ +export interface SetupResult { + /** The base document element, usually `document.body`. */ + baseElement: HTMLElement + /** The component's immediate container element, usually a `

` appended to `document.body`. */ + container: HTMLElement + /** Options to pass to `mount`. */ + mountOptions: MountOptions +} + +/** The result of setting up the document and rendering the component. */ +export interface RenderResult { + /** The base document element, usually `document.body`. */ + baseElement: HTMLElement + /** The component's immediate container element, usually a `
` appended to `document.body`. */ + container: HTMLElement + /** The mounted component's exports. */ + component: Exports + /** Unmount the component. */ + unmount: () => void + /** Rerender the component. */ + rerender: Rerender +} diff --git a/tools/ui/node_modules/@testing-library/user-event/LICENSE b/tools/ui/node_modules/@testing-library/user-event/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..527063a1a5c1008645afa5069b2f6ad6943a80bc --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) +Copyright (c) 2020 Giorgio Polvara + +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. diff --git a/tools/ui/node_modules/@testing-library/user-event/README.md b/tools/ui/node_modules/@testing-library/user-event/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3dc9bebe6aa61a435885a87a47d643a726420c7f --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/README.md @@ -0,0 +1,124 @@ +
+

user-event

+ + + dog + + +

Fire events the same way the user does

+ +
+ +[**Read The Docs**](https://testing-library.com/docs/user-event/intro) + +
+
+ +--- + + +[![Build Status][build-badge]][build] +[![Code Coverage][coverage-badge]][coverage] +[![version][version-badge]][package] +[![downloads][downloads-badge]][npmtrends] +[![MIT License][license-badge]][license] +[![All Contributors][all-contributors-badge]](#contributors) +[![PRs Welcome][prs-badge]][prs] +[![Code of Conduct][coc-badge]][coc] +[![Discord][discord-badge]][discord] + +[![Watch on GitHub][github-watch-badge]][github-watch] +[![Star on GitHub][github-star-badge]][github-star] +[![Tweet][twitter-badge]][twitter] + + +## The problem + +From +[testing-library/dom-testing-library#107](https://github.com/testing-library/dom-testing-library/issues/107): + +> [...] it is becoming apparent the need to express user actions on a web page +> using a higher-level abstraction than [`fireEvent`][fire-event] + +## The solution + +`user-event` tries to simulate the real events that would happen in the browser +as the user interacts with it. For example `userEvent.click(checkbox)` would +change the state of the checkbox. + +> [The more your tests resemble the way your software is used, the more +> confidence they can give you.][guiding-principle] + +## Issues + +Looking to contribute? Look for the [Good First Issue][good-first-issue] label. + +### 🐛 Bugs + +Please file an issue for bugs, missing documentation, or unexpected behavior. + +[**See Bugs**][bugs] + +### 💡 Feature Requests + +Please file an issue to suggest new features. Vote on feature requests by adding +a 👍. This helps maintainers prioritize what to work on. + +[**See Feature Requests**][requests] + +### ❓ Questions + +For questions related to using the library, please visit a support community +instead of filing an issue on GitHub. + +- [Discord][discord] +- [Stack Overflow][stackoverflow] + +## Contributors + +We most sincerely thank [the people who make this project +possible][contributors]. Contributions of any kind are welcome! 💚 + +## License + +[MIT](LICENSE) + + +[npm]: https://www.npmjs.com +[node]: https://nodejs.org +[build-badge]: https://img.shields.io/github/workflow/status/testing-library/user-event/validate/main?logo=github&style=flat-square +[build]: https://github.com/testing-library/user-event/actions?query=workflow%3Avalidate +[coverage-badge]: https://img.shields.io/codecov/c/github/testing-library/user-event.svg?style=flat-square +[coverage]: https://codecov.io/github/testing-library/user-event +[version-badge]: https://img.shields.io/npm/v/@testing-library/user-event.svg?style=flat-square +[package]: https://www.npmjs.com/package/@testing-library/user-event +[downloads-badge]: https://img.shields.io/npm/dm/@testing-library/user-event.svg?style=flat-square +[npmtrends]: http://www.npmtrends.com/@testing-library/user-event +[license-badge]: https://img.shields.io/npm/l/@testing-library/user-event.svg?style=flat-square +[license]: https://github.com/testing-library/user-event/blob/main/LICENSE +[prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square +[prs]: http://makeapullrequest.com +[coc-badge]: https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square +[coc]: https://github.com/testing-library/.github/blob/main/CODE_OF_CONDUCT.md +[github-watch-badge]: https://img.shields.io/github/watchers/testing-library/user-event.svg?style=social +[github-watch]: https://github.com/testing-library/user-event/watchers +[github-star-badge]: https://img.shields.io/github/stars/testing-library/user-event.svg?style=social +[github-star]: https://github.com/testing-library/user-event/stargazers +[twitter]: https://twitter.com/intent/tweet?text=Check%20out%20user-event%20by%20%40@TestingLib%20https%3A%2F%2Fgithub.com%2Ftesting-library%2Fuser-event%20%F0%9F%91%8D +[twitter-badge]: https://img.shields.io/twitter/url/https/github.com/testing-library/user-event.svg?style=social +[all-contributors-badge]: https://img.shields.io/github/all-contributors/testing-library/user-event?color=orange&style=flat-square +[guiding-principle]: https://twitter.com/kentcdodds/status/977018512689455106 +[bugs]: https://github.com/testing-library/user-event/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Acreated-desc+label%3Abug +[requests]: https://github.com/testing-library/user-event/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc+label%3Aenhancement +[good-first-issue]: https://github.com/testing-library/user-event/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc+label%3Aenhancement+label%3A%22good+first+issue%22 +[fire-event]: https://testing-library.com/docs/dom-testing-library/api-events#fireevent +[discord-badge]: https://img.shields.io/discord/723559267868737556.svg?color=7389D8&labelColor=6A7EC2&logo=discord&logoColor=ffffff&style=flat-square +[discord]: https://discord.gg/testing-library +[stackoverflow]: https://stackoverflow.com/questions/tagged/user-event +[contributors]: https://github.com/testing-library/user-event/blob/main/CONTRIBUTORS.md + diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/clipboard/copy.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/clipboard/copy.js new file mode 100644 index 0000000000000000000000000000000000000000..d0232670239a3fd3215dd3b9215fb26a143e261a --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/clipboard/copy.js @@ -0,0 +1,22 @@ +'use strict'; + +var Clipboard = require('../utils/dataTransfer/Clipboard.js'); +var copySelection = require('../document/copySelection.js'); + +async function copy() { + const doc = this.config.document; + var _doc_activeElement; + const target = (_doc_activeElement = doc.activeElement) !== null && _doc_activeElement !== undefined ? _doc_activeElement : /* istanbul ignore next */ doc.body; + const clipboardData = copySelection.copySelection(target); + if (clipboardData.items.length === 0) { + return; + } + if (this.dispatchUIEvent(target, 'copy', { + clipboardData + }) && this.config.writeToClipboard) { + await Clipboard.writeDataTransferToClipboard(doc, clipboardData); + } + return clipboardData; +} + +exports.copy = copy; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/clipboard/cut.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/clipboard/cut.js new file mode 100644 index 0000000000000000000000000000000000000000..632995bd2293aac5684e9a76ea83e385cac1ebfa --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/clipboard/cut.js @@ -0,0 +1,22 @@ +'use strict'; + +var Clipboard = require('../utils/dataTransfer/Clipboard.js'); +var copySelection = require('../document/copySelection.js'); + +async function cut() { + const doc = this.config.document; + var _doc_activeElement; + const target = (_doc_activeElement = doc.activeElement) !== null && _doc_activeElement !== undefined ? _doc_activeElement : /* istanbul ignore next */ doc.body; + const clipboardData = copySelection.copySelection(target); + if (clipboardData.items.length === 0) { + return; + } + if (this.dispatchUIEvent(target, 'cut', { + clipboardData + }) && this.config.writeToClipboard) { + await Clipboard.writeDataTransferToClipboard(target.ownerDocument, clipboardData); + } + return clipboardData; +} + +exports.cut = cut; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/clipboard/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/clipboard/index.js new file mode 100644 index 0000000000000000000000000000000000000000..62097bc745171d2a276813dc4e0bacc8d34bbae6 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/clipboard/index.js @@ -0,0 +1,11 @@ +'use strict'; + +var copy = require('./copy.js'); +var cut = require('./cut.js'); +var paste = require('./paste.js'); + + + +exports.copy = copy.copy; +exports.cut = cut.cut; +exports.paste = paste.paste; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/clipboard/paste.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/clipboard/paste.js new file mode 100644 index 0000000000000000000000000000000000000000..e2ec57d04d1c7f0da9b981d77de02e10bc26e885 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/clipboard/paste.js @@ -0,0 +1,25 @@ +'use strict'; + +var DataTransfer = require('../utils/dataTransfer/DataTransfer.js'); +var Clipboard = require('../utils/dataTransfer/Clipboard.js'); +var getWindow = require('../utils/misc/getWindow.js'); + +async function paste(clipboardData) { + const doc = this.config.document; + var _doc_activeElement; + const target = (_doc_activeElement = doc.activeElement) !== null && _doc_activeElement !== undefined ? _doc_activeElement : /* istanbul ignore next */ doc.body; + var _ref; + const dataTransfer = (_ref = typeof clipboardData === 'string' ? getClipboardDataFromString(doc, clipboardData) : clipboardData) !== null && _ref !== undefined ? _ref : await Clipboard.readDataTransferFromClipboard(doc).catch(()=>{ + throw new Error('`userEvent.paste()` without `clipboardData` requires the `ClipboardAPI` to be available.'); + }); + this.dispatchUIEvent(target, 'paste', { + clipboardData: dataTransfer + }); +} +function getClipboardDataFromString(doc, text) { + const dt = DataTransfer.createDataTransfer(getWindow.getWindow(doc)); + dt.setData('text', text); + return dt; +} + +exports.paste = paste; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/convenience/click.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/convenience/click.js new file mode 100644 index 0000000000000000000000000000000000000000..12fc0724be063ce9407eb9e93cf7eed3f5d43307 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/convenience/click.js @@ -0,0 +1,35 @@ +'use strict'; + +async function click(element) { + const pointerIn = []; + if (!this.config.skipHover) { + pointerIn.push({ + target: element + }); + } + pointerIn.push({ + keys: '[MouseLeft]', + target: element + }); + return this.pointer(pointerIn); +} +async function dblClick(element) { + return this.pointer([ + { + target: element + }, + '[MouseLeft][MouseLeft]' + ]); +} +async function tripleClick(element) { + return this.pointer([ + { + target: element + }, + '[MouseLeft][MouseLeft][MouseLeft]' + ]); +} + +exports.click = click; +exports.dblClick = dblClick; +exports.tripleClick = tripleClick; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/convenience/hover.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/convenience/hover.js new file mode 100644 index 0000000000000000000000000000000000000000..dc9b9f9b2511bd7fb1e71a6711e9b968011b8434 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/convenience/hover.js @@ -0,0 +1,19 @@ +'use strict'; + +require('../utils/dataTransfer/Clipboard.js'); +var cssPointerEvents = require('../utils/pointer/cssPointerEvents.js'); + +async function hover(element) { + return this.pointer({ + target: element + }); +} +async function unhover(element) { + cssPointerEvents.assertPointerEvents(this, this.system.pointer.getMouseTarget(this)); + return this.pointer({ + target: element.ownerDocument.body + }); +} + +exports.hover = hover; +exports.unhover = unhover; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/convenience/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/convenience/index.js new file mode 100644 index 0000000000000000000000000000000000000000..15bfb49ce13b583cf794ec32834d8d59188dc5d8 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/convenience/index.js @@ -0,0 +1,14 @@ +'use strict'; + +var click = require('./click.js'); +var hover = require('./hover.js'); +var tab = require('./tab.js'); + + + +exports.click = click.click; +exports.dblClick = click.dblClick; +exports.tripleClick = click.tripleClick; +exports.hover = hover.hover; +exports.unhover = hover.unhover; +exports.tab = tab.tab; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/convenience/tab.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/convenience/tab.js new file mode 100644 index 0000000000000000000000000000000000000000..dc91ff4cfc321cf12c8fe63c1b52ca7e64ba4522 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/convenience/tab.js @@ -0,0 +1,7 @@ +'use strict'; + +async function tab({ shift } = {}) { + return this.keyboard(shift === true ? '{Shift>}{Tab}{/Shift}' : shift === false ? '[/ShiftLeft][/ShiftRight]{Tab}' : '{Tab}'); +} + +exports.tab = tab; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/UI.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/UI.js new file mode 100644 index 0000000000000000000000000000000000000000..4d4e02a15b6e4a2c728c8162013de8ce6146eeb7 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/UI.js @@ -0,0 +1,92 @@ +'use strict'; + +const UIValue = Symbol('Displayed value in UI'); +const UISelection = Symbol('Displayed selection in UI'); +const InitialValue = Symbol('Initial value to compare on blur'); +function isUIValue(value) { + return typeof value === 'object' && UIValue in value; +} +function isUISelectionStart(start) { + return !!start && typeof start === 'object' && UISelection in start; +} +function setUIValue(element, value) { + if (element[InitialValue] === undefined) { + element[InitialValue] = element.value; + } + element[UIValue] = value; + // eslint-disable-next-line no-new-wrappers + element.value = Object.assign(new String(value), { + [UIValue]: true + }); +} +function getUIValue(element) { + return element[UIValue] === undefined ? element.value : String(element[UIValue]); +} +/** Flag the IDL value as clean. This does not change the value.*/ function setUIValueClean(element) { + element[UIValue] = undefined; +} +function clearInitialValue(element) { + element[InitialValue] = undefined; +} +function getInitialValue(element) { + return element[InitialValue]; +} +function setUISelectionRaw(element, selection) { + element[UISelection] = selection; +} +function setUISelection(element, { focusOffset: focusOffsetParam, anchorOffset: anchorOffsetParam = focusOffsetParam }, mode = 'replace') { + const valueLength = getUIValue(element).length; + const sanitizeOffset = (o)=>Math.max(0, Math.min(valueLength, o)); + const anchorOffset = mode === 'replace' || element[UISelection] === undefined ? sanitizeOffset(anchorOffsetParam) : element[UISelection].anchorOffset; + const focusOffset = sanitizeOffset(focusOffsetParam); + const startOffset = Math.min(anchorOffset, focusOffset); + const endOffset = Math.max(anchorOffset, focusOffset); + element[UISelection] = { + anchorOffset, + focusOffset + }; + if (element.selectionStart === startOffset && element.selectionEnd === endOffset) { + return; + } + // eslint-disable-next-line no-new-wrappers + const startObj = Object.assign(new Number(startOffset), { + [UISelection]: true + }); + try { + element.setSelectionRange(startObj, endOffset); + } catch { + // DOMException for invalid state is expected when calling this + // on an element without support for setSelectionRange + } +} +function getUISelection(element) { + var _element_selectionStart, _element_selectionEnd, _element_UISelection; + const sel = (_element_UISelection = element[UISelection]) !== null && _element_UISelection !== undefined ? _element_UISelection : { + anchorOffset: (_element_selectionStart = element.selectionStart) !== null && _element_selectionStart !== undefined ? _element_selectionStart : 0, + focusOffset: (_element_selectionEnd = element.selectionEnd) !== null && _element_selectionEnd !== undefined ? _element_selectionEnd : 0 + }; + return { + ...sel, + startOffset: Math.min(sel.anchorOffset, sel.focusOffset), + endOffset: Math.max(sel.anchorOffset, sel.focusOffset) + }; +} +function hasUISelection(element) { + return !!element[UISelection]; +} +/** Flag the IDL selection as clean. This does not change the selection. */ function setUISelectionClean(element) { + element[UISelection] = undefined; +} + +exports.clearInitialValue = clearInitialValue; +exports.getInitialValue = getInitialValue; +exports.getUISelection = getUISelection; +exports.getUIValue = getUIValue; +exports.hasUISelection = hasUISelection; +exports.isUISelectionStart = isUISelectionStart; +exports.isUIValue = isUIValue; +exports.setUISelection = setUISelection; +exports.setUISelectionClean = setUISelectionClean; +exports.setUISelectionRaw = setUISelectionRaw; +exports.setUIValue = setUIValue; +exports.setUIValueClean = setUIValueClean; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/copySelection.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/copySelection.js new file mode 100644 index 0000000000000000000000000000000000000000..e9d039c02ea3d166197fc5c5dcc149873e864632 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/copySelection.js @@ -0,0 +1,29 @@ +'use strict'; + +var DataTransfer = require('../utils/dataTransfer/DataTransfer.js'); +require('../utils/dataTransfer/Clipboard.js'); +var getWindow = require('../utils/misc/getWindow.js'); +var selection = require('../utils/focus/selection.js'); +var UI = require('./UI.js'); + +function copySelection(target) { + const data = selection.hasOwnSelection(target) ? { + 'text/plain': readSelectedValueFromInput(target) + } : { + 'text/plain': String(target.ownerDocument.getSelection()) + }; + const dt = DataTransfer.createDataTransfer(getWindow.getWindow(target)); + for(const type in data){ + if (data[type]) { + dt.setData(type, data[type]); + } + } + return dt; +} +function readSelectedValueFromInput(target) { + const sel = UI.getUISelection(target); + const val = UI.getUIValue(target); + return val.substring(sel.startOffset, sel.endOffset); +} + +exports.copySelection = copySelection; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/getValueOrTextContent.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/getValueOrTextContent.js new file mode 100644 index 0000000000000000000000000000000000000000..0aca940e9ff9e232a007759982a9294a82e90d13 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/getValueOrTextContent.js @@ -0,0 +1,18 @@ +'use strict'; + +require('../utils/dataTransfer/Clipboard.js'); +var isContentEditable = require('../utils/edit/isContentEditable.js'); +var UI = require('./UI.js'); + +function getValueOrTextContent(element) { + // istanbul ignore if + if (!element) { + return null; + } + if (isContentEditable.isContentEditable(element)) { + return element.textContent; + } + return UI.getUIValue(element); +} + +exports.getValueOrTextContent = getValueOrTextContent; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d8495bd140c3ec1dad4ab3edfafd9c5e130b9fa3 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/index.js @@ -0,0 +1,17 @@ +'use strict'; + +var UI = require('./UI.js'); +var getValueOrTextContent = require('./getValueOrTextContent.js'); +var copySelection = require('./copySelection.js'); +var trackValue = require('./trackValue.js'); + + + +exports.clearInitialValue = UI.clearInitialValue; +exports.getUISelection = UI.getUISelection; +exports.getUIValue = UI.getUIValue; +exports.setUISelection = UI.setUISelection; +exports.setUIValue = UI.setUIValue; +exports.getValueOrTextContent = getValueOrTextContent.getValueOrTextContent; +exports.copySelection = copySelection.copySelection; +exports.commitValueAfterInput = trackValue.commitValueAfterInput; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/interceptor.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/interceptor.js new file mode 100644 index 0000000000000000000000000000000000000000..dbdd13fae0196471a86e752bcc4dfc3a89821ec9 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/interceptor.js @@ -0,0 +1,104 @@ +'use strict'; + +var isElementType = require('../utils/misc/isElementType.js'); +require('../utils/dataTransfer/Clipboard.js'); +var trackValue = require('./trackValue.js'); +var UI = require('./UI.js'); + +const Interceptor = Symbol('Interceptor for programmatical calls'); +function prepareInterceptor(element, propName, interceptorImpl) { + const prototypeDescriptor = Object.getOwnPropertyDescriptor(element.constructor.prototype, propName); + const objectDescriptor = Object.getOwnPropertyDescriptor(element, propName); + const target = (prototypeDescriptor === null || prototypeDescriptor === undefined ? undefined : prototypeDescriptor.set) ? 'set' : 'value'; + /* istanbul ignore if */ if (typeof (prototypeDescriptor === null || prototypeDescriptor === undefined ? undefined : prototypeDescriptor[target]) !== 'function' || prototypeDescriptor[target][Interceptor]) { + throw new Error(`Element ${element.tagName} does not implement "${String(propName)}".`); + } + function intercept(...args) { + const { applyNative = false, realArgs, then } = interceptorImpl.call(this, ...args); + const realFunc = (!applyNative && objectDescriptor || prototypeDescriptor)[target]; + if (target === 'set') { + realFunc.call(this, realArgs); + } else { + realFunc.call(this, ...realArgs); + } + then === null || then === undefined ? undefined : then(); + } + intercept[Interceptor] = Interceptor; + Object.defineProperty(element, propName, { + ...objectDescriptor !== null && objectDescriptor !== undefined ? objectDescriptor : prototypeDescriptor, + [target]: intercept + }); +} +function prepareValueInterceptor(element) { + prepareInterceptor(element, 'value', function interceptorImpl(v) { + const isUI = UI.isUIValue(v); + if (isUI) { + trackValue.startTrackValue(this); + } + return { + applyNative: !!isUI, + realArgs: sanitizeValue(this, v), + then: isUI ? undefined : ()=>trackValue.trackOrSetValue(this, String(v)) + }; + }); +} +function sanitizeValue(element, v) { + // Workaround for JSDOM + if (isElementType.isElementType(element, 'input', { + type: 'number' + }) && String(v) !== '' && !Number.isNaN(Number(v))) { + // Setting value to "1." results in `null` in JSDOM + return String(Number(v)); + } + return String(v); +} +function prepareSelectionInterceptor(element) { + prepareInterceptor(element, 'setSelectionRange', function interceptorImpl(start, ...others) { + const isUI = UI.isUISelectionStart(start); + return { + applyNative: !!isUI, + realArgs: [ + Number(start), + ...others + ], + then: ()=>isUI ? undefined : UI.setUISelectionClean(element) + }; + }); + prepareInterceptor(element, 'selectionStart', function interceptorImpl(v) { + return { + realArgs: v, + then: ()=>UI.setUISelectionClean(element) + }; + }); + prepareInterceptor(element, 'selectionEnd', function interceptorImpl(v) { + return { + realArgs: v, + then: ()=>UI.setUISelectionClean(element) + }; + }); + prepareInterceptor(element, 'select', function interceptorImpl() { + return { + realArgs: [], + then: ()=>UI.setUISelectionRaw(element, { + anchorOffset: 0, + focusOffset: UI.getUIValue(element).length + }) + }; + }); +} +function prepareRangeTextInterceptor(element) { + prepareInterceptor(element, 'setRangeText', function interceptorImpl(...realArgs) { + return { + realArgs, + then: ()=>{ + UI.setUIValueClean(element); + UI.setUISelectionClean(element); + } + }; + }); +} + +exports.prepareInterceptor = prepareInterceptor; +exports.prepareRangeTextInterceptor = prepareRangeTextInterceptor; +exports.prepareSelectionInterceptor = prepareSelectionInterceptor; +exports.prepareValueInterceptor = prepareValueInterceptor; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/patchFocus.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/patchFocus.js new file mode 100644 index 0000000000000000000000000000000000000000..69491b754d28fc0a492e336479d98360e4e00e83 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/patchFocus.js @@ -0,0 +1,104 @@ +'use strict'; + +var dispatchEvent = require('../event/dispatchEvent.js'); +require('../utils/dataTransfer/Clipboard.js'); +var getActiveElement = require('../utils/focus/getActiveElement.js'); +require('@testing-library/dom'); + +const patched = Symbol('patched focus/blur methods'); +function patchFocus(HTMLElement) { + if (HTMLElement.prototype[patched]) { + return; + } + // eslint-disable-next-line @typescript-eslint/unbound-method + const { focus, blur } = HTMLElement.prototype; + Object.defineProperties(HTMLElement.prototype, { + focus: { + configurable: true, + get: ()=>patchedFocus + }, + blur: { + configurable: true, + get: ()=>patchedBlur + }, + [patched]: { + configurable: true, + get: ()=>({ + focus, + blur + }) + } + }); + let activeCall; + function patchedFocus(options) { + if (this.ownerDocument.visibilityState !== 'hidden') { + return focus.call(this, options); + } + const blurred = getActiveTarget(this.ownerDocument); + if (blurred === this) { + return; + } + const thisCall = Symbol('focus call'); + activeCall = thisCall; + if (blurred) { + blur.call(blurred); + dispatchEvent.dispatchDOMEvent(blurred, 'blur', { + relatedTarget: this + }); + dispatchEvent.dispatchDOMEvent(blurred, 'focusout', { + relatedTarget: activeCall === thisCall ? this : null + }); + } + if (activeCall === thisCall) { + focus.call(this, options); + dispatchEvent.dispatchDOMEvent(this, 'focus', { + relatedTarget: blurred + }); + } + if (activeCall === thisCall) { + dispatchEvent.dispatchDOMEvent(this, 'focusin', { + relatedTarget: blurred + }); + } + } + function patchedBlur() { + if (this.ownerDocument.visibilityState !== 'hidden') { + return blur.call(this); + } + const blurred = getActiveTarget(this.ownerDocument); + if (blurred !== this) { + return; + } + const thisCall = Symbol('blur call'); + activeCall = thisCall; + blur.call(this); + dispatchEvent.dispatchDOMEvent(blurred, 'blur', { + relatedTarget: null + }); + dispatchEvent.dispatchDOMEvent(blurred, 'focusout', { + relatedTarget: null + }); + } +} +function getActiveTarget(document) { + const active = getActiveElement.getActiveElement(document); + return (active === null || active === undefined ? undefined : active.tagName) === 'BODY' ? null : active; +} +function restoreFocus(HTMLElement) { + if (HTMLElement.prototype[patched]) { + const { focus, blur } = HTMLElement.prototype[patched]; + Object.defineProperties(HTMLElement.prototype, { + focus: { + configurable: true, + get: ()=>focus + }, + blur: { + configurable: true, + get: ()=>blur + } + }); + } +} + +exports.patchFocus = patchFocus; +exports.restoreFocus = restoreFocus; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/prepareDocument.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/prepareDocument.js new file mode 100644 index 0000000000000000000000000000000000000000..39a24b8f2ccdc52739d130480ab18975073616cb --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/prepareDocument.js @@ -0,0 +1,58 @@ +'use strict'; + +var dispatchEvent = require('../event/dispatchEvent.js'); +var isElementType = require('../utils/misc/isElementType.js'); +require('../utils/dataTransfer/Clipboard.js'); +var UI = require('./UI.js'); +require('@testing-library/dom'); +var interceptor = require('./interceptor.js'); + +const isPrepared = Symbol('Node prepared with document state workarounds'); +function prepareDocument(document) { + if (document[isPrepared]) { + return; + } + document.addEventListener('focus', (e)=>{ + const el = e.target; + prepareElement(el); + }, { + capture: true, + passive: true + }); + // Our test environment defaults to `document.body` as `activeElement`. + // In other environments this might be `null` when preparing. + // istanbul ignore else + if (document.activeElement) { + prepareElement(document.activeElement); + } + document.addEventListener('blur', (e)=>{ + const el = e.target; + const initialValue = UI.getInitialValue(el); + if (initialValue !== undefined) { + if (el.value !== initialValue) { + dispatchEvent.dispatchDOMEvent(el, 'change'); + } + UI.clearInitialValue(el); + } + }, { + capture: true, + passive: true + }); + document[isPrepared] = isPrepared; +} +function prepareElement(el) { + if (el[isPrepared]) { + return; + } + if (isElementType.isElementType(el, [ + 'input', + 'textarea' + ])) { + interceptor.prepareValueInterceptor(el); + interceptor.prepareSelectionInterceptor(el); + interceptor.prepareRangeTextInterceptor(el); + } + el[isPrepared] = isPrepared; +} + +exports.prepareDocument = prepareDocument; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/trackValue.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/trackValue.js new file mode 100644 index 0000000000000000000000000000000000000000..7386f98d70c1aabb3ccd7e8a6d42118319b3ce2c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/document/trackValue.js @@ -0,0 +1,57 @@ +'use strict'; + +require('../utils/dataTransfer/Clipboard.js'); +var getWindow = require('../utils/misc/getWindow.js'); +var UI = require('./UI.js'); + +const TrackChanges = Symbol('Track programmatic changes for React workaround'); +// When the input event happens in the browser, React executes all event handlers +// and if they change state of a controlled value, nothing happens. +// But when we trigger the event handlers in test environment with React@17, +// the changes are rolled back before the state update is applied. +// This results in a reset cursor. +// There might be a better way to work around if we figure out +// why the batched update is executed differently in our test environment. +function isReact17Element(element) { + return Object.getOwnPropertyNames(element).some((k)=>k.startsWith('__react')) && getWindow.getWindow(element).REACT_VERSION === 17; +} +function startTrackValue(element) { + if (!isReact17Element(element)) { + return; + } + element[TrackChanges] = { + previousValue: String(element.value), + tracked: [] + }; +} +function trackOrSetValue(element, v) { + var _element_TrackChanges_tracked, _element_TrackChanges; + (_element_TrackChanges = element[TrackChanges]) === null || _element_TrackChanges === undefined ? undefined : (_element_TrackChanges_tracked = _element_TrackChanges.tracked) === null || _element_TrackChanges_tracked === undefined ? undefined : _element_TrackChanges_tracked.push(v); + if (!element[TrackChanges]) { + UI.setUIValueClean(element); + UI.setUISelection(element, { + focusOffset: v.length + }); + } +} +function commitValueAfterInput(element, cursorOffset) { + var _changes_tracked; + const changes = element[TrackChanges]; + element[TrackChanges] = undefined; + if (!(changes === null || changes === undefined ? undefined : (_changes_tracked = changes.tracked) === null || _changes_tracked === undefined ? undefined : _changes_tracked.length)) { + return; + } + const isJustReactStateUpdate = changes.tracked.length === 2 && changes.tracked[0] === changes.previousValue && changes.tracked[1] === element.value; + if (!isJustReactStateUpdate) { + UI.setUIValueClean(element); + } + if (UI.hasUISelection(element)) { + UI.setUISelection(element, { + focusOffset: isJustReactStateUpdate ? cursorOffset : element.value.length + }); + } +} + +exports.commitValueAfterInput = commitValueAfterInput; +exports.startTrackValue = startTrackValue; +exports.trackOrSetValue = trackOrSetValue; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/click.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/click.js new file mode 100644 index 0000000000000000000000000000000000000000..d486d7da8d7cc514400330874f965869e7b4b6e5 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/click.js @@ -0,0 +1,32 @@ +'use strict'; + +var isElementType = require('../../utils/misc/isElementType.js'); +require('../../utils/dataTransfer/Clipboard.js'); +var getWindow = require('../../utils/misc/getWindow.js'); +var isFocusable = require('../../utils/focus/isFocusable.js'); +var cloneEvent = require('../../utils/misc/cloneEvent.js'); +var focus = require('../focus.js'); +var registry = require('./registry.js'); + +registry.behavior.click = (event, target, instance)=>{ + const context = target.closest('button,input,label,select,textarea'); + const control = context && isElementType.isElementType(context, 'label') && context.control; + if (control && control !== target) { + return ()=>{ + if (isFocusable.isFocusable(control)) { + focus.focusElement(control); + instance.dispatchEvent(control, cloneEvent.cloneEvent(event)); + } + }; + } else if (isElementType.isElementType(target, 'input', { + type: 'file' + })) { + return ()=>{ + // blur fires when the file selector pops up + focus.blurElement(target); + target.dispatchEvent(new (getWindow.getWindow(target)).Event('fileDialog')); + // focus fires after the file selector has been closed + focus.focusElement(target); + }; + } +}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/cut.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/cut.js new file mode 100644 index 0000000000000000000000000000000000000000..581cc7c4c119380424cca7491eb3cde3d11ac042 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/cut.js @@ -0,0 +1,14 @@ +'use strict'; + +require('../../utils/dataTransfer/Clipboard.js'); +var isEditable = require('../../utils/edit/isEditable.js'); +var input = require('../input.js'); +var registry = require('./registry.js'); + +registry.behavior.cut = (event, target, instance)=>{ + return ()=>{ + if (isEditable.isEditable(target)) { + input.input(instance, target, '', 'deleteByCut'); + } + }; +}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bae0f26898904353c5aaace998d27572710ad4a7 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/index.js @@ -0,0 +1,13 @@ +'use strict'; + +require('./click.js'); +require('./cut.js'); +require('./keydown.js'); +require('./keypress.js'); +require('./keyup.js'); +require('./paste.js'); +var registry = require('./registry.js'); + + + +exports.behavior = registry.behavior; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/keydown.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/keydown.js new file mode 100644 index 0000000000000000000000000000000000000000..55027cb256f66b808d17280dc01bc55a796a1032 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/keydown.js @@ -0,0 +1,128 @@ +'use strict'; + +var UI = require('../../document/UI.js'); +var getValueOrTextContent = require('../../document/getValueOrTextContent.js'); +var isElementType = require('../../utils/misc/isElementType.js'); +require('../../utils/dataTransfer/Clipboard.js'); +var isContentEditable = require('../../utils/edit/isContentEditable.js'); +var isEditable = require('../../utils/edit/isEditable.js'); +var getTabDestination = require('../../utils/focus/getTabDestination.js'); +var selection = require('../../utils/focus/selection.js'); +var focus = require('../focus.js'); +var input = require('../input.js'); +var moveSelection = require('../selection/moveSelection.js'); +var selectAll = require('../selection/selectAll.js'); +var setSelectionRange = require('../selection/setSelectionRange.js'); +var radio = require('../radio.js'); +var registry = require('./registry.js'); + +registry.behavior.keydown = (event, target, instance)=>{ + var _keydownBehavior_event_key; + var _keydownBehavior_event_key1; + return (_keydownBehavior_event_key1 = (_keydownBehavior_event_key = keydownBehavior[event.key]) === null || _keydownBehavior_event_key === undefined ? undefined : _keydownBehavior_event_key.call(keydownBehavior, event, target, instance)) !== null && _keydownBehavior_event_key1 !== undefined ? _keydownBehavior_event_key1 : combinationBehavior(event, target, instance); +}; +const keydownBehavior = { + ArrowDown: (event, target, instance)=>{ + /* istanbul ignore else */ if (isElementType.isElementType(target, 'input', { + type: 'radio' + })) { + return ()=>radio.walkRadio(instance, target, 1); + } + }, + ArrowLeft: (event, target, instance)=>{ + if (isElementType.isElementType(target, 'input', { + type: 'radio' + })) { + return ()=>radio.walkRadio(instance, target, -1); + } + return ()=>moveSelection.moveSelection(target, -1); + }, + ArrowRight: (event, target, instance)=>{ + if (isElementType.isElementType(target, 'input', { + type: 'radio' + })) { + return ()=>radio.walkRadio(instance, target, 1); + } + return ()=>moveSelection.moveSelection(target, 1); + }, + ArrowUp: (event, target, instance)=>{ + /* istanbul ignore else */ if (isElementType.isElementType(target, 'input', { + type: 'radio' + })) { + return ()=>radio.walkRadio(instance, target, -1); + } + }, + Backspace: (event, target, instance)=>{ + if (isEditable.isEditable(target)) { + return ()=>{ + input.input(instance, target, '', 'deleteContentBackward'); + }; + } + }, + Delete: (event, target, instance)=>{ + if (isEditable.isEditable(target)) { + return ()=>{ + input.input(instance, target, '', 'deleteContentForward'); + }; + } + }, + End: (event, target)=>{ + if (isElementType.isElementType(target, [ + 'input', + 'textarea' + ]) || isContentEditable.isContentEditable(target)) { + return ()=>{ + var _getValueOrTextContent; + var _getValueOrTextContent_length; + const newPos = (_getValueOrTextContent_length = (_getValueOrTextContent = getValueOrTextContent.getValueOrTextContent(target)) === null || _getValueOrTextContent === undefined ? undefined : _getValueOrTextContent.length) !== null && _getValueOrTextContent_length !== undefined ? _getValueOrTextContent_length : /* istanbul ignore next */ 0; + setSelectionRange.setSelectionRange(target, newPos, newPos); + }; + } + }, + Home: (event, target)=>{ + if (isElementType.isElementType(target, [ + 'input', + 'textarea' + ]) || isContentEditable.isContentEditable(target)) { + return ()=>{ + setSelectionRange.setSelectionRange(target, 0, 0); + }; + } + }, + PageDown: (event, target)=>{ + if (isElementType.isElementType(target, [ + 'input' + ])) { + return ()=>{ + const newPos = UI.getUIValue(target).length; + setSelectionRange.setSelectionRange(target, newPos, newPos); + }; + } + }, + PageUp: (event, target)=>{ + if (isElementType.isElementType(target, [ + 'input' + ])) { + return ()=>{ + setSelectionRange.setSelectionRange(target, 0, 0); + }; + } + }, + Tab: (event, target, instance)=>{ + return ()=>{ + const dest = getTabDestination.getTabDestination(target, instance.system.keyboard.modifiers.Shift); + focus.focusElement(dest); + if (selection.hasOwnSelection(dest)) { + UI.setUISelection(dest, { + anchorOffset: 0, + focusOffset: dest.value.length + }); + } + }; + } +}; +const combinationBehavior = (event, target, instance)=>{ + if (event.code === 'KeyA' && instance.system.keyboard.modifiers.Control) { + return ()=>selectAll.selectAll(target); + } +}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/keypress.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/keypress.js new file mode 100644 index 0000000000000000000000000000000000000000..9489336b155ff9d056d1b896bc02bfd94e1c88c6 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/keypress.js @@ -0,0 +1,51 @@ +'use strict'; + +var isElementType = require('../../utils/misc/isElementType.js'); +require('../../utils/dataTransfer/Clipboard.js'); +var isContentEditable = require('../../utils/edit/isContentEditable.js'); +var isEditable = require('../../utils/edit/isEditable.js'); +var input = require('../input.js'); +var registry = require('./registry.js'); + +registry.behavior.keypress = (event, target, instance)=>{ + if (event.key === 'Enter') { + if (isElementType.isElementType(target, 'button') || isElementType.isElementType(target, 'input') && ClickInputOnEnter.includes(target.type) || isElementType.isElementType(target, 'a') && Boolean(target.href)) { + return ()=>{ + instance.dispatchUIEvent(target, 'click'); + }; + } else if (isElementType.isElementType(target, 'input')) { + const form = target.form; + const submit = form === null || form === undefined ? undefined : form.querySelector('input[type="submit"], button:not([type]), button[type="submit"]'); + if (submit) { + return ()=>instance.dispatchUIEvent(submit, 'click'); + } else if (form && SubmitSingleInputOnEnter.includes(target.type) && form.querySelectorAll('input').length === 1) { + return ()=>instance.dispatchUIEvent(form, 'submit'); + } else { + return; + } + } + } + if (isEditable.isEditable(target)) { + const inputType = event.key === 'Enter' ? isContentEditable.isContentEditable(target) && !instance.system.keyboard.modifiers.Shift ? 'insertParagraph' : 'insertLineBreak' : 'insertText'; + const inputData = event.key === 'Enter' ? '\n' : event.key; + return ()=>input.input(instance, target, inputData, inputType); + } +}; +const ClickInputOnEnter = [ + 'button', + 'color', + 'file', + 'image', + 'reset', + 'submit' +]; +const SubmitSingleInputOnEnter = [ + 'email', + 'month', + 'password', + 'search', + 'tel', + 'text', + 'url', + 'week' +]; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/keyup.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/keyup.js new file mode 100644 index 0000000000000000000000000000000000000000..5167a9840c45eaddfa3829721dee03a328010af0 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/keyup.js @@ -0,0 +1,17 @@ +'use strict'; + +var isClickableInput = require('../../utils/click/isClickableInput.js'); +require('../../utils/dataTransfer/Clipboard.js'); +var registry = require('./registry.js'); + +registry.behavior.keyup = (event, target, instance)=>{ + var _keyupBehavior_event_key; + return (_keyupBehavior_event_key = keyupBehavior[event.key]) === null || _keyupBehavior_event_key === undefined ? undefined : _keyupBehavior_event_key.call(keyupBehavior, event, target, instance); +}; +const keyupBehavior = { + ' ': (event, target, instance)=>{ + if (isClickableInput.isClickableInput(target)) { + return ()=>instance.dispatchUIEvent(target, 'click'); + } + } +}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/paste.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/paste.js new file mode 100644 index 0000000000000000000000000000000000000000..cdda58cac6c8d9cd200a575139e5840ef2aefcba --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/paste.js @@ -0,0 +1,18 @@ +'use strict'; + +require('../../utils/dataTransfer/Clipboard.js'); +var isEditable = require('../../utils/edit/isEditable.js'); +var input = require('../input.js'); +var registry = require('./registry.js'); + +registry.behavior.paste = (event, target, instance)=>{ + if (isEditable.isEditable(target)) { + return ()=>{ + var _event_clipboardData; + const insertData = (_event_clipboardData = event.clipboardData) === null || _event_clipboardData === undefined ? undefined : _event_clipboardData.getData('text'); + if (insertData) { + input.input(instance, target, insertData, 'insertFromPaste'); + } + }; + } +}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/registry.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/registry.js new file mode 100644 index 0000000000000000000000000000000000000000..c060733b6439b66e002e435fad3cd9522eab24a3 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/behavior/registry.js @@ -0,0 +1,5 @@ +'use strict'; + +const behavior = {}; + +exports.behavior = behavior; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/createEvent.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/createEvent.js new file mode 100644 index 0000000000000000000000000000000000000000..b63c0093f492f5072ce2eabb74ca290144353548 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/createEvent.js @@ -0,0 +1,207 @@ +'use strict'; + +require('../utils/dataTransfer/Clipboard.js'); +var getWindow = require('../utils/misc/getWindow.js'); +var eventMap = require('./eventMap.js'); + +const eventInitializer = { + ClipboardEvent: [ + initClipboardEvent + ], + Event: [], + FocusEvent: [ + initUIEvent, + initFocusEvent + ], + InputEvent: [ + initUIEvent, + initInputEvent + ], + MouseEvent: [ + initUIEvent, + initUIEventModifiers, + initMouseEvent + ], + PointerEvent: [ + initUIEvent, + initUIEventModifiers, + initMouseEvent, + initPointerEvent + ], + KeyboardEvent: [ + initUIEvent, + initUIEventModifiers, + initKeyboardEvent + ] +}; +function createEvent(type, target, init) { + const window = getWindow.getWindow(target); + const { EventType, defaultInit } = eventMap.eventMap[type]; + const event = new (getEventConstructors(window))[EventType](type, defaultInit); + eventInitializer[EventType].forEach((f)=>f(event, init !== null && init !== undefined ? init : {})); + return event; +} +/* istanbul ignore next */ function getEventConstructors(window) { + var _window_Event; + /* eslint-disable @typescript-eslint/no-unnecessary-condition, @typescript-eslint/no-extraneous-class */ const Event = (_window_Event = window.Event) !== null && _window_Event !== undefined ? _window_Event : class Event { + }; + var _window_AnimationEvent; + const AnimationEvent = (_window_AnimationEvent = window.AnimationEvent) !== null && _window_AnimationEvent !== undefined ? _window_AnimationEvent : class AnimationEvent extends Event { + }; + var _window_ClipboardEvent; + const ClipboardEvent = (_window_ClipboardEvent = window.ClipboardEvent) !== null && _window_ClipboardEvent !== undefined ? _window_ClipboardEvent : class ClipboardEvent extends Event { + }; + var _window_PopStateEvent; + const PopStateEvent = (_window_PopStateEvent = window.PopStateEvent) !== null && _window_PopStateEvent !== undefined ? _window_PopStateEvent : class PopStateEvent extends Event { + }; + var _window_ProgressEvent; + const ProgressEvent = (_window_ProgressEvent = window.ProgressEvent) !== null && _window_ProgressEvent !== undefined ? _window_ProgressEvent : class ProgressEvent extends Event { + }; + var _window_TransitionEvent; + const TransitionEvent = (_window_TransitionEvent = window.TransitionEvent) !== null && _window_TransitionEvent !== undefined ? _window_TransitionEvent : class TransitionEvent extends Event { + }; + var _window_UIEvent; + const UIEvent = (_window_UIEvent = window.UIEvent) !== null && _window_UIEvent !== undefined ? _window_UIEvent : class UIEvent extends Event { + }; + var _window_CompositionEvent; + const CompositionEvent = (_window_CompositionEvent = window.CompositionEvent) !== null && _window_CompositionEvent !== undefined ? _window_CompositionEvent : class CompositionEvent extends UIEvent { + }; + var _window_FocusEvent; + const FocusEvent = (_window_FocusEvent = window.FocusEvent) !== null && _window_FocusEvent !== undefined ? _window_FocusEvent : class FocusEvent extends UIEvent { + }; + var _window_InputEvent; + const InputEvent = (_window_InputEvent = window.InputEvent) !== null && _window_InputEvent !== undefined ? _window_InputEvent : class InputEvent extends UIEvent { + }; + var _window_KeyboardEvent; + const KeyboardEvent = (_window_KeyboardEvent = window.KeyboardEvent) !== null && _window_KeyboardEvent !== undefined ? _window_KeyboardEvent : class KeyboardEvent extends UIEvent { + }; + var _window_MouseEvent; + const MouseEvent = (_window_MouseEvent = window.MouseEvent) !== null && _window_MouseEvent !== undefined ? _window_MouseEvent : class MouseEvent extends UIEvent { + }; + var _window_DragEvent; + const DragEvent = (_window_DragEvent = window.DragEvent) !== null && _window_DragEvent !== undefined ? _window_DragEvent : class DragEvent extends MouseEvent { + }; + var _window_PointerEvent; + const PointerEvent = (_window_PointerEvent = window.PointerEvent) !== null && _window_PointerEvent !== undefined ? _window_PointerEvent : class PointerEvent extends MouseEvent { + }; + var _window_TouchEvent; + const TouchEvent = (_window_TouchEvent = window.TouchEvent) !== null && _window_TouchEvent !== undefined ? _window_TouchEvent : class TouchEvent extends UIEvent { + }; + /* eslint-enable @typescript-eslint/no-unnecessary-condition, @typescript-eslint/no-extraneous-class */ return { + Event, + AnimationEvent, + ClipboardEvent, + PopStateEvent, + ProgressEvent, + TransitionEvent, + UIEvent, + CompositionEvent, + FocusEvent, + InputEvent, + KeyboardEvent, + MouseEvent, + DragEvent, + PointerEvent, + TouchEvent + }; +} +function assignProps(obj, props) { + for (const [key, value] of Object.entries(props)){ + Object.defineProperty(obj, key, { + get: ()=>value !== null && value !== undefined ? value : null + }); + } +} +function sanitizeNumber(n) { + return Number(n !== null && n !== undefined ? n : 0); +} +function initClipboardEvent(event, { clipboardData }) { + assignProps(event, { + clipboardData + }); +} +function initFocusEvent(event, { relatedTarget }) { + assignProps(event, { + relatedTarget + }); +} +function initInputEvent(event, { data, inputType, isComposing }) { + assignProps(event, { + data, + isComposing: Boolean(isComposing), + inputType: String(inputType) + }); +} +function initUIEvent(event, { view, detail }) { + assignProps(event, { + view, + detail: sanitizeNumber(detail !== null && detail !== undefined ? detail : 0) + }); +} +function initUIEventModifiers(event, { altKey, ctrlKey, metaKey, shiftKey, modifierAltGraph, modifierCapsLock, modifierFn, modifierFnLock, modifierNumLock, modifierScrollLock, modifierSymbol, modifierSymbolLock }) { + assignProps(event, { + altKey: Boolean(altKey), + ctrlKey: Boolean(ctrlKey), + metaKey: Boolean(metaKey), + shiftKey: Boolean(shiftKey), + getModifierState (k) { + return Boolean({ + Alt: altKey, + AltGraph: modifierAltGraph, + CapsLock: modifierCapsLock, + Control: ctrlKey, + Fn: modifierFn, + FnLock: modifierFnLock, + Meta: metaKey, + NumLock: modifierNumLock, + ScrollLock: modifierScrollLock, + Shift: shiftKey, + Symbol: modifierSymbol, + SymbolLock: modifierSymbolLock + }[k]); + } + }); +} +function initKeyboardEvent(event, { key, code, location, repeat, isComposing, charCode }) { + assignProps(event, { + key: String(key), + code: String(code), + location: sanitizeNumber(location), + repeat: Boolean(repeat), + isComposing: Boolean(isComposing), + charCode + }); +} +function initMouseEvent(event, { x, y, screenX, screenY, clientX = x, clientY = y, button, buttons, relatedTarget, offsetX, offsetY, pageX, pageY }) { + assignProps(event, { + screenX: sanitizeNumber(screenX), + screenY: sanitizeNumber(screenY), + clientX: sanitizeNumber(clientX), + x: sanitizeNumber(clientX), + clientY: sanitizeNumber(clientY), + y: sanitizeNumber(clientY), + button: sanitizeNumber(button), + buttons: sanitizeNumber(buttons), + relatedTarget, + offsetX: sanitizeNumber(offsetX), + offsetY: sanitizeNumber(offsetY), + pageX: sanitizeNumber(pageX), + pageY: sanitizeNumber(pageY) + }); +} +function initPointerEvent(event, { pointerId, width, height, pressure, tangentialPressure, tiltX, tiltY, twist, pointerType, isPrimary }) { + assignProps(event, { + pointerId: sanitizeNumber(pointerId), + width: sanitizeNumber(width !== null && width !== undefined ? width : 1), + height: sanitizeNumber(height !== null && height !== undefined ? height : 1), + pressure: sanitizeNumber(pressure), + tangentialPressure: sanitizeNumber(tangentialPressure), + tiltX: sanitizeNumber(tiltX), + tiltY: sanitizeNumber(tiltY), + twist: sanitizeNumber(twist), + pointerType: String(pointerType), + isPrimary: Boolean(isPrimary) + }); +} + +exports.createEvent = createEvent; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/dispatchEvent.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/dispatchEvent.js new file mode 100644 index 0000000000000000000000000000000000000000..8d06d6db0d5bfcccf971803772202eff9bd68027 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/dispatchEvent.js @@ -0,0 +1,54 @@ +'use strict'; + +require('./behavior/click.js'); +require('./behavior/cut.js'); +require('./behavior/keydown.js'); +require('./behavior/keypress.js'); +require('./behavior/keyup.js'); +require('./behavior/paste.js'); +var registry = require('./behavior/registry.js'); +var wrapEvent = require('./wrapEvent.js'); +var eventMap = require('./eventMap.js'); +var createEvent = require('./createEvent.js'); + +function dispatchUIEvent(target, type, init, preventDefault = false) { + if (eventMap.isMouseEvent(type) || eventMap.isKeyboardEvent(type)) { + init = { + ...init, + ...this.system.getUIEventModifiers() + }; + } + const event = createEvent.createEvent(type, target, init); + return dispatchEvent.call(this, target, event, preventDefault); +} +function dispatchEvent(target, event, preventDefault = false) { + var _behavior_type; + const type = event.type; + const behaviorImplementation = preventDefault ? ()=>{} : (_behavior_type = registry.behavior[type]) === null || _behavior_type === undefined ? undefined : _behavior_type.call(registry.behavior, event, target, this); + if (behaviorImplementation) { + event.preventDefault(); + let defaultPrevented = false; + Object.defineProperty(event, 'defaultPrevented', { + get: ()=>defaultPrevented + }); + Object.defineProperty(event, 'preventDefault', { + value: ()=>{ + defaultPrevented = event.cancelable; + } + }); + wrapEvent.wrapEvent(()=>target.dispatchEvent(event)); + if (!defaultPrevented) { + behaviorImplementation(); + } + return !defaultPrevented; + } + return wrapEvent.wrapEvent(()=>target.dispatchEvent(event)); +} +function dispatchDOMEvent(target, type, init) { + const event = createEvent.createEvent(type, target, init); + wrapEvent.wrapEvent(()=>target.dispatchEvent(event)); +} + +exports.dispatchDOMEvent = dispatchDOMEvent; +exports.dispatchEvent = dispatchEvent; +exports.dispatchUIEvent = dispatchUIEvent; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/eventMap.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/eventMap.js new file mode 100644 index 0000000000000000000000000000000000000000..c782d8aa93ca3093725d15125312b55fc7253dc2 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/eventMap.js @@ -0,0 +1,281 @@ +'use strict'; + +const eventMap = { + auxclick: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + beforeinput: { + EventType: 'InputEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + blur: { + EventType: 'FocusEvent', + defaultInit: { + bubbles: false, + cancelable: false, + composed: true + } + }, + click: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + contextmenu: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + copy: { + EventType: 'ClipboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + change: { + EventType: 'Event', + defaultInit: { + bubbles: true, + cancelable: false + } + }, + cut: { + EventType: 'ClipboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + dblclick: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + focus: { + EventType: 'FocusEvent', + defaultInit: { + bubbles: false, + cancelable: false, + composed: true + } + }, + focusin: { + EventType: 'FocusEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + focusout: { + EventType: 'FocusEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + keydown: { + EventType: 'KeyboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + keypress: { + EventType: 'KeyboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + keyup: { + EventType: 'KeyboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + paste: { + EventType: 'ClipboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + input: { + EventType: 'InputEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + mousedown: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseenter: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: false, + cancelable: false, + composed: true + } + }, + mouseleave: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: false, + cancelable: false, + composed: true + } + }, + mousemove: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseout: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseover: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseup: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + pointerover: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + pointerenter: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + pointerdown: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + pointermove: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + pointerup: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + pointercancel: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + pointerout: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + pointerleave: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + submit: { + EventType: 'Event', + defaultInit: { + bubbles: true, + cancelable: true + } + } +}; +function getEventClass(type) { + return eventMap[type].EventType; +} +const mouseEvents = [ + 'MouseEvent', + 'PointerEvent' +]; +function isMouseEvent(type) { + return mouseEvents.includes(getEventClass(type)); +} +function isKeyboardEvent(type) { + return getEventClass(type) === 'KeyboardEvent'; +} + +exports.eventMap = eventMap; +exports.isKeyboardEvent = isKeyboardEvent; +exports.isMouseEvent = isMouseEvent; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/focus.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/focus.js new file mode 100644 index 0000000000000000000000000000000000000000..b344f35e482ae35e11d07754de613a46afe11d7d --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/focus.js @@ -0,0 +1,34 @@ +'use strict'; + +require('../utils/dataTransfer/Clipboard.js'); +var getActiveElement = require('../utils/focus/getActiveElement.js'); +var isFocusable = require('../utils/focus/isFocusable.js'); +var findClosest = require('../utils/misc/findClosest.js'); +var updateSelectionOnFocus = require('./selection/updateSelectionOnFocus.js'); +var wrapEvent = require('./wrapEvent.js'); + +// Browsers do not dispatch FocusEvent if the document does not have focus. +// TODO: simulate FocusEvent in browsers +/** + * Focus closest focusable element. + */ function focusElement(element) { + const target = findClosest.findClosest(element, isFocusable.isFocusable); + const activeElement = getActiveElement.getActiveElement(element.ownerDocument); + if ((target !== null && target !== undefined ? target : element.ownerDocument.body) === activeElement) { + return; + } else if (target) { + wrapEvent.wrapEvent(()=>target.focus()); + } else { + wrapEvent.wrapEvent(()=>activeElement === null || activeElement === undefined ? undefined : activeElement.blur()); + } + updateSelectionOnFocus.updateSelectionOnFocus(target !== null && target !== undefined ? target : element.ownerDocument.body); +} +function blurElement(element) { + if (!isFocusable.isFocusable(element)) return; + const wasActive = getActiveElement.getActiveElement(element.ownerDocument) === element; + if (!wasActive) return; + wrapEvent.wrapEvent(()=>element.blur()); +} + +exports.blurElement = blurElement; +exports.focusElement = focusElement; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/index.js new file mode 100644 index 0000000000000000000000000000000000000000..eedcf058e473bfc19307ea104a56b95f9ac6a7c3 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/index.js @@ -0,0 +1,22 @@ +'use strict'; + +var dispatchEvent = require('./dispatchEvent.js'); +var focus = require('./focus.js'); +var input = require('./input.js'); +require('../utils/dataTransfer/Clipboard.js'); +var setSelectionPerMouse = require('./selection/setSelectionPerMouse.js'); +var modifySelectionPerMouse = require('./selection/modifySelectionPerMouse.js'); +var selectAll = require('./selection/selectAll.js'); + + + +exports.dispatchDOMEvent = dispatchEvent.dispatchDOMEvent; +exports.dispatchEvent = dispatchEvent.dispatchEvent; +exports.dispatchUIEvent = dispatchEvent.dispatchUIEvent; +exports.blurElement = focus.blurElement; +exports.focusElement = focus.focusElement; +exports.input = input.input; +exports.setSelectionPerMouseDown = setSelectionPerMouse.setSelectionPerMouseDown; +exports.modifySelectionPerMouseMove = modifySelectionPerMouse.modifySelectionPerMouseMove; +exports.isAllSelected = selectAll.isAllSelected; +exports.selectAll = selectAll.selectAll; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/input.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/input.js new file mode 100644 index 0000000000000000000000000000000000000000..aec8a858c0788fe650492ffdfeddb2116cf30001 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/input.js @@ -0,0 +1,157 @@ +'use strict'; + +var UI = require('../document/UI.js'); +var isElementType = require('../utils/misc/isElementType.js'); +require('../utils/dataTransfer/Clipboard.js'); +var timeValue = require('../utils/edit/timeValue.js'); +var maxLength = require('../utils/edit/maxLength.js'); +var cursor = require('../utils/focus/cursor.js'); +var trackValue = require('../document/trackValue.js'); +var getInputRange = require('./selection/getInputRange.js'); +var setSelection = require('./selection/setSelection.js'); + +function isDateOrTime(element) { + return isElementType.isElementType(element, 'input') && [ + 'date', + 'time' + ].includes(element.type); +} +function input(instance, element, data, inputType = 'insertText') { + const inputRange = getInputRange.getInputRange(element); + /* istanbul ignore if */ if (!inputRange) { + return; + } + // There is no `beforeinput` event on `date` and `time` input + if (!isDateOrTime(element)) { + const unprevented = instance.dispatchUIEvent(element, 'beforeinput', { + inputType, + data + }); + if (!unprevented) { + return; + } + } + if ('startContainer' in inputRange) { + editContenteditable(instance, element, inputRange, data, inputType); + } else { + editInputElement(instance, element, inputRange, data, inputType); + } +} +function editContenteditable(instance, element, inputRange, data, inputType) { + let del = false; + if (!inputRange.collapsed) { + del = true; + inputRange.deleteContents(); + } else if ([ + 'deleteContentBackward', + 'deleteContentForward' + ].includes(inputType)) { + const nextPosition = cursor.getNextCursorPosition(inputRange.startContainer, inputRange.startOffset, inputType === 'deleteContentBackward' ? -1 : 1, inputType); + if (nextPosition) { + del = true; + const delRange = inputRange.cloneRange(); + if (delRange.comparePoint(nextPosition.node, nextPosition.offset) < 0) { + delRange.setStart(nextPosition.node, nextPosition.offset); + } else { + delRange.setEnd(nextPosition.node, nextPosition.offset); + } + delRange.deleteContents(); + } + } + if (data) { + if (inputRange.endContainer.nodeType === 3) { + const offset = inputRange.endOffset; + inputRange.endContainer.insertData(offset, data); + inputRange.setStart(inputRange.endContainer, offset + data.length); + inputRange.setEnd(inputRange.endContainer, offset + data.length); + } else { + const text = element.ownerDocument.createTextNode(data); + inputRange.insertNode(text); + inputRange.setStart(text, data.length); + inputRange.setEnd(text, data.length); + } + } + if (del || data) { + instance.dispatchUIEvent(element, 'input', { + inputType + }); + } +} +function editInputElement(instance, element, inputRange, data, inputType) { + let dataToInsert = data; + if (maxLength.supportsMaxLength(element)) { + const maxLength$1 = maxLength.getMaxLength(element); + if (maxLength$1 !== undefined && data.length > 0) { + const spaceUntilMaxLength = maxLength$1 - element.value.length; + if (spaceUntilMaxLength > 0) { + dataToInsert = data.substring(0, spaceUntilMaxLength); + } else { + return; + } + } + } + const { newValue, newOffset, oldValue } = calculateNewValue(dataToInsert, element, inputRange, inputType); + if (newValue === oldValue && newOffset === inputRange.startOffset && newOffset === inputRange.endOffset) { + return; + } + if (isElementType.isElementType(element, 'input', { + type: 'number' + }) && !isValidNumberInput(newValue)) { + return; + } + UI.setUIValue(element, newValue); + setSelection.setSelection({ + focusNode: element, + anchorOffset: newOffset, + focusOffset: newOffset + }); + if (isDateOrTime(element)) { + if (timeValue.isValidDateOrTimeValue(element, newValue)) { + commitInput(instance, element, newOffset, {}); + instance.dispatchUIEvent(element, 'change'); + UI.clearInitialValue(element); + } + } else { + commitInput(instance, element, newOffset, { + data, + inputType + }); + } +} +function calculateNewValue(inputData, node, { startOffset, endOffset }, inputType) { + const value = UI.getUIValue(node); + const prologEnd = Math.max(0, startOffset === endOffset && inputType === 'deleteContentBackward' ? startOffset - 1 : startOffset); + const prolog = value.substring(0, prologEnd); + const epilogStart = Math.min(value.length, startOffset === endOffset && inputType === 'deleteContentForward' ? startOffset + 1 : endOffset); + const epilog = value.substring(epilogStart, value.length); + let newValue = `${prolog}${inputData}${epilog}`; + let newOffset = prologEnd + inputData.length; + if (isElementType.isElementType(node, 'input', { + type: 'time' + })) { + const builtValue = timeValue.buildTimeValue(newValue); + if (builtValue !== '' && timeValue.isValidDateOrTimeValue(node, builtValue)) { + newValue = builtValue; + newOffset = builtValue.length; + } + } + return { + oldValue: value, + newValue, + newOffset + }; +} +function commitInput(instance, element, newOffset, inputInit) { + instance.dispatchUIEvent(element, 'input', inputInit); + trackValue.commitValueAfterInput(element, newOffset); +} +function isValidNumberInput(value) { + var _value_match, _value_match1; + // the browser allows some invalid input but not others + // it allows up to two '-' at any place before any 'e' or one directly following 'e' + // it allows one '.' at any place before e + const valueParts = value.split('e', 2); + return !(/[^\d.\-e]/.test(value) || Number((_value_match = value.match(/-/g)) === null || _value_match === undefined ? undefined : _value_match.length) > 2 || Number((_value_match1 = value.match(/\./g)) === null || _value_match1 === undefined ? undefined : _value_match1.length) > 1 || valueParts[1] && !/^-?\d*$/.test(valueParts[1])); +} + +exports.input = input; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/radio.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/radio.js new file mode 100644 index 0000000000000000000000000000000000000000..27cac7966f57cf40e2df9afc5d1c8d5133c9ccb3 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/radio.js @@ -0,0 +1,27 @@ +'use strict'; + +require('../utils/dataTransfer/Clipboard.js'); +var isDisabled = require('../utils/misc/isDisabled.js'); +var getWindow = require('../utils/misc/getWindow.js'); +var focus = require('./focus.js'); + +function walkRadio(instance, el, direction) { + const window = getWindow.getWindow(el); + const group = Array.from(el.ownerDocument.querySelectorAll(el.name ? `input[type="radio"][name="${window.CSS.escape(el.name)}"]` : `input[type="radio"][name=""], input[type="radio"]:not([name])`)); + for(let i = group.findIndex((e)=>e === el) + direction;; i += direction){ + if (!group[i]) { + i = direction > 0 ? 0 : group.length - 1; + } + if (group[i] === el) { + return; + } + if (isDisabled.isDisabled(group[i])) { + continue; + } + focus.focusElement(group[i]); + instance.dispatchUIEvent(group[i], 'click'); + return; + } +} + +exports.walkRadio = walkRadio; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/getInputRange.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/getInputRange.js new file mode 100644 index 0000000000000000000000000000000000000000..6dab0cb5d0f273b1ac3082411c856f805d32de16 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/getInputRange.js @@ -0,0 +1,18 @@ +'use strict'; + +var getTargetTypeAndSelection = require('./getTargetTypeAndSelection.js'); + +/** + * Get the range that would be overwritten by input. + */ function getInputRange(focusNode) { + const typeAndSelection = getTargetTypeAndSelection.getTargetTypeAndSelection(focusNode); + if (typeAndSelection.type === 'input') { + return typeAndSelection.selection; + } else if (typeAndSelection.type === 'contenteditable') { + var _typeAndSelection_selection; + // Multi-range on contenteditable edits the first selection instead of the last + return (_typeAndSelection_selection = typeAndSelection.selection) === null || _typeAndSelection_selection === undefined ? undefined : _typeAndSelection_selection.getRangeAt(0); + } +} + +exports.getInputRange = getInputRange; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/getTargetTypeAndSelection.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/getTargetTypeAndSelection.js new file mode 100644 index 0000000000000000000000000000000000000000..40d4d7dd2301ee1777ed6e4094066f2b50876187 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/getTargetTypeAndSelection.js @@ -0,0 +1,31 @@ +'use strict'; + +var UI = require('../../document/UI.js'); +require('../../utils/dataTransfer/Clipboard.js'); +var isContentEditable = require('../../utils/edit/isContentEditable.js'); +var selection = require('../../utils/focus/selection.js'); + +/** + * Determine which selection logic and selection ranges to consider. + */ function getTargetTypeAndSelection(node) { + const element = getElement(node); + if (element && selection.hasOwnSelection(element)) { + return { + type: 'input', + selection: UI.getUISelection(element) + }; + } + const selection$1 = element === null || element === undefined ? undefined : element.ownerDocument.getSelection(); + // It is possible to extend a single-range selection into a contenteditable. + // This results in the range acting like a range outside of contenteditable. + const isCE = isContentEditable.getContentEditable(node) && (selection$1 === null || selection$1 === undefined ? undefined : selection$1.anchorNode) && isContentEditable.getContentEditable(selection$1.anchorNode); + return { + type: isCE ? 'contenteditable' : 'default', + selection: selection$1 + }; +} +function getElement(node) { + return node.nodeType === 1 ? node : node.parentElement; +} + +exports.getTargetTypeAndSelection = getTargetTypeAndSelection; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1fbea3d3ae3c0f59561539e23d4835b63c78573a --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/index.js @@ -0,0 +1,24 @@ +'use strict'; + +var getInputRange = require('./getInputRange.js'); +var modifySelection = require('./modifySelection.js'); +var moveSelection = require('./moveSelection.js'); +var setSelectionPerMouse = require('./setSelectionPerMouse.js'); +var modifySelectionPerMouse = require('./modifySelectionPerMouse.js'); +var selectAll = require('./selectAll.js'); +var setSelectionRange = require('./setSelectionRange.js'); +var setSelection = require('./setSelection.js'); +var updateSelectionOnFocus = require('./updateSelectionOnFocus.js'); + + + +exports.getInputRange = getInputRange.getInputRange; +exports.modifySelection = modifySelection.modifySelection; +exports.moveSelection = moveSelection.moveSelection; +exports.setSelectionPerMouseDown = setSelectionPerMouse.setSelectionPerMouseDown; +exports.modifySelectionPerMouseMove = modifySelectionPerMouse.modifySelectionPerMouseMove; +exports.isAllSelected = selectAll.isAllSelected; +exports.selectAll = selectAll.selectAll; +exports.setSelectionRange = setSelectionRange.setSelectionRange; +exports.setSelection = setSelection.setSelection; +exports.updateSelectionOnFocus = updateSelectionOnFocus.updateSelectionOnFocus; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/modifySelection.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/modifySelection.js new file mode 100644 index 0000000000000000000000000000000000000000..d808edcc9ad17341b7c0d7fecff93a10219e8d04 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/modifySelection.js @@ -0,0 +1,21 @@ +'use strict'; + +var UI = require('../../document/UI.js'); +require('../../utils/dataTransfer/Clipboard.js'); +var getTargetTypeAndSelection = require('./getTargetTypeAndSelection.js'); + +/** + * Extend/shrink the selection like with Shift+Arrows or Shift+Mouse + */ function modifySelection({ focusNode, focusOffset }) { + var _focusNode_ownerDocument_getSelection, _focusNode_ownerDocument; + const typeAndSelection = getTargetTypeAndSelection.getTargetTypeAndSelection(focusNode); + if (typeAndSelection.type === 'input') { + return UI.setUISelection(focusNode, { + anchorOffset: typeAndSelection.selection.anchorOffset, + focusOffset + }, 'modify'); + } + (_focusNode_ownerDocument = focusNode.ownerDocument) === null || _focusNode_ownerDocument === undefined ? undefined : (_focusNode_ownerDocument_getSelection = _focusNode_ownerDocument.getSelection()) === null || _focusNode_ownerDocument_getSelection === undefined ? undefined : _focusNode_ownerDocument_getSelection.extend(focusNode, focusOffset); +} + +exports.modifySelection = modifySelection; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/modifySelectionPerMouse.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/modifySelectionPerMouse.js new file mode 100644 index 0000000000000000000000000000000000000000..47e800a255d5b64e62cc516d3149e77eca48c980 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/modifySelectionPerMouse.js @@ -0,0 +1,40 @@ +'use strict'; + +var UI = require('../../document/UI.js'); +require('../../utils/dataTransfer/Clipboard.js'); +var resolveCaretPosition = require('./resolveCaretPosition.js'); + +function modifySelectionPerMouseMove(selectionRange, { document, target, node, offset }) { + const selectionFocus = resolveCaretPosition.resolveCaretPosition({ + target, + node, + offset + }); + if ('node' in selectionRange) { + // When the mouse is dragged outside of an input/textarea, + // the selection is extended to the beginning or end of the input + // depending on pointer position. + // TODO: extend selection according to pointer position + /* istanbul ignore else */ if (selectionFocus.node === selectionRange.node) { + const anchorOffset = selectionFocus.offset < selectionRange.start ? selectionRange.end : selectionRange.start; + const focusOffset = selectionFocus.offset > selectionRange.end || selectionFocus.offset < selectionRange.start ? selectionFocus.offset : selectionRange.end; + UI.setUISelection(selectionRange.node, { + anchorOffset, + focusOffset + }); + } + } else { + const range = selectionRange.cloneRange(); + const cmp = range.comparePoint(selectionFocus.node, selectionFocus.offset); + if (cmp < 0) { + range.setStart(selectionFocus.node, selectionFocus.offset); + } else if (cmp > 0) { + range.setEnd(selectionFocus.node, selectionFocus.offset); + } + const selection = document.getSelection(); + selection === null || selection === undefined ? undefined : selection.removeAllRanges(); + selection === null || selection === undefined ? undefined : selection.addRange(range.cloneRange()); + } +} + +exports.modifySelectionPerMouseMove = modifySelectionPerMouseMove; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/moveSelection.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/moveSelection.js new file mode 100644 index 0000000000000000000000000000000000000000..72c85cbd161e3b80f702116c77b3241dcfe058f2 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/moveSelection.js @@ -0,0 +1,38 @@ +'use strict'; + +var UI = require('../../document/UI.js'); +require('../../utils/dataTransfer/Clipboard.js'); +var cursor = require('../../utils/focus/cursor.js'); +var selection = require('../../utils/focus/selection.js'); +var setSelection = require('./setSelection.js'); + +/** + * Move the selection + */ function moveSelection(node, direction) { + // TODO: implement shift + if (selection.hasOwnSelection(node)) { + const selection = UI.getUISelection(node); + setSelection.setSelection({ + focusNode: node, + focusOffset: selection.startOffset === selection.endOffset ? selection.focusOffset + direction : direction < 0 ? selection.startOffset : selection.endOffset + }); + } else { + const selection = node.ownerDocument.getSelection(); + if (!(selection === null || selection === undefined ? undefined : selection.focusNode)) { + return; + } + if (selection.isCollapsed) { + const nextPosition = cursor.getNextCursorPosition(selection.focusNode, selection.focusOffset, direction); + if (nextPosition) { + setSelection.setSelection({ + focusNode: nextPosition.node, + focusOffset: nextPosition.offset + }); + } + } else { + selection[direction < 0 ? 'collapseToStart' : 'collapseToEnd'](); + } + } +} + +exports.moveSelection = moveSelection; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/resolveCaretPosition.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/resolveCaretPosition.js new file mode 100644 index 0000000000000000000000000000000000000000..b6f16d2871b42cf8ca19e1e81b2220ec4c1b7325 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/resolveCaretPosition.js @@ -0,0 +1,61 @@ +'use strict'; + +var UI = require('../../document/UI.js'); +require('../../utils/dataTransfer/Clipboard.js'); +var selection = require('../../utils/focus/selection.js'); + +function resolveCaretPosition({ target, node, offset }) { + if (selection.hasOwnSelection(target)) { + return { + node: target, + offset: offset !== null && offset !== undefined ? offset : UI.getUIValue(target).length + }; + } else if (node) { + return { + node, + offset: offset !== null && offset !== undefined ? offset : node.nodeType === 3 ? node.nodeValue.length : node.childNodes.length + }; + } + return findNodeAtTextOffset(target, offset); +} +function findNodeAtTextOffset(node, offset, isRoot = true) { + // When clicking after the content the browser behavior can be complicated: + // 1. If there is textContent after the last element child, + // the cursor is moved there. + // 2. If there is textContent in the last element child, + // the browser moves the cursor to the last non-empty text node inside this element. + // 3. Otherwise the cursor is moved to the end of the target. + let i = offset === undefined ? node.childNodes.length - 1 : 0; + const step = offset === undefined ? -1 : 1; + while(offset === undefined ? i >= (isRoot ? Math.max(node.childNodes.length - 1, 0) : 0) : i <= node.childNodes.length){ + if (offset && i === node.childNodes.length) { + throw new Error('The given offset is out of bounds.'); + } + const c = node.childNodes.item(i); + const text = String(c.textContent); + if (text.length) { + if (offset !== undefined && text.length < offset) { + offset -= text.length; + } else if (c.nodeType === 1) { + return findNodeAtTextOffset(c, offset, false); + } else { + // The pre-commit hooks keeps changing this + // See https://github.com/kentcdodds/kcd-scripts/issues/218 + /* istanbul ignore else */ // eslint-disable-next-line no-lonely-if + if (c.nodeType === 3) { + return { + node: c, + offset: offset !== null && offset !== undefined ? offset : c.nodeValue.length + }; + } + } + } + i += step; + } + return { + node, + offset: node.childNodes.length + }; +} + +exports.resolveCaretPosition = resolveCaretPosition; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/selectAll.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/selectAll.js new file mode 100644 index 0000000000000000000000000000000000000000..596cde21129654e2ca934e2e1d1d42a91dd6e45b --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/selectAll.js @@ -0,0 +1,38 @@ +'use strict'; + +var UI = require('../../document/UI.js'); +require('../../utils/dataTransfer/Clipboard.js'); +var isContentEditable = require('../../utils/edit/isContentEditable.js'); +var selection = require('../../utils/focus/selection.js'); +var setSelection = require('./setSelection.js'); + +/** + * Expand a selection like the browser does when pressing Ctrl+A. + */ function selectAll(target) { + if (selection.hasOwnSelection(target)) { + return setSelection.setSelection({ + focusNode: target, + anchorOffset: 0, + focusOffset: UI.getUIValue(target).length + }); + } + var _getContentEditable; + const focusNode = (_getContentEditable = isContentEditable.getContentEditable(target)) !== null && _getContentEditable !== undefined ? _getContentEditable : target.ownerDocument.body; + setSelection.setSelection({ + focusNode, + anchorOffset: 0, + focusOffset: focusNode.childNodes.length + }); +} +function isAllSelected(target) { + if (selection.hasOwnSelection(target)) { + return UI.getUISelection(target).startOffset === 0 && UI.getUISelection(target).endOffset === UI.getUIValue(target).length; + } + var _getContentEditable; + const focusNode = (_getContentEditable = isContentEditable.getContentEditable(target)) !== null && _getContentEditable !== undefined ? _getContentEditable : target.ownerDocument.body; + const selection$1 = target.ownerDocument.getSelection(); + return (selection$1 === null || selection$1 === undefined ? undefined : selection$1.anchorNode) === focusNode && selection$1.focusNode === focusNode && selection$1.anchorOffset === 0 && selection$1.focusOffset === focusNode.childNodes.length; +} + +exports.isAllSelected = isAllSelected; +exports.selectAll = selectAll; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/setSelection.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/setSelection.js new file mode 100644 index 0000000000000000000000000000000000000000..39b3554ad0add53c673e029489c13424a0fd435c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/setSelection.js @@ -0,0 +1,21 @@ +'use strict'; + +var UI = require('../../document/UI.js'); +require('../../utils/dataTransfer/Clipboard.js'); +var getTargetTypeAndSelection = require('./getTargetTypeAndSelection.js'); + +/** + * Set the selection + */ function setSelection({ focusNode, focusOffset, anchorNode = focusNode, anchorOffset = focusOffset }) { + var _anchorNode_ownerDocument_getSelection, _anchorNode_ownerDocument; + const typeAndSelection = getTargetTypeAndSelection.getTargetTypeAndSelection(focusNode); + if (typeAndSelection.type === 'input') { + return UI.setUISelection(focusNode, { + anchorOffset, + focusOffset + }); + } + (_anchorNode_ownerDocument = anchorNode.ownerDocument) === null || _anchorNode_ownerDocument === undefined ? undefined : (_anchorNode_ownerDocument_getSelection = _anchorNode_ownerDocument.getSelection()) === null || _anchorNode_ownerDocument_getSelection === undefined ? undefined : _anchorNode_ownerDocument_getSelection.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset); +} + +exports.setSelection = setSelection; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/setSelectionPerMouse.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/setSelectionPerMouse.js new file mode 100644 index 0000000000000000000000000000000000000000..34a522704c041acce0d70518b16a536eceaba5c7 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/setSelectionPerMouse.js @@ -0,0 +1,81 @@ +'use strict'; + +var UI = require('../../document/UI.js'); +require('../../utils/dataTransfer/Clipboard.js'); +var selection = require('../../utils/focus/selection.js'); +var resolveCaretPosition = require('./resolveCaretPosition.js'); + +function setSelectionPerMouseDown({ document, target, clickCount, node, offset }) { + if (selection.hasNoSelection(target)) { + return; + } + const targetHasOwnSelection = selection.hasOwnSelection(target); + // On non-input elements the text selection per multiple click + // can extend beyond the target boundaries. + // The exact mechanism what is considered in the same line is unclear. + // Looks it might be every inline element. + // TODO: Check what might be considered part of the same line of text. + const text = String(targetHasOwnSelection ? UI.getUIValue(target) : target.textContent); + const [start, end] = node ? // which elements might be considered in the same line of text. + // TODO: support expanding initial range on multiple clicks if node is given + [ + offset, + offset + ] : getTextRange(text, offset, clickCount); + // TODO: implement modifying selection per shift/ctrl+mouse + if (targetHasOwnSelection) { + UI.setUISelection(target, { + anchorOffset: start !== null && start !== undefined ? start : text.length, + focusOffset: end !== null && end !== undefined ? end : text.length + }); + return { + node: target, + start: start !== null && start !== undefined ? start : 0, + end: end !== null && end !== undefined ? end : text.length + }; + } else { + const { node: startNode, offset: startOffset } = resolveCaretPosition.resolveCaretPosition({ + target, + node, + offset: start + }); + const { node: endNode, offset: endOffset } = resolveCaretPosition.resolveCaretPosition({ + target, + node, + offset: end + }); + const range = target.ownerDocument.createRange(); + try { + range.setStart(startNode, startOffset); + range.setEnd(endNode, endOffset); + } catch (e) { + throw new Error('The given offset is out of bounds.'); + } + const selection = document.getSelection(); + selection === null || selection === undefined ? undefined : selection.removeAllRanges(); + selection === null || selection === undefined ? undefined : selection.addRange(range.cloneRange()); + return range; + } +} +function getTextRange(text, pos, clickCount) { + if (clickCount % 3 === 1 || text.length === 0) { + return [ + pos, + pos + ]; + } + const textPos = pos !== null && pos !== undefined ? pos : text.length; + if (clickCount % 3 === 2) { + return [ + textPos - text.substr(0, pos).match(/(\w+|\s+|\W)?$/)[0].length, + pos === undefined ? pos : pos + text.substr(pos).match(/^(\w+|\s+|\W)?/)[0].length + ]; + } + // triple click + return [ + textPos - text.substr(0, pos).match(/[^\r\n]*$/)[0].length, + pos === undefined ? pos : pos + text.substr(pos).match(/^[^\r\n]*/)[0].length + ]; +} + +exports.setSelectionPerMouseDown = setSelectionPerMouseDown; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/setSelectionRange.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/setSelectionRange.js new file mode 100644 index 0000000000000000000000000000000000000000..6664e15c9b71397931f44a89218575be59fb5c8a --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/setSelectionRange.js @@ -0,0 +1,31 @@ +'use strict'; + +require('../../utils/dataTransfer/Clipboard.js'); +var isContentEditable = require('../../utils/edit/isContentEditable.js'); +var selection = require('../../utils/focus/selection.js'); +var setSelection = require('./setSelection.js'); + +/** + * Backward-compatible selection. + * + * Handles input elements and contenteditable if it only contains a single text node. + */ function setSelectionRange(element, anchorOffset, focusOffset) { + var _element_firstChild; + if (selection.hasOwnSelection(element)) { + return setSelection.setSelection({ + focusNode: element, + anchorOffset, + focusOffset + }); + } + /* istanbul ignore else */ if (isContentEditable.isContentEditable(element) && ((_element_firstChild = element.firstChild) === null || _element_firstChild === undefined ? undefined : _element_firstChild.nodeType) === 3) { + return setSelection.setSelection({ + focusNode: element.firstChild, + anchorOffset, + focusOffset + }); + } + /* istanbul ignore next */ throw new Error('Not implemented. The result of this interaction is unreliable.'); +} + +exports.setSelectionRange = setSelectionRange; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/updateSelectionOnFocus.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/updateSelectionOnFocus.js new file mode 100644 index 0000000000000000000000000000000000000000..e6232eee981cc67ed0da96085df844bc61c43cf9 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/selection/updateSelectionOnFocus.js @@ -0,0 +1,40 @@ +'use strict'; + +require('../../utils/dataTransfer/Clipboard.js'); +var isContentEditable = require('../../utils/edit/isContentEditable.js'); +var selection = require('../../utils/focus/selection.js'); + +// The browser implementation seems to have changed. +// When focus is inside , +// Chrome updates Selection to be collapsed at the position of the input element. +// TODO: update implementation to match that of current browsers +/** + * Reset the Document Selection when moving focus into an element + * with own selection implementation. + */ function updateSelectionOnFocus(element) { + const selection$1 = element.ownerDocument.getSelection(); + /* istanbul ignore if */ if (!(selection$1 === null || selection$1 === undefined ? undefined : selection$1.focusNode)) { + return; + } + // If the focus moves inside an element with own selection implementation, + // the document selection will be this element. + // But if the focused element is inside a contenteditable, + // 1) a collapsed selection will be retained. + // 2) other selections will be replaced by a cursor + // 2.a) at the start of the first child if it is a text node + // 2.b) at the start of the contenteditable. + if (selection.hasOwnSelection(element)) { + const contenteditable = isContentEditable.getContentEditable(selection$1.focusNode); + if (contenteditable) { + if (!selection$1.isCollapsed) { + var _contenteditable_firstChild; + const focusNode = ((_contenteditable_firstChild = contenteditable.firstChild) === null || _contenteditable_firstChild === undefined ? undefined : _contenteditable_firstChild.nodeType) === 3 ? contenteditable.firstChild : contenteditable; + selection$1.setBaseAndExtent(focusNode, 0, focusNode, 0); + } + } else { + selection$1.setBaseAndExtent(element, 0, element, 0); + } + } +} + +exports.updateSelectionOnFocus = updateSelectionOnFocus; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/types.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/types.js new file mode 100644 index 0000000000000000000000000000000000000000..eb109abbed09786c904e3c767f123a1a0dae21ec --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/types.js @@ -0,0 +1,2 @@ +'use strict'; + diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/wrapEvent.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/wrapEvent.js new file mode 100644 index 0000000000000000000000000000000000000000..be3ab9ddf1d4e549562192d3c2787bbab96639e0 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/event/wrapEvent.js @@ -0,0 +1,9 @@ +'use strict'; + +var dom = require('@testing-library/dom'); + +function wrapEvent(cb, _element) { + return dom.getConfig().eventWrapper(cb); +} + +exports.wrapEvent = wrapEvent; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b4402f4a385c44b798598ad36d2f0f1835a04e7b --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/index.js @@ -0,0 +1,12 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var index = require('./setup/index.js'); +var options = require('./options.js'); + + + +exports.default = index.userEvent; +exports.userEvent = index.userEvent; +exports.PointerEventsCheckLevel = options.PointerEventsCheckLevel; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/keyboard/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/keyboard/index.js new file mode 100644 index 0000000000000000000000000000000000000000..18f5b4b8eb995fe5ecb352230f71b25e90f2a8a0 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/keyboard/index.js @@ -0,0 +1,40 @@ +'use strict'; + +require('../utils/dataTransfer/Clipboard.js'); +var wait = require('../utils/misc/wait.js'); +var parseKeyDef = require('./parseKeyDef.js'); + +async function keyboard(text) { + const actions = parseKeyDef.parseKeyDef(this.config.keyboardMap, text); + for(let i = 0; i < actions.length; i++){ + await wait.wait(this.config); + await keyboardAction(this, actions[i]); + } +} +async function keyboardAction(instance, { keyDef, releasePrevious, releaseSelf, repeat }) { + const { system } = instance; + // Release the key automatically if it was pressed before. + if (system.keyboard.isKeyPressed(keyDef)) { + await system.keyboard.keyup(instance, keyDef); + } + if (!releasePrevious) { + for(let i = 1; i <= repeat; i++){ + await system.keyboard.keydown(instance, keyDef); + if (i < repeat) { + await wait.wait(instance.config); + } + } + // Release the key only on the last iteration on `state.repeatKey`. + if (releaseSelf) { + await system.keyboard.keyup(instance, keyDef); + } + } +} +async function releaseAllKeys(instance) { + for (const k of instance.system.keyboard.getPressedKeys()){ + await instance.system.keyboard.keyup(instance, k); + } +} + +exports.keyboard = keyboard; +exports.releaseAllKeys = releaseAllKeys; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/keyboard/keyMap.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/keyboard/keyMap.js new file mode 100644 index 0000000000000000000000000000000000000000..77153c1b8a8fa513b5f5f9250e5f844542eadc16 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/keyboard/keyMap.js @@ -0,0 +1,178 @@ +'use strict'; + +var keyboard = require('../system/keyboard.js'); + +/** + * Mapping for a default US-104-QWERTY keyboard + */ const defaultKeyMap = [ + // alphanumeric block - writing system + ...'0123456789'.split('').map((c)=>({ + code: `Digit${c}`, + key: c + })), + ...')!@#$%^&*('.split('').map((c, i)=>({ + code: `Digit${i}`, + key: c, + shiftKey: true + })), + ...'abcdefghijklmnopqrstuvwxyz'.split('').map((c)=>({ + code: `Key${c.toUpperCase()}`, + key: c + })), + ...'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('').map((c)=>({ + code: `Key${c}`, + key: c, + shiftKey: true + })), + { + code: 'BracketLeft', + key: '[' + }, + { + code: 'BracketLeft', + key: '{', + shiftKey: true + }, + { + code: 'BracketRight', + key: ']' + }, + { + code: 'BracketRight', + key: '}', + shiftKey: true + }, + // alphanumeric block - functional + { + code: 'Space', + key: ' ' + }, + { + code: 'AltLeft', + key: 'Alt', + location: keyboard.DOM_KEY_LOCATION.LEFT + }, + { + code: 'AltRight', + key: 'Alt', + location: keyboard.DOM_KEY_LOCATION.RIGHT + }, + { + code: 'ShiftLeft', + key: 'Shift', + location: keyboard.DOM_KEY_LOCATION.LEFT + }, + { + code: 'ShiftRight', + key: 'Shift', + location: keyboard.DOM_KEY_LOCATION.RIGHT + }, + { + code: 'ControlLeft', + key: 'Control', + location: keyboard.DOM_KEY_LOCATION.LEFT + }, + { + code: 'ControlRight', + key: 'Control', + location: keyboard.DOM_KEY_LOCATION.RIGHT + }, + { + code: 'MetaLeft', + key: 'Meta', + location: keyboard.DOM_KEY_LOCATION.LEFT + }, + { + code: 'MetaRight', + key: 'Meta', + location: keyboard.DOM_KEY_LOCATION.RIGHT + }, + { + code: 'OSLeft', + key: 'OS', + location: keyboard.DOM_KEY_LOCATION.LEFT + }, + { + code: 'OSRight', + key: 'OS', + location: keyboard.DOM_KEY_LOCATION.RIGHT + }, + { + code: 'ContextMenu', + key: 'ContextMenu' + }, + { + code: 'Tab', + key: 'Tab' + }, + { + code: 'CapsLock', + key: 'CapsLock' + }, + { + code: 'Backspace', + key: 'Backspace' + }, + { + code: 'Enter', + key: 'Enter' + }, + // function + { + code: 'Escape', + key: 'Escape' + }, + // arrows + { + code: 'ArrowUp', + key: 'ArrowUp' + }, + { + code: 'ArrowDown', + key: 'ArrowDown' + }, + { + code: 'ArrowLeft', + key: 'ArrowLeft' + }, + { + code: 'ArrowRight', + key: 'ArrowRight' + }, + // control pad + { + code: 'Home', + key: 'Home' + }, + { + code: 'End', + key: 'End' + }, + { + code: 'Delete', + key: 'Delete' + }, + { + code: 'PageUp', + key: 'PageUp' + }, + { + code: 'PageDown', + key: 'PageDown' + }, + // Special keys that are not part of a default US-layout but included for specific behavior + { + code: 'Fn', + key: 'Fn' + }, + { + code: 'Symbol', + key: 'Symbol' + }, + { + code: 'AltRight', + key: 'AltGraph' + } +]; + +exports.defaultKeyMap = defaultKeyMap; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/keyboard/parseKeyDef.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/keyboard/parseKeyDef.js new file mode 100644 index 0000000000000000000000000000000000000000..f798fdd31035ff7dd7c8673db2db9af833d04927 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/keyboard/parseKeyDef.js @@ -0,0 +1,45 @@ +'use strict'; + +require('../utils/dataTransfer/Clipboard.js'); +var readNextDescriptor = require('../utils/keyDef/readNextDescriptor.js'); + +/** + * Parse key definitions per `keyboardMap` + * + * Keys can be referenced by `{key}` or `{special}` as well as physical locations per `[code]`. + * Everything else will be interpreted as a typed character - e.g. `a`. + * Brackets `{` and `[` can be escaped by doubling - e.g. `foo[[bar` translates to `foo[bar`. + * Keeping the key pressed can be written as `{key>}`. + * When keeping the key pressed you can choose how long (how many keydown and keypress) the key is pressed `{key>3}`. + * You can then release the key per `{key>3/}` or keep it pressed and continue with the next key. + */ function parseKeyDef(keyboardMap, text) { + const defs = []; + do { + const { type, descriptor, consumedLength, releasePrevious, releaseSelf = true, repeat } = readNextDescriptor.readNextDescriptor(text, 'keyboard'); + var _keyboardMap_find; + const keyDef = (_keyboardMap_find = keyboardMap.find((def)=>{ + if (type === '[') { + var _def_code; + return ((_def_code = def.code) === null || _def_code === undefined ? undefined : _def_code.toLowerCase()) === descriptor.toLowerCase(); + } else if (type === '{') { + var _def_key; + return ((_def_key = def.key) === null || _def_key === undefined ? undefined : _def_key.toLowerCase()) === descriptor.toLowerCase(); + } + return def.key === descriptor; + })) !== null && _keyboardMap_find !== undefined ? _keyboardMap_find : { + key: 'Unknown', + code: 'Unknown', + [type === '[' ? 'code' : 'key']: descriptor + }; + defs.push({ + keyDef, + releasePrevious, + releaseSelf, + repeat + }); + text = text.slice(consumedLength); + }while (text) + return defs; +} + +exports.parseKeyDef = parseKeyDef; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/options.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/options.js new file mode 100644 index 0000000000000000000000000000000000000000..1581b9d76fe7e200174c24bd41fb04b092fc75a9 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/options.js @@ -0,0 +1,14 @@ +'use strict'; + +var PointerEventsCheckLevel = /*#__PURE__*/ function(PointerEventsCheckLevel) { + /** + * Check pointer events on every user interaction that triggers a bunch of events. + * E.g. once for releasing a mouse button even though this triggers `pointerup`, `mouseup`, `click`, etc... + */ PointerEventsCheckLevel[PointerEventsCheckLevel["EachTrigger"] = 4] = "EachTrigger"; + /** Check each target once per call to pointer (related) API */ PointerEventsCheckLevel[PointerEventsCheckLevel["EachApiCall"] = 2] = "EachApiCall"; + /** Check each event target once */ PointerEventsCheckLevel[PointerEventsCheckLevel["EachTarget"] = 1] = "EachTarget"; + /** No pointer events check */ PointerEventsCheckLevel[PointerEventsCheckLevel["Never"] = 0] = "Never"; + return PointerEventsCheckLevel; +}({}); + +exports.PointerEventsCheckLevel = PointerEventsCheckLevel; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/package.json b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c9a44226149708aa5c098ac46f9addc86f6f4d22 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/pointer/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/pointer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..af742177e3f7888cb21179a4ea5325b32b84fc02 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/pointer/index.js @@ -0,0 +1,74 @@ +'use strict'; + +require('../utils/dataTransfer/Clipboard.js'); +var level = require('../utils/misc/level.js'); +var wait = require('../utils/misc/wait.js'); +var parseKeyDef = require('./parseKeyDef.js'); + +async function pointer(input) { + const { pointerMap } = this.config; + const actions = []; + (Array.isArray(input) ? input : [ + input + ]).forEach((actionInput)=>{ + if (typeof actionInput === 'string') { + actions.push(...parseKeyDef.parseKeyDef(pointerMap, actionInput)); + } else if ('keys' in actionInput) { + actions.push(...parseKeyDef.parseKeyDef(pointerMap, actionInput.keys).map((i)=>({ + ...actionInput, + ...i + }))); + } else { + actions.push(actionInput); + } + }); + for(let i = 0; i < actions.length; i++){ + await wait.wait(this.config); + await pointerAction(this, actions[i]); + } + this.system.pointer.resetClickCount(); +} +async function pointerAction(instance, action) { + var _previousPosition_caret, _previousPosition_caret1; + const pointerName = 'pointerName' in action && action.pointerName ? action.pointerName : 'keyDef' in action ? instance.system.pointer.getPointerName(action.keyDef) : 'mouse'; + const previousPosition = instance.system.pointer.getPreviousPosition(pointerName); + var _action_target, _action_coords, _action_node, _action_offset; + const position = { + target: (_action_target = action.target) !== null && _action_target !== undefined ? _action_target : getPrevTarget(instance, previousPosition), + coords: (_action_coords = action.coords) !== null && _action_coords !== undefined ? _action_coords : previousPosition === null || previousPosition === undefined ? undefined : previousPosition.coords, + caret: { + node: (_action_node = action.node) !== null && _action_node !== undefined ? _action_node : hasCaretPosition(action) ? undefined : previousPosition === null || previousPosition === undefined ? undefined : (_previousPosition_caret = previousPosition.caret) === null || _previousPosition_caret === undefined ? undefined : _previousPosition_caret.node, + offset: (_action_offset = action.offset) !== null && _action_offset !== undefined ? _action_offset : hasCaretPosition(action) ? undefined : previousPosition === null || previousPosition === undefined ? undefined : (_previousPosition_caret1 = previousPosition.caret) === null || _previousPosition_caret1 === undefined ? undefined : _previousPosition_caret1.offset + } + }; + if ('keyDef' in action) { + if (instance.system.pointer.isKeyPressed(action.keyDef)) { + level.setLevelRef(instance, level.ApiLevel.Trigger); + await instance.system.pointer.release(instance, action.keyDef, position); + } + if (!action.releasePrevious) { + level.setLevelRef(instance, level.ApiLevel.Trigger); + await instance.system.pointer.press(instance, action.keyDef, position); + if (action.releaseSelf) { + level.setLevelRef(instance, level.ApiLevel.Trigger); + await instance.system.pointer.release(instance, action.keyDef, position); + } + } + } else { + level.setLevelRef(instance, level.ApiLevel.Trigger); + await instance.system.pointer.move(instance, pointerName, position); + } +} +function hasCaretPosition(action) { + var _action_target, _ref; + return !!((_ref = (_action_target = action.target) !== null && _action_target !== undefined ? _action_target : action.node) !== null && _ref !== undefined ? _ref : action.offset !== undefined); +} +function getPrevTarget(instance, position) { + if (!position) { + throw new Error('This pointer has no previous position. Provide a target property!'); + } + var _position_target; + return (_position_target = position.target) !== null && _position_target !== undefined ? _position_target : instance.config.document.body; +} + +exports.pointer = pointer; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/pointer/keyMap.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/pointer/keyMap.js new file mode 100644 index 0000000000000000000000000000000000000000..52ecd970930579a4fd86703d91a079d4fd280b2c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/pointer/keyMap.js @@ -0,0 +1,33 @@ +'use strict'; + +const defaultKeyMap = [ + { + name: 'MouseLeft', + pointerType: 'mouse', + button: 'primary' + }, + { + name: 'MouseRight', + pointerType: 'mouse', + button: 'secondary' + }, + { + name: 'MouseMiddle', + pointerType: 'mouse', + button: 'auxiliary' + }, + { + name: 'TouchA', + pointerType: 'touch' + }, + { + name: 'TouchB', + pointerType: 'touch' + }, + { + name: 'TouchC', + pointerType: 'touch' + } +]; + +exports.defaultKeyMap = defaultKeyMap; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/pointer/parseKeyDef.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/pointer/parseKeyDef.js new file mode 100644 index 0000000000000000000000000000000000000000..79e3026c5272b13d0a48b2ecd1a399e74692ab2a --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/pointer/parseKeyDef.js @@ -0,0 +1,23 @@ +'use strict'; + +require('../utils/dataTransfer/Clipboard.js'); +var readNextDescriptor = require('../utils/keyDef/readNextDescriptor.js'); + +function parseKeyDef(pointerMap, keys) { + const defs = []; + do { + const { descriptor, consumedLength, releasePrevious, releaseSelf = true } = readNextDescriptor.readNextDescriptor(keys, 'pointer'); + const keyDef = pointerMap.find((p)=>p.name === descriptor); + if (keyDef) { + defs.push({ + keyDef, + releasePrevious, + releaseSelf + }); + } + keys = keys.slice(consumedLength); + }while (keys) + return defs; +} + +exports.parseKeyDef = parseKeyDef; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/setup/api.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/setup/api.js new file mode 100644 index 0000000000000000000000000000000000000000..ef94e384d46ea9672f2efe9025197331e1302a04 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/setup/api.js @@ -0,0 +1,35 @@ +'use strict'; + +var click = require('../convenience/click.js'); +var hover = require('../convenience/hover.js'); +var tab = require('../convenience/tab.js'); +var index = require('../keyboard/index.js'); +var copy = require('../clipboard/copy.js'); +var cut = require('../clipboard/cut.js'); +var paste = require('../clipboard/paste.js'); +var index$1 = require('../pointer/index.js'); +var clear = require('../utility/clear.js'); +var selectOptions = require('../utility/selectOptions.js'); +var type = require('../utility/type.js'); +var upload = require('../utility/upload.js'); + +const userEventApi = { + click: click.click, + dblClick: click.dblClick, + tripleClick: click.tripleClick, + hover: hover.hover, + unhover: hover.unhover, + tab: tab.tab, + keyboard: index.keyboard, + copy: copy.copy, + cut: cut.cut, + paste: paste.paste, + pointer: index$1.pointer, + clear: clear.clear, + deselectOptions: selectOptions.deselectOptions, + selectOptions: selectOptions.selectOptions, + type: type.type, + upload: upload.upload +}; + +exports.userEventApi = userEventApi; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/setup/directApi.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/setup/directApi.js new file mode 100644 index 0000000000000000000000000000000000000000..44361f2db27e1083f9b43e4b96f9a7f5bab50298 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/setup/directApi.js @@ -0,0 +1,75 @@ +'use strict'; + +var setup = require('./setup.js'); + +function clear(element) { + return setup.setupDirect().api.clear(element); +} +function click(element, options = {}) { + return setup.setupDirect(options, element).api.click(element); +} +function copy(options = {}) { + return setup.setupDirect(options).api.copy(); +} +function cut(options = {}) { + return setup.setupDirect(options).api.cut(); +} +function dblClick(element, options = {}) { + return setup.setupDirect(options).api.dblClick(element); +} +function deselectOptions(select, values, options = {}) { + return setup.setupDirect(options).api.deselectOptions(select, values); +} +function hover(element, options = {}) { + return setup.setupDirect(options).api.hover(element); +} +async function keyboard(text, options = {}) { + const { api, system } = setup.setupDirect(options); + return api.keyboard(text).then(()=>system); +} +async function pointer(input, options = {}) { + const { api, system } = setup.setupDirect(options); + return api.pointer(input).then(()=>system); +} +function paste(clipboardData, options) { + return setup.setupDirect(options).api.paste(clipboardData); +} +function selectOptions(select, values, options = {}) { + return setup.setupDirect(options).api.selectOptions(select, values); +} +function tripleClick(element, options = {}) { + return setup.setupDirect(options).api.tripleClick(element); +} +function type(element, text, options = {}) { + return setup.setupDirect(options, element).api.type(element, text, options); +} +function unhover(element, options = {}) { + const { api, system } = setup.setupDirect(options); + system.pointer.setMousePosition({ + target: element + }); + return api.unhover(element); +} +function upload(element, fileOrFiles, options = {}) { + return setup.setupDirect(options).api.upload(element, fileOrFiles); +} +function tab(options = {}) { + return setup.setupDirect().api.tab(options); +} + +exports.clear = clear; +exports.click = click; +exports.copy = copy; +exports.cut = cut; +exports.dblClick = dblClick; +exports.deselectOptions = deselectOptions; +exports.hover = hover; +exports.keyboard = keyboard; +exports.paste = paste; +exports.pointer = pointer; +exports.selectOptions = selectOptions; +exports.tab = tab; +exports.tripleClick = tripleClick; +exports.type = type; +exports.unhover = unhover; +exports.upload = upload; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/setup/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/setup/index.js new file mode 100644 index 0000000000000000000000000000000000000000..55560d5e0d680468038d2703005ccafb25c8c123 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/setup/index.js @@ -0,0 +1,11 @@ +'use strict'; + +var setup = require('./setup.js'); +var directApi = require('./directApi.js'); + +const userEvent = { + ...directApi, + setup: setup.setupMain +}; + +exports.userEvent = userEvent; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/setup/setup.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/setup/setup.js new file mode 100644 index 0000000000000000000000000000000000000000..6046ae17c6860a84a19f8c344dc60f4de86ee648 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/setup/setup.js @@ -0,0 +1,125 @@ +'use strict'; + +var patchFocus = require('../document/patchFocus.js'); +var prepareDocument = require('../document/prepareDocument.js'); +var dispatchEvent = require('../event/dispatchEvent.js'); +var Clipboard = require('../utils/dataTransfer/Clipboard.js'); +var getWindow = require('../utils/misc/getWindow.js'); +var getDocumentFromNode = require('../utils/misc/getDocumentFromNode.js'); +var level = require('../utils/misc/level.js'); +var wait = require('../utils/misc/wait.js'); +var options = require('../options.js'); +require('@testing-library/dom'); +var keyMap = require('../keyboard/keyMap.js'); +var keyMap$1 = require('../pointer/keyMap.js'); +var index = require('../system/index.js'); +var api = require('./api.js'); +var wrapAsync = require('./wrapAsync.js'); + +/** + * Default options applied when API is called per `userEvent.anyApi()` + */ const defaultOptionsDirect = { + applyAccept: true, + autoModify: true, + delay: 0, + document: globalThis.document, + keyboardMap: keyMap.defaultKeyMap, + pointerMap: keyMap$1.defaultKeyMap, + pointerEventsCheck: options.PointerEventsCheckLevel.EachApiCall, + skipAutoClose: false, + skipClick: false, + skipHover: false, + writeToClipboard: false, + advanceTimers: ()=>Promise.resolve() +}; +/** + * Default options applied when API is called per `userEvent().anyApi()` + */ const defaultOptionsSetup = { + ...defaultOptionsDirect, + writeToClipboard: true +}; +function createConfig(options = {}, defaults = defaultOptionsSetup, node) { + const document = getDocument(options, node, defaults); + return { + ...defaults, + ...options, + document + }; +} +/** + * Start a "session" with userEvent. + * All APIs returned by this function share an input device state and a default configuration. + */ function setupMain(options = {}) { + const config = createConfig(options); + prepareDocument.prepareDocument(config.document); + patchFocus.patchFocus(getWindow.getWindow(config.document).HTMLElement); + var _config_document_defaultView; + const view = (_config_document_defaultView = config.document.defaultView) !== null && _config_document_defaultView !== undefined ? _config_document_defaultView : /* istanbul ignore next */ globalThis.window; + Clipboard.attachClipboardStubToView(view); + return createInstance(config).api; +} +/** + * Setup in direct call per `userEvent.anyApi()` + */ function setupDirect({ keyboardState, pointerState, ...options } = {}, node) { + const config = createConfig(options, defaultOptionsDirect, node); + prepareDocument.prepareDocument(config.document); + patchFocus.patchFocus(getWindow.getWindow(config.document).HTMLElement); + var _ref; + const system = (_ref = pointerState !== null && pointerState !== undefined ? pointerState : keyboardState) !== null && _ref !== undefined ? _ref : new index.System(); + return { + api: createInstance(config, system).api, + system + }; +} +/** + * Create a set of callbacks with different default settings but the same state. + */ function setupSub(options) { + return createInstance({ + ...this.config, + ...options + }, this.system).api; +} +function wrapAndBindImpl(instance, impl) { + function method(...args) { + level.setLevelRef(instance, level.ApiLevel.Call); + return wrapAsync.wrapAsync(()=>impl.apply(instance, args).then(async (ret)=>{ + await wait.wait(instance.config); + return ret; + })); + } + Object.defineProperty(method, 'name', { + get: ()=>impl.name + }); + return method; +} +function createInstance(config, system = new index.System()) { + const instance = {}; + Object.assign(instance, { + config, + dispatchEvent: dispatchEvent.dispatchEvent.bind(instance), + dispatchUIEvent: dispatchEvent.dispatchUIEvent.bind(instance), + system, + levelRefs: {}, + ...api.userEventApi + }); + return { + instance, + api: { + ...Object.fromEntries(Object.entries(api.userEventApi).map(([name, api])=>[ + name, + wrapAndBindImpl(instance, api) + ])), + setup: setupSub.bind(instance) + } + }; +} +function getDocument(options, node, defaults) { + var _options_document, _ref; + return (_ref = (_options_document = options.document) !== null && _options_document !== undefined ? _options_document : node && getDocumentFromNode.getDocumentFromNode(node)) !== null && _ref !== undefined ? _ref : defaults.document; +} + +exports.createConfig = createConfig; +exports.createInstance = createInstance; +exports.setupDirect = setupDirect; +exports.setupMain = setupMain; +exports.setupSub = setupSub; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/setup/wrapAsync.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/setup/wrapAsync.js new file mode 100644 index 0000000000000000000000000000000000000000..5c85123a76dc2d397910a392f45e6971ad2a54a4 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/setup/wrapAsync.js @@ -0,0 +1,11 @@ +'use strict'; + +var dom = require('@testing-library/dom'); + +/** + * Wrap an internal Promise + */ function wrapAsync(implementation) { + return dom.getConfig().asyncWrapper(implementation); +} + +exports.wrapAsync = wrapAsync; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7ff3b5c53346184a032d6f2565c5495ddea62cb7 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/index.js @@ -0,0 +1,44 @@ +'use strict'; + +var keyboard = require('./keyboard.js'); +var index = require('./pointer/index.js'); + +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +/** + * @internal Do not create/alter this by yourself as this type might be subject to changes. + */ class System { + getUIEventModifiers() { + return { + altKey: this.keyboard.modifiers.Alt, + ctrlKey: this.keyboard.modifiers.Control, + metaKey: this.keyboard.modifiers.Meta, + shiftKey: this.keyboard.modifiers.Shift, + modifierAltGraph: this.keyboard.modifiers.AltGraph, + modifierCapsLock: this.keyboard.modifiers.CapsLock, + modifierFn: this.keyboard.modifiers.Fn, + modifierFnLock: this.keyboard.modifiers.FnLock, + modifierNumLock: this.keyboard.modifiers.NumLock, + modifierScrollLock: this.keyboard.modifiers.ScrollLock, + modifierSymbol: this.keyboard.modifiers.Symbol, + modifierSymbolLock: this.keyboard.modifiers.SymbolLock + }; + } + constructor(){ + _define_property(this, "keyboard", new keyboard.KeyboardHost(this)); + _define_property(this, "pointer", new index.PointerHost(this)); + } +} + +exports.System = System; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/keyboard.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/keyboard.js new file mode 100644 index 0000000000000000000000000000000000000000..3272fd7e642e79a8f67052b4b521355314cbc496 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/keyboard.js @@ -0,0 +1,169 @@ +'use strict'; + +require('../utils/dataTransfer/Clipboard.js'); +var getActiveElement = require('../utils/focus/getActiveElement.js'); + +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +var DOM_KEY_LOCATION = /*#__PURE__*/ function(DOM_KEY_LOCATION) { + DOM_KEY_LOCATION[DOM_KEY_LOCATION["STANDARD"] = 0] = "STANDARD"; + DOM_KEY_LOCATION[DOM_KEY_LOCATION["LEFT"] = 1] = "LEFT"; + DOM_KEY_LOCATION[DOM_KEY_LOCATION["RIGHT"] = 2] = "RIGHT"; + DOM_KEY_LOCATION[DOM_KEY_LOCATION["NUMPAD"] = 3] = "NUMPAD"; + return DOM_KEY_LOCATION; +}({}); +const modifierKeys = [ + 'Alt', + 'AltGraph', + 'Control', + 'Fn', + 'Meta', + 'Shift', + 'Symbol' +]; +function isModifierKey(key) { + return modifierKeys.includes(key); +} +const modifierLocks = [ + 'CapsLock', + 'FnLock', + 'NumLock', + 'ScrollLock', + 'SymbolLock' +]; +function isModifierLock(key) { + return modifierLocks.includes(key); +} +class KeyboardHost { + isKeyPressed(keyDef) { + return this.pressed.has(String(keyDef.code)); + } + getPressedKeys() { + return this.pressed.values().map((p)=>p.keyDef); + } + /** Press a key */ async keydown(instance, keyDef) { + const key = String(keyDef.key); + const code = String(keyDef.code); + const target = getActiveElement.getActiveElementOrBody(instance.config.document); + this.setKeydownTarget(target); + this.pressed.add(code, keyDef); + if (isModifierKey(key)) { + this.modifiers[key] = true; + } + const unprevented = instance.dispatchUIEvent(target, 'keydown', { + key, + code + }); + if (isModifierLock(key) && !this.modifiers[key]) { + this.modifiers[key] = true; + this.modifierLockStart[key] = true; + } + if (unprevented) { + this.pressed.setUnprevented(code); + } + if (unprevented && this.hasKeyPress(key)) { + instance.dispatchUIEvent(getActiveElement.getActiveElementOrBody(instance.config.document), 'keypress', { + key, + code, + charCode: keyDef.key === 'Enter' ? 13 : String(keyDef.key).charCodeAt(0) + }); + } + } + /** Release a key */ async keyup(instance, keyDef) { + const key = String(keyDef.key); + const code = String(keyDef.code); + const unprevented = this.pressed.isUnprevented(code); + this.pressed.delete(code); + if (isModifierKey(key) && !this.pressed.values().find((p)=>p.keyDef.key === key)) { + this.modifiers[key] = false; + } + instance.dispatchUIEvent(getActiveElement.getActiveElementOrBody(instance.config.document), 'keyup', { + key, + code + }, !unprevented); + if (isModifierLock(key) && this.modifiers[key]) { + if (this.modifierLockStart[key]) { + this.modifierLockStart[key] = false; + } else { + this.modifiers[key] = false; + } + } + } + setKeydownTarget(target) { + if (target !== this.lastKeydownTarget) { + this.carryChar = ''; + } + this.lastKeydownTarget = target; + } + hasKeyPress(key) { + return (key.length === 1 || key === 'Enter') && !this.modifiers.Control && !this.modifiers.Alt; + } + constructor(system){ + _define_property(this, "system", undefined); + _define_property(this, "modifiers", { + Alt: false, + AltGraph: false, + CapsLock: false, + Control: false, + Fn: false, + FnLock: false, + Meta: false, + NumLock: false, + ScrollLock: false, + Shift: false, + Symbol: false, + SymbolLock: false + }); + _define_property(this, "pressed", new class { + add(code, keyDef) { + var _this_registry, _code; + var _; + (_ = (_this_registry = this.registry)[_code = code]) !== null && _ !== undefined ? _ : _this_registry[_code] = { + keyDef, + unpreventedDefault: false + }; + } + has(code) { + return !!this.registry[code]; + } + setUnprevented(code) { + const o = this.registry[code]; + if (o) { + o.unpreventedDefault = true; + } + } + isUnprevented(code) { + var _this_registry_code; + return !!((_this_registry_code = this.registry[code]) === null || _this_registry_code === undefined ? undefined : _this_registry_code.unpreventedDefault); + } + delete(code) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this.registry[code]; + } + values() { + return Object.values(this.registry); + } + constructor(){ + _define_property(this, "registry", {}); + } + }()); + _define_property(this, "carryChar", ''); + _define_property(this, "lastKeydownTarget", undefined); + _define_property(this, "modifierLockStart", {}); + this.system = system; + } +} + +exports.DOM_KEY_LOCATION = DOM_KEY_LOCATION; +exports.KeyboardHost = KeyboardHost; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/buttons.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/buttons.js new file mode 100644 index 0000000000000000000000000000000000000000..31a7bd3b8ef65de69cba0dabff69387dd58c1476 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/buttons.js @@ -0,0 +1,84 @@ +'use strict'; + +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +class Buttons { + getButtons() { + let v = 0; + for (const button of Object.keys(this.pressed)){ + // eslint-disable-next-line no-bitwise + v |= 2 ** Number(button); + } + return v; + } + down(keyDef) { + const button = getMouseButtonId(keyDef.button); + if (button in this.pressed) { + this.pressed[button].push(keyDef); + return undefined; + } + this.pressed[button] = [ + keyDef + ]; + return button; + } + up(keyDef) { + const button = getMouseButtonId(keyDef.button); + if (button in this.pressed) { + this.pressed[button] = this.pressed[button].filter((k)=>k.name !== keyDef.name); + if (this.pressed[button].length === 0) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this.pressed[button]; + return button; + } + } + return undefined; + } + constructor(){ + _define_property(this, "pressed", {}); + } +} +const MouseButton = { + primary: 0, + secondary: 1, + auxiliary: 2, + back: 3, + X1: 3, + forward: 4, + X2: 4 +}; +function getMouseButtonId(button = 0) { + if (button in MouseButton) { + return MouseButton[button]; + } + return Number(button); +} +// On the `MouseEvent.button` property auxiliary and secondary button are flipped compared to `MouseEvent.buttons`. +const MouseButtonFlip = { + 1: 2, + 2: 1 +}; +function getMouseEventButton(button) { + button = getMouseButtonId(button); + if (button in MouseButtonFlip) { + return MouseButtonFlip[button]; + } + return button; +} + +exports.Buttons = Buttons; +exports.MouseButton = MouseButton; +exports.MouseButtonFlip = MouseButtonFlip; +exports.getMouseButtonId = getMouseButtonId; +exports.getMouseEventButton = getMouseEventButton; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/device.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/device.js new file mode 100644 index 0000000000000000000000000000000000000000..20d63c76559cbcda0e05a28e4f455afb96b74988 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/device.js @@ -0,0 +1,34 @@ +'use strict'; + +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +class Device { + get countPressed() { + return this.pressedKeys.size; + } + isPressed(keyDef) { + return this.pressedKeys.has(keyDef.name); + } + addPressed(keyDef) { + return this.pressedKeys.add(keyDef.name); + } + removePressed(keyDef) { + return this.pressedKeys.delete(keyDef.name); + } + constructor(){ + _define_property(this, "pressedKeys", new Set()); + } +} + +exports.Device = Device; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6ce2092ef15cdf9103188a925a2533812273ad6d --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/index.js @@ -0,0 +1,159 @@ +'use strict'; + +var buttons = require('./buttons.js'); +var device = require('./device.js'); +var mouse = require('./mouse.js'); +var pointer = require('./pointer.js'); + +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +class PointerHost { + isKeyPressed(keyDef) { + return this.devices.get(keyDef.pointerType).isPressed(keyDef); + } + async press(instance, keyDef, position) { + this.devices.get(keyDef.pointerType).addPressed(keyDef); + this.buttons.down(keyDef); + const pointerName = this.getPointerName(keyDef); + const pointer = keyDef.pointerType === 'touch' ? this.pointers.new(pointerName, keyDef.pointerType, this.buttons) : this.pointers.get(pointerName); + // TODO: deprecate the following implicit setting of position + pointer.position = position; + if (pointer.pointerType !== 'touch') { + this.mouse.position = position; + } + if (pointer.pointerType === 'touch') { + pointer.init(instance); + } + pointer.down(instance, keyDef.button); + if (pointer.pointerType !== 'touch') { + this.mouse.down(instance, keyDef, pointer.isPrevented); + } + } + async move(instance, pointerName, position) { + const pointer = this.pointers.get(pointerName); + // In (some?) browsers this order of events can be observed. + // This interweaving of events is probably unnecessary. + // While the order of mouse (or pointer) events is defined per spec, + // the order in which they interweave/follow on a user interaction depends on the implementation. + const pointermove = pointer.move(instance, position); + const mousemove = pointer.pointerType === 'touch' ? undefined : this.mouse.move(instance, position, pointer.isPrevented); + pointermove === null || pointermove === undefined ? undefined : pointermove.leave(); + mousemove === null || mousemove === undefined ? undefined : mousemove.leave(); + pointermove === null || pointermove === undefined ? undefined : pointermove.enter(); + mousemove === null || mousemove === undefined ? undefined : mousemove.enter(); + pointermove === null || pointermove === undefined ? undefined : pointermove.move(); + mousemove === null || mousemove === undefined ? undefined : mousemove.move(); + } + async release(instance, keyDef, position) { + const device = this.devices.get(keyDef.pointerType); + device.removePressed(keyDef); + this.buttons.up(keyDef); + const pointer = this.pointers.get(this.getPointerName(keyDef)); + const isPrevented = pointer.isPrevented; + // TODO: deprecate the following implicit setting of position + pointer.position = position; + if (pointer.pointerType !== 'touch') { + this.mouse.position = position; + } + if (device.countPressed === 0) { + pointer.up(instance, keyDef.button); + } + if (pointer.pointerType === 'touch') { + pointer.release(instance); + } + if (pointer.pointerType === 'touch' && !pointer.isMultitouch) { + const mousemove = this.mouse.move(instance, position, isPrevented); + mousemove === null || mousemove === undefined ? undefined : mousemove.leave(); + mousemove === null || mousemove === undefined ? undefined : mousemove.enter(); + mousemove === null || mousemove === undefined ? undefined : mousemove.move(); + this.mouse.down(instance, keyDef, isPrevented); + } + if (!pointer.isMultitouch) { + const mousemove = this.mouse.move(instance, position, isPrevented); + mousemove === null || mousemove === undefined ? undefined : mousemove.leave(); + mousemove === null || mousemove === undefined ? undefined : mousemove.enter(); + mousemove === null || mousemove === undefined ? undefined : mousemove.move(); + this.mouse.up(instance, keyDef, isPrevented); + } + } + getPointerName(keyDef) { + return keyDef.pointerType === 'touch' ? keyDef.name : keyDef.pointerType; + } + getPreviousPosition(pointerName) { + return this.pointers.has(pointerName) ? this.pointers.get(pointerName).position : undefined; + } + resetClickCount() { + this.mouse.resetClickCount(); + } + getMouseTarget(instance) { + var _this_mouse_position_target; + return (_this_mouse_position_target = this.mouse.position.target) !== null && _this_mouse_position_target !== undefined ? _this_mouse_position_target : instance.config.document.body; + } + setMousePosition(position) { + this.mouse.position = position; + this.pointers.get('mouse').position = position; + } + constructor(system){ + _define_property(this, "system", undefined); + _define_property(this, "mouse", undefined); + _define_property(this, "buttons", undefined); + _define_property(this, "devices", new class { + get(k) { + var _this_registry, _k; + var _; + return (_ = (_this_registry = this.registry)[_k = k]) !== null && _ !== undefined ? _ : _this_registry[_k] = new device.Device(); + } + constructor(){ + _define_property(this, "registry", {}); + } + }()); + _define_property(this, "pointers", new class { + new(pointerName, pointerType, buttons) { + const isPrimary = pointerType !== 'touch' || !Object.values(this.registry).some((p)=>p.pointerType === 'touch' && !p.isCancelled); + if (!isPrimary) { + Object.values(this.registry).forEach((p)=>{ + if (p.pointerType === pointerType && !p.isCancelled) { + p.isMultitouch = true; + } + }); + } + this.registry[pointerName] = new pointer.Pointer({ + pointerId: this.nextId++, + pointerType, + isPrimary + }, buttons); + return this.registry[pointerName]; + } + get(pointerName) { + if (!this.has(pointerName)) { + throw new Error(`Trying to access pointer "${pointerName}" which does not exist.`); + } + return this.registry[pointerName]; + } + has(pointerName) { + return pointerName in this.registry; + } + constructor(){ + _define_property(this, "registry", {}); + _define_property(this, "nextId", 1); + } + }()); + this.system = system; + this.buttons = new buttons.Buttons(); + this.mouse = new mouse.Mouse(); + this.pointers.new('mouse', 'mouse', this.buttons); + } +} + +exports.PointerHost = PointerHost; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/mouse.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/mouse.js new file mode 100644 index 0000000000000000000000000000000000000000..8a4b6ac8ab0877adeb7022c8eb38a0b26cda526c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/mouse.js @@ -0,0 +1,207 @@ +'use strict'; + +require('../../event/behavior/click.js'); +require('../../event/behavior/cut.js'); +require('../../event/behavior/keydown.js'); +require('../../event/behavior/keypress.js'); +require('../../event/behavior/keyup.js'); +require('../../event/behavior/paste.js'); +require('@testing-library/dom'); +require('../../utils/dataTransfer/Clipboard.js'); +var isDisabled = require('../../utils/misc/isDisabled.js'); +var getTreeDiff = require('../../utils/misc/getTreeDiff.js'); +var focus = require('../../event/focus.js'); +var setSelectionPerMouse = require('../../event/selection/setSelectionPerMouse.js'); +var modifySelectionPerMouse = require('../../event/selection/modifySelectionPerMouse.js'); +var buttons = require('./buttons.js'); +var shared = require('./shared.js'); + +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +/** + * This object is the single "virtual" mouse that might be controlled by multiple different pointer devices. + */ class Mouse { + move(instance, position, /** Whether `preventDefault()` has been called on the `pointerdown` event */ isPrevented) { + const prevPosition = this.position; + const prevTarget = this.getTarget(instance); + this.position = position; + if (!shared.isDifferentPointerPosition(prevPosition, position)) { + return; + } + const nextTarget = this.getTarget(instance); + const init = this.getEventInit('mousemove'); + const [leave, enter] = getTreeDiff.getTreeDiff(prevTarget, nextTarget); + return { + leave: ()=>{ + if (prevTarget !== nextTarget) { + instance.dispatchUIEvent(prevTarget, 'mouseout', init); + leave.forEach((el)=>instance.dispatchUIEvent(el, 'mouseleave', init)); + } + }, + enter: ()=>{ + if (prevTarget !== nextTarget) { + instance.dispatchUIEvent(nextTarget, 'mouseover', init); + enter.forEach((el)=>instance.dispatchUIEvent(el, 'mouseenter', init)); + } + }, + move: ()=>{ + if (isPrevented) { + return; + } + instance.dispatchUIEvent(nextTarget, 'mousemove', init); + this.modifySelecting(instance); + } + }; + } + down(instance, keyDef, /** Whether `preventDefault()` has been called on the `pointerdown` event */ isPrevented) { + const button = this.buttons.down(keyDef); + if (button === undefined) { + return; + } + const target = this.getTarget(instance); + this.buttonDownTarget[button] = target; + const init = this.getEventInit('mousedown', keyDef.button); + const disabled = isDisabled.isDisabled(target); + if (!isPrevented && (disabled || instance.dispatchUIEvent(target, 'mousedown', init))) { + this.startSelecting(instance, init.detail); + focus.focusElement(target); + } + if (!disabled && buttons.getMouseEventButton(keyDef.button) === 2) { + instance.dispatchUIEvent(target, 'contextmenu', this.getEventInit('contextmenu', keyDef.button)); + } + } + up(instance, keyDef, /** Whether `preventDefault()` has been called on the `pointerdown` event */ isPrevented) { + const button = this.buttons.up(keyDef); + if (button === undefined) { + return; + } + const target = this.getTarget(instance); + if (!isDisabled.isDisabled(target)) { + if (!isPrevented) { + const mouseUpInit = this.getEventInit('mouseup', keyDef.button); + instance.dispatchUIEvent(target, 'mouseup', mouseUpInit); + this.endSelecting(); + } + const clickTarget = getTreeDiff.getTreeDiff(this.buttonDownTarget[button], target)[2][0]; + if (clickTarget) { + const init = this.getEventInit('click', keyDef.button); + if (init.detail) { + instance.dispatchUIEvent(clickTarget, init.button === 0 ? 'click' : 'auxclick', init); + if (init.button === 0 && init.detail === 2) { + instance.dispatchUIEvent(clickTarget, 'dblclick', { + ...this.getEventInit('dblclick', keyDef.button), + detail: init.detail + }); + } + } + } + } + } + resetClickCount() { + this.clickCount.reset(); + } + getEventInit(type, button) { + const init = { + ...this.position.coords + }; + init.button = buttons.getMouseEventButton(button); + init.buttons = this.buttons.getButtons(); + if (type === 'mousedown') { + init.detail = this.clickCount.getOnDown(init.button); + } else if (type === 'mouseup') { + init.detail = this.clickCount.getOnUp(init.button); + } else if (type === 'click' || type === 'auxclick') { + init.detail = this.clickCount.incOnClick(init.button); + } + return init; + } + getTarget(instance) { + var _this_position_target; + return (_this_position_target = this.position.target) !== null && _this_position_target !== undefined ? _this_position_target : instance.config.document.body; + } + startSelecting(instance, clickCount) { + var _this_position_caret, _this_position_caret1; + // TODO: support extending range (shift) + this.selecting = setSelectionPerMouse.setSelectionPerMouseDown({ + document: instance.config.document, + target: this.getTarget(instance), + node: (_this_position_caret = this.position.caret) === null || _this_position_caret === undefined ? undefined : _this_position_caret.node, + offset: (_this_position_caret1 = this.position.caret) === null || _this_position_caret1 === undefined ? undefined : _this_position_caret1.offset, + clickCount + }); + } + modifySelecting(instance) { + var _this_position_caret, _this_position_caret1; + if (!this.selecting) { + return; + } + modifySelectionPerMouse.modifySelectionPerMouseMove(this.selecting, { + document: instance.config.document, + target: this.getTarget(instance), + node: (_this_position_caret = this.position.caret) === null || _this_position_caret === undefined ? undefined : _this_position_caret.node, + offset: (_this_position_caret1 = this.position.caret) === null || _this_position_caret1 === undefined ? undefined : _this_position_caret1.offset + }); + } + endSelecting() { + this.selecting = undefined; + } + constructor(){ + _define_property(this, "position", {}); + _define_property(this, "buttons", new buttons.Buttons()); + _define_property(this, "selecting", undefined); + _define_property(this, "buttonDownTarget", {}); + // According to spec the `detail` on click events should be the number + // of *consecutive* clicks with a specific button. + // On `mousedown` and `mouseup` it should be this number increased by one. + // But the browsers don't implement it this way. + // If another button is pressed, + // in Webkit: the `mouseup` on the previously pressed button has `detail: 0` and no `click`/`auxclick`. + // in Gecko: the `mouseup` and click events have the same detail as the `mousedown`. + // If there is a delay while a button is pressed, + // the `mouseup` and `click` are normal, but a following `mousedown` starts a new click count. + // We'll follow the minimal implementation of Webkit. + _define_property(this, "clickCount", new class { + incOnClick(button) { + const current = this.down[button] === undefined ? undefined : Number(this.down[button]) + 1; + this.count = this.count[button] === undefined ? {} : { + [button]: Number(this.count[button]) + 1 + }; + return current; + } + getOnDown(button) { + var _this_count_button; + this.down = { + [button]: (_this_count_button = this.count[button]) !== null && _this_count_button !== undefined ? _this_count_button : 0 + }; + var _this_count_button1; + this.count = { + [button]: (_this_count_button1 = this.count[button]) !== null && _this_count_button1 !== undefined ? _this_count_button1 : 0 + }; + return Number(this.count[button]) + 1; + } + getOnUp(button) { + return this.down[button] === undefined ? undefined : Number(this.down[button]) + 1; + } + reset() { + this.count = {}; + } + constructor(){ + _define_property(this, "down", {}); + _define_property(this, "count", {}); + } + }()); + } +} + +exports.Mouse = Mouse; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/pointer.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/pointer.js new file mode 100644 index 0000000000000000000000000000000000000000..4b7f262045c646071bd7c359e214a2df40a6579f --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/pointer.js @@ -0,0 +1,131 @@ +'use strict'; + +require('../../utils/dataTransfer/Clipboard.js'); +var getTreeDiff = require('../../utils/misc/getTreeDiff.js'); +var cssPointerEvents = require('../../utils/pointer/cssPointerEvents.js'); +var shared = require('./shared.js'); +var buttons = require('./buttons.js'); + +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +class Pointer { + init(instance) { + const target = this.getTarget(instance); + const [, enter] = getTreeDiff.getTreeDiff(null, target); + const init = this.getEventInit(); + cssPointerEvents.assertPointerEvents(instance, target); + instance.dispatchUIEvent(target, 'pointerover', init); + enter.forEach((el)=>instance.dispatchUIEvent(el, 'pointerenter', init)); + return this; + } + move(instance, position) { + const prevPosition = this.position; + const prevTarget = this.getTarget(instance); + this.position = position; + if (!shared.isDifferentPointerPosition(prevPosition, position)) { + return; + } + const nextTarget = this.getTarget(instance); + const init = this.getEventInit(-1); + const [leave, enter] = getTreeDiff.getTreeDiff(prevTarget, nextTarget); + return { + leave: ()=>{ + if (cssPointerEvents.hasPointerEvents(instance, prevTarget)) { + if (prevTarget !== nextTarget) { + instance.dispatchUIEvent(prevTarget, 'pointerout', init); + leave.forEach((el)=>instance.dispatchUIEvent(el, 'pointerleave', init)); + } + } + }, + enter: ()=>{ + cssPointerEvents.assertPointerEvents(instance, nextTarget); + if (prevTarget !== nextTarget) { + instance.dispatchUIEvent(nextTarget, 'pointerover', init); + enter.forEach((el)=>instance.dispatchUIEvent(el, 'pointerenter', init)); + } + }, + move: ()=>{ + instance.dispatchUIEvent(nextTarget, 'pointermove', init); + } + }; + } + down(instance, button = 0) { + if (this.isDown) { + return; + } + const target = this.getTarget(instance); + cssPointerEvents.assertPointerEvents(instance, target); + this.isDown = true; + this.isPrevented = !instance.dispatchUIEvent(target, 'pointerdown', this.getEventInit(button)); + } + up(instance, button = 0) { + if (!this.isDown) { + return; + } + const target = this.getTarget(instance); + cssPointerEvents.assertPointerEvents(instance, target); + this.isPrevented = false; + this.isDown = false; + instance.dispatchUIEvent(target, 'pointerup', this.getEventInit(button)); + } + release(instance) { + const target = this.getTarget(instance); + const [leave] = getTreeDiff.getTreeDiff(target, null); + const init = this.getEventInit(); + // Currently there is no PointerEventsCheckLevel that would + // make this check not use the *asserted* cached value from `up`. + /* istanbul ignore else */ if (cssPointerEvents.hasPointerEvents(instance, target)) { + instance.dispatchUIEvent(target, 'pointerout', init); + leave.forEach((el)=>instance.dispatchUIEvent(el, 'pointerleave', init)); + } + this.isCancelled = true; + } + getTarget(instance) { + var _this_position_target; + return (_this_position_target = this.position.target) !== null && _this_position_target !== undefined ? _this_position_target : instance.config.document.body; + } + getEventInit(/** + * The `button` that caused the event. + * + * This should be `-1` if the event is not caused by a button or touch/pen contact, + * e.g. a moving pointer. + */ button) { + return { + ...this.position.coords, + pointerId: this.pointerId, + pointerType: this.pointerType, + isPrimary: this.isPrimary, + button: buttons.getMouseEventButton(button), + buttons: this.buttons.getButtons() + }; + } + constructor({ pointerId, pointerType, isPrimary }, buttons){ + _define_property(this, "pointerId", undefined); + _define_property(this, "pointerType", undefined); + _define_property(this, "isPrimary", undefined); + _define_property(this, "buttons", undefined); + _define_property(this, "isMultitouch", false); + _define_property(this, "isCancelled", false); + _define_property(this, "isDown", false); + _define_property(this, "isPrevented", false); + _define_property(this, "position", {}); + this.pointerId = pointerId; + this.pointerType = pointerType; + this.isPrimary = isPrimary; + this.isMultitouch = !isPrimary; + this.buttons = buttons; + } +} + +exports.Pointer = Pointer; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/shared.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/shared.js new file mode 100644 index 0000000000000000000000000000000000000000..de7e7a3e5659eee370488ac26ea241a692a817b0 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/system/pointer/shared.js @@ -0,0 +1,8 @@ +'use strict'; + +function isDifferentPointerPosition(positionA, positionB) { + var _positionA_coords, _positionB_coords, _positionA_coords1, _positionB_coords1, _positionA_coords2, _positionB_coords2, _positionA_coords3, _positionB_coords3, _positionA_coords4, _positionB_coords4, _positionA_coords5, _positionB_coords5, _positionA_coords6, _positionB_coords6, _positionA_coords7, _positionB_coords7, _positionA_coords8, _positionB_coords8, _positionA_coords9, _positionB_coords9, _positionA_caret, _positionB_caret, _positionA_caret1, _positionB_caret1; + return positionA.target !== positionB.target || ((_positionA_coords = positionA.coords) === null || _positionA_coords === undefined ? undefined : _positionA_coords.x) !== ((_positionB_coords = positionB.coords) === null || _positionB_coords === undefined ? undefined : _positionB_coords.x) || ((_positionA_coords1 = positionA.coords) === null || _positionA_coords1 === undefined ? undefined : _positionA_coords1.y) !== ((_positionB_coords1 = positionB.coords) === null || _positionB_coords1 === undefined ? undefined : _positionB_coords1.y) || ((_positionA_coords2 = positionA.coords) === null || _positionA_coords2 === undefined ? undefined : _positionA_coords2.clientX) !== ((_positionB_coords2 = positionB.coords) === null || _positionB_coords2 === undefined ? undefined : _positionB_coords2.clientX) || ((_positionA_coords3 = positionA.coords) === null || _positionA_coords3 === undefined ? undefined : _positionA_coords3.clientY) !== ((_positionB_coords3 = positionB.coords) === null || _positionB_coords3 === undefined ? undefined : _positionB_coords3.clientY) || ((_positionA_coords4 = positionA.coords) === null || _positionA_coords4 === undefined ? undefined : _positionA_coords4.offsetX) !== ((_positionB_coords4 = positionB.coords) === null || _positionB_coords4 === undefined ? undefined : _positionB_coords4.offsetX) || ((_positionA_coords5 = positionA.coords) === null || _positionA_coords5 === undefined ? undefined : _positionA_coords5.offsetY) !== ((_positionB_coords5 = positionB.coords) === null || _positionB_coords5 === undefined ? undefined : _positionB_coords5.offsetY) || ((_positionA_coords6 = positionA.coords) === null || _positionA_coords6 === undefined ? undefined : _positionA_coords6.pageX) !== ((_positionB_coords6 = positionB.coords) === null || _positionB_coords6 === undefined ? undefined : _positionB_coords6.pageX) || ((_positionA_coords7 = positionA.coords) === null || _positionA_coords7 === undefined ? undefined : _positionA_coords7.pageY) !== ((_positionB_coords7 = positionB.coords) === null || _positionB_coords7 === undefined ? undefined : _positionB_coords7.pageY) || ((_positionA_coords8 = positionA.coords) === null || _positionA_coords8 === undefined ? undefined : _positionA_coords8.screenX) !== ((_positionB_coords8 = positionB.coords) === null || _positionB_coords8 === undefined ? undefined : _positionB_coords8.screenX) || ((_positionA_coords9 = positionA.coords) === null || _positionA_coords9 === undefined ? undefined : _positionA_coords9.screenY) !== ((_positionB_coords9 = positionB.coords) === null || _positionB_coords9 === undefined ? undefined : _positionB_coords9.screenY) || ((_positionA_caret = positionA.caret) === null || _positionA_caret === undefined ? undefined : _positionA_caret.node) !== ((_positionB_caret = positionB.caret) === null || _positionB_caret === undefined ? undefined : _positionB_caret.node) || ((_positionA_caret1 = positionA.caret) === null || _positionA_caret1 === undefined ? undefined : _positionA_caret1.offset) !== ((_positionB_caret1 = positionB.caret) === null || _positionB_caret1 === undefined ? undefined : _positionB_caret1.offset); +} + +exports.isDifferentPointerPosition = isDifferentPointerPosition; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utility/clear.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utility/clear.js new file mode 100644 index 0000000000000000000000000000000000000000..c7b728e4f0cb7265c1e4abbfb97caf6aa7da5ee9 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utility/clear.js @@ -0,0 +1,32 @@ +'use strict'; + +require('../event/behavior/click.js'); +require('../event/behavior/cut.js'); +require('../event/behavior/keydown.js'); +require('../event/behavior/keypress.js'); +require('../event/behavior/keyup.js'); +require('../event/behavior/paste.js'); +require('@testing-library/dom'); +require('../utils/dataTransfer/Clipboard.js'); +var isEditable = require('../utils/edit/isEditable.js'); +var isDisabled = require('../utils/misc/isDisabled.js'); +var focus = require('../event/focus.js'); +var input = require('../event/input.js'); +var selectAll = require('../event/selection/selectAll.js'); + +async function clear(element) { + if (!isEditable.isEditable(element) || isDisabled.isDisabled(element)) { + throw new Error('clear()` is only supported on editable elements.'); + } + focus.focusElement(element); + if (element.ownerDocument.activeElement !== element) { + throw new Error('The element to be cleared could not be focused.'); + } + selectAll.selectAll(element); + if (!selectAll.isAllSelected(element)) { + throw new Error('The element content to be cleared could not be selected.'); + } + input.input(this, element, '', 'deleteContentBackward'); +} + +exports.clear = clear; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utility/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utility/index.js new file mode 100644 index 0000000000000000000000000000000000000000..760f8e066df78509556cf5fe6e13855084f2f339 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utility/index.js @@ -0,0 +1,14 @@ +'use strict'; + +var clear = require('./clear.js'); +var selectOptions = require('./selectOptions.js'); +var type = require('./type.js'); +var upload = require('./upload.js'); + + + +exports.clear = clear.clear; +exports.deselectOptions = selectOptions.deselectOptions; +exports.selectOptions = selectOptions.selectOptions; +exports.type = type.type; +exports.upload = upload.upload; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utility/selectOptions.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utility/selectOptions.js new file mode 100644 index 0000000000000000000000000000000000000000..65a980fc1babddc21256f46082e3b09210cbd1cc --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utility/selectOptions.js @@ -0,0 +1,114 @@ +'use strict'; + +var dom = require('@testing-library/dom'); +var isElementType = require('../utils/misc/isElementType.js'); +require('../utils/dataTransfer/Clipboard.js'); +var isDisabled = require('../utils/misc/isDisabled.js'); +var wait = require('../utils/misc/wait.js'); +var cssPointerEvents = require('../utils/pointer/cssPointerEvents.js'); +require('../event/behavior/click.js'); +require('../event/behavior/cut.js'); +require('../event/behavior/keydown.js'); +require('../event/behavior/keypress.js'); +require('../event/behavior/keyup.js'); +require('../event/behavior/paste.js'); +var focus = require('../event/focus.js'); + +async function selectOptions(select, values) { + return selectOptionsBase.call(this, true, select, values); +} +async function deselectOptions(select, values) { + return selectOptionsBase.call(this, false, select, values); +} +async function selectOptionsBase(newValue, select, values) { + if (!newValue && !select.multiple) { + throw dom.getConfig().getElementError(`Unable to deselect an option in a non-multiple select. Use selectOptions to change the selection instead.`, select); + } + const valArray = Array.isArray(values) ? values : [ + values + ]; + const allOptions = Array.from(select.querySelectorAll('option, [role="option"]')); + const selectedOptions = valArray.map((val)=>{ + if (typeof val !== 'string' && allOptions.includes(val)) { + return val; + } else { + const matchingOption = allOptions.find((o)=>o.value === val || o.innerHTML === val); + if (matchingOption) { + return matchingOption; + } else { + throw dom.getConfig().getElementError(`Value "${String(val)}" not found in options`, select); + } + } + }).filter((option)=>!isDisabled.isDisabled(option)); + if (isDisabled.isDisabled(select) || !selectedOptions.length) return; + const selectOption = (option)=>{ + option.selected = newValue; + this.dispatchUIEvent(select, 'input', { + bubbles: true, + cancelable: false, + composed: true + }); + this.dispatchUIEvent(select, 'change'); + }; + if (isElementType.isElementType(select, 'select')) { + if (select.multiple) { + for (const option of selectedOptions){ + const withPointerEvents = this.config.pointerEventsCheck === 0 ? true : cssPointerEvents.hasPointerEvents(this, option); + // events fired for multiple select are weird. Can't use hover... + if (withPointerEvents) { + this.dispatchUIEvent(option, 'pointerover'); + this.dispatchUIEvent(select, 'pointerenter'); + this.dispatchUIEvent(option, 'mouseover'); + this.dispatchUIEvent(select, 'mouseenter'); + this.dispatchUIEvent(option, 'pointermove'); + this.dispatchUIEvent(option, 'mousemove'); + this.dispatchUIEvent(option, 'pointerdown'); + this.dispatchUIEvent(option, 'mousedown'); + } + focus.focusElement(select); + if (withPointerEvents) { + this.dispatchUIEvent(option, 'pointerup'); + this.dispatchUIEvent(option, 'mouseup'); + } + selectOption(option); + if (withPointerEvents) { + this.dispatchUIEvent(option, 'click'); + } + await wait.wait(this.config); + } + } else if (selectedOptions.length === 1) { + const withPointerEvents = this.config.pointerEventsCheck === 0 ? true : cssPointerEvents.hasPointerEvents(this, select); + // the click to open the select options + if (withPointerEvents) { + await this.click(select); + } else { + focus.focusElement(select); + } + selectOption(selectedOptions[0]); + if (withPointerEvents) { + // the browser triggers another click event on the select for the click on the option + // this second click has no 'down' phase + this.dispatchUIEvent(select, 'pointerover'); + this.dispatchUIEvent(select, 'pointerenter'); + this.dispatchUIEvent(select, 'mouseover'); + this.dispatchUIEvent(select, 'mouseenter'); + this.dispatchUIEvent(select, 'pointerup'); + this.dispatchUIEvent(select, 'mouseup'); + this.dispatchUIEvent(select, 'click'); + } + await wait.wait(this.config); + } else { + throw dom.getConfig().getElementError(`Cannot select multiple options on a non-multiple select`, select); + } + } else if (select.getAttribute('role') === 'listbox') { + for (const option of selectedOptions){ + await this.click(option); + await this.unhover(option); + } + } else { + throw dom.getConfig().getElementError(`Cannot select options on elements that are neither select nor listbox elements`, select); + } +} + +exports.deselectOptions = deselectOptions; +exports.selectOptions = selectOptions; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utility/type.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utility/type.js new file mode 100644 index 0000000000000000000000000000000000000000..f330ec74a9839f9de02e730d24b8e38471d86cfa --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utility/type.js @@ -0,0 +1,23 @@ +'use strict'; + +var index = require('../keyboard/index.js'); +require('../utils/dataTransfer/Clipboard.js'); +var setSelectionRange = require('../event/selection/setSelectionRange.js'); + +async function type(element, text, { skipClick = this.config.skipClick, skipAutoClose = this.config.skipAutoClose, initialSelectionStart, initialSelectionEnd } = {}) { + // TODO: properly type guard + // we use this workaround for now to prevent changing behavior + if (element.disabled) return; + if (!skipClick) { + await this.click(element); + } + if (initialSelectionStart !== undefined) { + setSelectionRange.setSelectionRange(element, initialSelectionStart, initialSelectionEnd !== null && initialSelectionEnd !== undefined ? initialSelectionEnd : initialSelectionStart); + } + await this.keyboard(text); + if (!skipAutoClose) { + await index.releaseAllKeys(this); + } +} + +exports.type = type; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utility/upload.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utility/upload.js new file mode 100644 index 0000000000000000000000000000000000000000..4a698b9b5b9c160bc8e4869ef16a9aac5bcc908c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utility/upload.js @@ -0,0 +1,62 @@ +'use strict'; + +var isElementType = require('../utils/misc/isElementType.js'); +var FileList = require('../utils/dataTransfer/FileList.js'); +require('../utils/dataTransfer/Clipboard.js'); +var setFiles = require('../utils/edit/setFiles.js'); +var isDisabled = require('../utils/misc/isDisabled.js'); +var getWindow = require('../utils/misc/getWindow.js'); + +async function upload(element, fileOrFiles) { + const input = isElementType.isElementType(element, 'label') ? element.control : element; + if (!input || !isElementType.isElementType(input, 'input', { + type: 'file' + })) { + throw new TypeError(`The ${input === element ? 'given' : 'associated'} ${input === null || input === undefined ? undefined : input.tagName} element does not accept file uploads`); + } + if (isDisabled.isDisabled(element)) return; + const files = (Array.isArray(fileOrFiles) ? fileOrFiles : [ + fileOrFiles + ]).filter((file)=>!this.config.applyAccept || isAcceptableFile(file, input.accept)).slice(0, input.multiple ? undefined : 1); + const fileDialog = ()=>{ + var _input_files; + // do not fire an input event if the file selection does not change + if (files.length === ((_input_files = input.files) === null || _input_files === undefined ? undefined : _input_files.length) && files.every((f, i)=>{ + var _input_files; + return f === ((_input_files = input.files) === null || _input_files === undefined ? undefined : _input_files.item(i)); + })) { + return; + } + setFiles.setFiles(input, FileList.createFileList(getWindow.getWindow(element), files)); + this.dispatchUIEvent(input, 'input'); + this.dispatchUIEvent(input, 'change'); + }; + input.addEventListener('fileDialog', fileDialog); + await this.click(element); + input.removeEventListener('fileDialog', fileDialog); +} +// When matching files, browsers ignore case and consider jpeg/jpg interchangeable. +function normalize(nameOrType) { + return nameOrType.toLowerCase().replace(/(\.|\/)jpg\b/g, '$1jpeg'); +} +function isAcceptableFile(file, accept) { + if (!accept) { + return true; + } + const wildcards = [ + 'audio/*', + 'image/*', + 'video/*' + ]; + return normalize(accept).trim().split(/\s*,\s*/).some((acceptToken)=>{ + // tokens starting with a dot represent a file extension + if (acceptToken.startsWith('.')) { + return normalize(file.name).endsWith(acceptToken); + } else if (wildcards.includes(acceptToken)) { + return normalize(file.type).startsWith(acceptToken.replace('*', '')); + } + return normalize(file.type) === acceptToken; + }); +} + +exports.upload = upload; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/click/isClickableInput.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/click/isClickableInput.js new file mode 100644 index 0000000000000000000000000000000000000000..4a40daf781dcc9e4a7da988fd9d9d888a8040038 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/click/isClickableInput.js @@ -0,0 +1,20 @@ +'use strict'; + +var isElementType = require('../misc/isElementType.js'); + +var clickableInputTypes = /*#__PURE__*/ function(clickableInputTypes) { + clickableInputTypes["button"] = "button"; + clickableInputTypes["color"] = "color"; + clickableInputTypes["file"] = "file"; + clickableInputTypes["image"] = "image"; + clickableInputTypes["reset"] = "reset"; + clickableInputTypes["submit"] = "submit"; + clickableInputTypes["checkbox"] = "checkbox"; + clickableInputTypes["radio"] = "radio"; + return clickableInputTypes; +}(clickableInputTypes || {}); +function isClickableInput(element) { + return isElementType.isElementType(element, 'button') || isElementType.isElementType(element, 'input') && element.type in clickableInputTypes; +} + +exports.isClickableInput = isClickableInput; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/dataTransfer/Blob.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/dataTransfer/Blob.js new file mode 100644 index 0000000000000000000000000000000000000000..ea2deb7a5a6471b63bf5d73e2a8a2b5b1b1b7e26 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/dataTransfer/Blob.js @@ -0,0 +1,16 @@ +'use strict'; + +// jsdom does not implement Blob.text() +function readBlobText(blob, FileReader) { + return new Promise((res, rej)=>{ + const fr = new FileReader(); + fr.onerror = rej; + fr.onabort = rej; + fr.onload = ()=>{ + res(String(fr.result)); + }; + fr.readAsText(blob); + }); +} + +exports.readBlobText = readBlobText; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/dataTransfer/Clipboard.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/dataTransfer/Clipboard.js new file mode 100644 index 0000000000000000000000000000000000000000..434be791b156984a8b76287bc0cc6c8955df4203 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/dataTransfer/Clipboard.js @@ -0,0 +1,169 @@ +'use strict'; + +var getWindow = require('../misc/getWindow.js'); +var Blob = require('./Blob.js'); +var DataTransfer = require('./DataTransfer.js'); + +// Clipboard is not available in jsdom +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +// MDN lists string|Blob|Promise as possible types in ClipboardItemData +// lib.dom.d.ts lists only Promise +// https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem/ClipboardItem#syntax +function createClipboardItem(window, ...blobs) { + const dataMap = Object.fromEntries(blobs.map((b)=>[ + typeof b === 'string' ? 'text/plain' : b.type, + Promise.resolve(b) + ])); + // use real ClipboardItem if available + /* istanbul ignore if */ if (typeof window.ClipboardItem !== 'undefined') { + return new window.ClipboardItem(dataMap); + } + return new class ClipboardItem { + get types() { + return Array.from(Object.keys(this.data)); + } + async getType(type) { + const value = await this.data[type]; + if (!value) { + throw new Error(`${type} is not one of the available MIME types on this item.`); + } + return value instanceof window.Blob ? value : new window.Blob([ + value + ], { + type + }); + } + constructor(d){ + _define_property(this, "data", undefined); + this.data = d; + } + }(dataMap); +} +const ClipboardStubControl = Symbol('Manage ClipboardSub'); +function createClipboardStub(window, control) { + return Object.assign(new class Clipboard extends window.EventTarget { + async read() { + return Array.from(this.items); + } + async readText() { + let text = ''; + for (const item of this.items){ + const type = item.types.includes('text/plain') ? 'text/plain' : item.types.find((t)=>t.startsWith('text/')); + if (type) { + text += await item.getType(type).then((b)=>Blob.readBlobText(b, window.FileReader)); + } + } + return text; + } + async write(data) { + this.items = data; + } + async writeText(text) { + this.items = [ + createClipboardItem(window, text) + ]; + } + constructor(...args){ + super(...args), _define_property(this, "items", []); + } + }(), { + [ClipboardStubControl]: control + }); +} +function isClipboardStub(clipboard) { + return !!(clipboard === null || clipboard === undefined ? undefined : clipboard[ClipboardStubControl]); +} +function attachClipboardStubToView(window) { + if (isClipboardStub(window.navigator.clipboard)) { + return window.navigator.clipboard[ClipboardStubControl]; + } + const realClipboard = Object.getOwnPropertyDescriptor(window.navigator, 'clipboard'); + let stub; + const control = { + resetClipboardStub: ()=>{ + stub = createClipboardStub(window, control); + }, + detachClipboardStub: ()=>{ + /* istanbul ignore if */ if (realClipboard) { + Object.defineProperty(window.navigator, 'clipboard', realClipboard); + } else { + Object.defineProperty(window.navigator, 'clipboard', { + value: undefined, + configurable: true + }); + } + } + }; + stub = createClipboardStub(window, control); + Object.defineProperty(window.navigator, 'clipboard', { + get: ()=>stub, + configurable: true + }); + return stub[ClipboardStubControl]; +} +function resetClipboardStubOnView(window) { + if (isClipboardStub(window.navigator.clipboard)) { + window.navigator.clipboard[ClipboardStubControl].resetClipboardStub(); + } +} +function detachClipboardStubFromView(window) { + if (isClipboardStub(window.navigator.clipboard)) { + window.navigator.clipboard[ClipboardStubControl].detachClipboardStub(); + } +} +async function readDataTransferFromClipboard(document) { + const window = document.defaultView; + const clipboard = window === null || window === undefined ? undefined : window.navigator.clipboard; + const items = clipboard && await clipboard.read(); + if (!items) { + throw new Error('The Clipboard API is unavailable.'); + } + const dt = DataTransfer.createDataTransfer(window); + for (const item of items){ + for (const type of item.types){ + dt.setData(type, await item.getType(type).then((b)=>Blob.readBlobText(b, window.FileReader))); + } + } + return dt; +} +async function writeDataTransferToClipboard(document, clipboardData) { + const window = getWindow.getWindow(document); + const clipboard = window.navigator.clipboard; + const items = []; + for(let i = 0; i < clipboardData.items.length; i++){ + const dtItem = clipboardData.items[i]; + const blob = await DataTransfer.getBlobFromDataTransferItem(window, dtItem); + items.push(createClipboardItem(window, blob)); + } + const written = clipboard && await clipboard.write(items).then(()=>true, // Can happen with other implementations that e.g. require permissions + /* istanbul ignore next */ ()=>false); + if (!written) { + throw new Error('The Clipboard API is unavailable.'); + } +} +const g = globalThis; +/* istanbul ignore else */ if (typeof g.afterEach === 'function') { + g.afterEach(()=>resetClipboardStubOnView(globalThis.window)); +} +/* istanbul ignore else */ if (typeof g.afterAll === 'function') { + g.afterAll(()=>detachClipboardStubFromView(globalThis.window)); +} + +exports.attachClipboardStubToView = attachClipboardStubToView; +exports.createClipboardItem = createClipboardItem; +exports.detachClipboardStubFromView = detachClipboardStubFromView; +exports.readDataTransferFromClipboard = readDataTransferFromClipboard; +exports.resetClipboardStubOnView = resetClipboardStubOnView; +exports.writeDataTransferToClipboard = writeDataTransferToClipboard; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/dataTransfer/DataTransfer.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/dataTransfer/DataTransfer.js new file mode 100644 index 0000000000000000000000000000000000000000..f0d8c204e247b1a408c72d1cd753031ba24e5262 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/dataTransfer/DataTransfer.js @@ -0,0 +1,136 @@ +'use strict'; + +var FileList = require('./FileList.js'); + +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +// DataTransfer is not implemented in jsdom. +// DataTransfer with FileList is being created by the browser on certain events. +class DataTransferItemStub { + getAsFile() { + return this.file; + } + getAsString(callback) { + if (typeof this.data === 'string') { + callback(this.data); + } + } + /* istanbul ignore next */ webkitGetAsEntry() { + throw new Error('not implemented'); + } + constructor(dataOrFile, type){ + _define_property(this, "kind", undefined); + _define_property(this, "type", undefined); + _define_property(this, "file", null); + _define_property(this, "data", undefined); + if (typeof dataOrFile === 'string') { + this.kind = 'string'; + this.type = String(type); + this.data = dataOrFile; + } else { + this.kind = 'file'; + this.type = dataOrFile.type; + this.file = dataOrFile; + } + } +} +class DataTransferItemListStub extends Array { + add(...args) { + const item = new DataTransferItemStub(args[0], args[1]); + this.push(item); + return item; + } + clear() { + this.splice(0, this.length); + } + remove(index) { + this.splice(index, 1); + } +} +function getTypeMatcher(type, exact) { + const [group, sub] = type.split('/'); + const isGroup = !sub || sub === '*'; + return (item)=>{ + return exact ? item.type === (isGroup ? group : type) : isGroup ? item.type.startsWith(`${group}/`) : item.type === group; + }; +} +function createDataTransferStub(window) { + return new class DataTransferStub { + getData(format) { + var _this_items_find; + const match = (_this_items_find = this.items.find(getTypeMatcher(format, true))) !== null && _this_items_find !== undefined ? _this_items_find : this.items.find(getTypeMatcher(format, false)); + let text = ''; + match === null || match === undefined ? undefined : match.getAsString((t)=>{ + text = t; + }); + return text; + } + setData(format, data) { + const matchIndex = this.items.findIndex(getTypeMatcher(format, true)); + const item = new DataTransferItemStub(data, format); + if (matchIndex >= 0) { + this.items.splice(matchIndex, 1, item); + } else { + this.items.push(item); + } + } + clearData(format) { + if (format) { + const matchIndex = this.items.findIndex(getTypeMatcher(format, true)); + if (matchIndex >= 0) { + this.items.remove(matchIndex); + } + } else { + this.items.clear(); + } + } + get types() { + const t = []; + if (this.files.length) { + t.push('Files'); + } + this.items.forEach((i)=>t.push(i.type)); + Object.freeze(t); + return t; + } + /* istanbul ignore next */ setDragImage() {} + constructor(){ + _define_property(this, "dropEffect", 'none'); + _define_property(this, "effectAllowed", 'uninitialized'); + _define_property(this, "items", new DataTransferItemListStub()); + _define_property(this, "files", FileList.createFileList(window, [])); + } + }(); +} +function createDataTransfer(window, files = []) { + // Use real DataTransfer if available + const dt = typeof window.DataTransfer === 'undefined' ? createDataTransferStub(window) : /* istanbul ignore next */ new window.DataTransfer(); + Object.defineProperty(dt, 'files', { + get: ()=>FileList.createFileList(window, files) + }); + return dt; +} +async function getBlobFromDataTransferItem(window, item) { + if (item.kind === 'file') { + return item.getAsFile(); + } + return new window.Blob([ + await new Promise((r)=>item.getAsString(r)) + ], { + type: item.type + }); +} + +exports.createDataTransfer = createDataTransfer; +exports.getBlobFromDataTransferItem = getBlobFromDataTransferItem; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/dataTransfer/FileList.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/dataTransfer/FileList.js new file mode 100644 index 0000000000000000000000000000000000000000..db71e9cc7585b33ff4cc20dacc5d5fb298e10c95 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/dataTransfer/FileList.js @@ -0,0 +1,24 @@ +'use strict'; + +// FileList can not be created per constructor. +function createFileList(window, files) { + const list = { + ...files, + length: files.length, + item: (index)=>list[index], + [Symbol.iterator]: function* nextFile() { + for(let i = 0; i < list.length; i++){ + yield list[i]; + } + } + }; + list.constructor = window.FileList; + // guard for environments without FileList + /* istanbul ignore else */ if (window.FileList) { + Object.setPrototypeOf(list, window.FileList.prototype); + } + Object.freeze(list); + return list; +} + +exports.createFileList = createFileList; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/edit/isContentEditable.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/edit/isContentEditable.js new file mode 100644 index 0000000000000000000000000000000000000000..fdae7753a0d7adf38223ae330f0cea549bec05b3 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/edit/isContentEditable.js @@ -0,0 +1,18 @@ +'use strict'; + +//jsdom is not supporting isContentEditable +function isContentEditable(element) { + return element.hasAttribute('contenteditable') && (element.getAttribute('contenteditable') == 'true' || element.getAttribute('contenteditable') == ''); +} +/** + * If a node is a contenteditable or inside one, return that element. + */ function getContentEditable(node) { + const element = getElement(node); + return element && (element.closest('[contenteditable=""]') || element.closest('[contenteditable="true"]')); +} +function getElement(node) { + return node.nodeType === 1 ? node : node.parentElement; +} + +exports.getContentEditable = getContentEditable; +exports.isContentEditable = isContentEditable; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/edit/isEditable.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/edit/isEditable.js new file mode 100644 index 0000000000000000000000000000000000000000..5f295bc7cbf48babcc80a7981715e68616493a1b --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/edit/isEditable.js @@ -0,0 +1,29 @@ +'use strict'; + +var isElementType = require('../misc/isElementType.js'); +var isContentEditable = require('./isContentEditable.js'); + +function isEditable(element) { + return isEditableInputOrTextArea(element) && !element.readOnly || isContentEditable.isContentEditable(element); +} +var editableInputTypes = /*#__PURE__*/ function(editableInputTypes) { + editableInputTypes["text"] = "text"; + editableInputTypes["date"] = "date"; + editableInputTypes["datetime-local"] = "datetime-local"; + editableInputTypes["email"] = "email"; + editableInputTypes["month"] = "month"; + editableInputTypes["number"] = "number"; + editableInputTypes["password"] = "password"; + editableInputTypes["search"] = "search"; + editableInputTypes["tel"] = "tel"; + editableInputTypes["time"] = "time"; + editableInputTypes["url"] = "url"; + editableInputTypes["week"] = "week"; + return editableInputTypes; +}(editableInputTypes || {}); +function isEditableInputOrTextArea(element) { + return isElementType.isElementType(element, 'textarea') || isElementType.isElementType(element, 'input') && element.type in editableInputTypes; +} + +exports.isEditable = isEditable; +exports.isEditableInputOrTextArea = isEditableInputOrTextArea; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/edit/maxLength.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/edit/maxLength.js new file mode 100644 index 0000000000000000000000000000000000000000..0839d9647973f5062b561220c576c3e8f5a76746 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/edit/maxLength.js @@ -0,0 +1,26 @@ +'use strict'; + +var isElementType = require('../misc/isElementType.js'); + +var maxLengthSupportedTypes = /*#__PURE__*/ function(maxLengthSupportedTypes) { + maxLengthSupportedTypes["email"] = "email"; + maxLengthSupportedTypes["password"] = "password"; + maxLengthSupportedTypes["search"] = "search"; + maxLengthSupportedTypes["telephone"] = "telephone"; + maxLengthSupportedTypes["text"] = "text"; + maxLengthSupportedTypes["url"] = "url"; + return maxLengthSupportedTypes; +}(maxLengthSupportedTypes || {}); +// can't use .maxLength property because of a jsdom bug: +// https://github.com/jsdom/jsdom/issues/2927 +function getMaxLength(element) { + var _element_getAttribute; + const attr = (_element_getAttribute = element.getAttribute('maxlength')) !== null && _element_getAttribute !== undefined ? _element_getAttribute : ''; + return /^\d+$/.test(attr) && Number(attr) >= 0 ? Number(attr) : undefined; +} +function supportsMaxLength(element) { + return isElementType.isElementType(element, 'textarea') || isElementType.isElementType(element, 'input') && element.type in maxLengthSupportedTypes; +} + +exports.getMaxLength = getMaxLength; +exports.supportsMaxLength = supportsMaxLength; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/edit/setFiles.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/edit/setFiles.js new file mode 100644 index 0000000000000000000000000000000000000000..c309feebd36081022930ade6ad34249f8273c96f --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/edit/setFiles.js @@ -0,0 +1,59 @@ +'use strict'; + +// It is not possible to create a real FileList programmatically. +// Therefore assigning `files` property with a programmatically created FileList results in an error. +// Just assigning the property (as per fireEvent) breaks the interweaving with the `value` property. +const fakeFiles = Symbol('files and value properties are mocked'); +function restoreProperty(obj, prop, descriptor) { + if (descriptor) { + Object.defineProperty(obj, prop, descriptor); + } else { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete obj[prop]; + } +} +function setFiles(el, files) { + var _el_fakeFiles; + (_el_fakeFiles = el[fakeFiles]) === null || _el_fakeFiles === undefined ? undefined : _el_fakeFiles.restore(); + const typeDescr = Object.getOwnPropertyDescriptor(el, 'type'); + const valueDescr = Object.getOwnPropertyDescriptor(el, 'value'); + const filesDescr = Object.getOwnPropertyDescriptor(el, 'files'); + function restore() { + restoreProperty(el, 'type', typeDescr); + restoreProperty(el, 'value', valueDescr); + restoreProperty(el, 'files', filesDescr); + } + el[fakeFiles] = { + restore + }; + Object.defineProperties(el, { + files: { + configurable: true, + get: ()=>files + }, + value: { + configurable: true, + get: ()=>files.length ? `C:\\fakepath\\${files[0].name}` : '', + set (v) { + if (v === '') { + restore(); + } else { + var _valueDescr_set; + valueDescr === null || valueDescr === undefined ? undefined : (_valueDescr_set = valueDescr.set) === null || _valueDescr_set === undefined ? undefined : _valueDescr_set.call(el, v); + } + } + }, + type: { + configurable: true, + get: ()=>'file', + set (v) { + if (v !== 'file') { + restore(); + el.type = v; + } + } + } + }); +} + +exports.setFiles = setFiles; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/edit/timeValue.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/edit/timeValue.js new file mode 100644 index 0000000000000000000000000000000000000000..fac7bc5b1dea1c4b0c0c731d9fe95d085353c5ac --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/edit/timeValue.js @@ -0,0 +1,40 @@ +'use strict'; + +const parseInt = globalThis.parseInt; +function buildTimeValue(value) { + const onlyDigitsValue = value.replace(/\D/g, ''); + if (onlyDigitsValue.length < 2) { + return value; + } + const firstDigit = parseInt(onlyDigitsValue[0], 10); + const secondDigit = parseInt(onlyDigitsValue[1], 10); + if (firstDigit >= 3 || firstDigit === 2 && secondDigit >= 4) { + let index; + if (firstDigit >= 3) { + index = 1; + } else { + index = 2; + } + return build(onlyDigitsValue, index); + } + if (value.length === 2) { + return value; + } + return build(onlyDigitsValue, 2); +} +function build(onlyDigitsValue, index) { + const hours = onlyDigitsValue.slice(0, index); + const validHours = Math.min(parseInt(hours, 10), 23); + const minuteCharacters = onlyDigitsValue.slice(index); + const parsedMinutes = parseInt(minuteCharacters, 10); + const validMinutes = Math.min(parsedMinutes, 59); + return `${validHours.toString().padStart(2, '0')}:${validMinutes.toString().padStart(2, '0')}`; +} +function isValidDateOrTimeValue(element, value) { + const clone = element.cloneNode(); + clone.value = value; + return clone.value === value; +} + +exports.buildTimeValue = buildTimeValue; +exports.isValidDateOrTimeValue = isValidDateOrTimeValue; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/cursor.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/cursor.js new file mode 100644 index 0000000000000000000000000000000000000000..a9429615303b2b1c1d93208ea90a4009293265d1 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/cursor.js @@ -0,0 +1,126 @@ +'use strict'; + +var isContentEditable = require('../edit/isContentEditable.js'); +var isElementType = require('../misc/isElementType.js'); + +function getNextCursorPosition(node, offset, direction, inputType) { + // The behavior at text node zero offset is inconsistent. + // When walking backwards: + // Firefox always moves to zero offset and jumps over last offset. + // Chrome jumps over zero offset per default but over last offset when Shift is pressed. + // The cursor always moves to zero offset if the focus area (contenteditable or body) ends there. + // When walking forward both ignore zero offset. + // When walking over input elements the cursor moves before or after that element. + // When walking over line breaks the cursor moves inside any following text node. + if (isTextNode(node) && offset + direction >= 0 && offset + direction <= node.nodeValue.length) { + return { + node, + offset: offset + direction + }; + } + const nextNode = getNextCharacterContentNode(node, offset, direction); + if (nextNode) { + if (isTextNode(nextNode)) { + return { + node: nextNode, + offset: direction > 0 ? Math.min(1, nextNode.nodeValue.length) : Math.max(nextNode.nodeValue.length - 1, 0) + }; + } else if (isElementType.isElementType(nextNode, 'br')) { + const nextPlusOne = getNextCharacterContentNode(nextNode, undefined, direction); + if (!nextPlusOne) { + // The behavior when there is no possible cursor position beyond the line break is inconsistent. + // In Chrome outside of contenteditable moving before a leading line break is possible. + // A leading line break can still be removed per deleteContentBackward. + // A trailing line break on the other hand is not removed by deleteContentForward. + if (direction < 0 && inputType === 'deleteContentBackward') { + return { + node: nextNode.parentNode, + offset: getOffset(nextNode) + }; + } + return undefined; + } else if (isTextNode(nextPlusOne)) { + return { + node: nextPlusOne, + offset: direction > 0 ? 0 : nextPlusOne.nodeValue.length + }; + } else if (direction < 0 && isElementType.isElementType(nextPlusOne, 'br')) { + return { + node: nextNode.parentNode, + offset: getOffset(nextNode) + }; + } else { + return { + node: nextPlusOne.parentNode, + offset: getOffset(nextPlusOne) + (direction > 0 ? 0 : 1) + }; + } + } else { + return { + node: nextNode.parentNode, + offset: getOffset(nextNode) + (direction > 0 ? 1 : 0) + }; + } + } +} +function getNextCharacterContentNode(node, offset, direction) { + const nextOffset = Number(offset) + (direction < 0 ? -1 : 0); + if (offset !== undefined && isElement(node) && nextOffset >= 0 && nextOffset < node.children.length) { + node = node.children[nextOffset]; + } + return walkNodes(node, direction === 1 ? 'next' : 'previous', isTreatedAsCharacterContent); +} +function isTreatedAsCharacterContent(node) { + if (isTextNode(node)) { + return true; + } + if (isElement(node)) { + if (isElementType.isElementType(node, [ + 'input', + 'textarea' + ])) { + return node.type !== 'hidden'; + } else if (isElementType.isElementType(node, 'br')) { + return true; + } + } + return false; +} +function getOffset(node) { + let i = 0; + while(node.previousSibling){ + i++; + node = node.previousSibling; + } + return i; +} +function isElement(node) { + return node.nodeType === 1; +} +function isTextNode(node) { + return node.nodeType === 3; +} +function walkNodes(node, direction, callback) { + for(;;){ + var _node_ownerDocument; + const sibling = node[`${direction}Sibling`]; + if (sibling) { + node = getDescendant(sibling, direction === 'next' ? 'first' : 'last'); + if (callback(node)) { + return node; + } + } else if (node.parentNode && (!isElement(node.parentNode) || !isContentEditable.isContentEditable(node.parentNode) && node.parentNode !== ((_node_ownerDocument = node.ownerDocument) === null || _node_ownerDocument === undefined ? undefined : _node_ownerDocument.body))) { + node = node.parentNode; + } else { + break; + } + } +} +function getDescendant(node, direction) { + while(node.hasChildNodes()){ + node = node[`${direction}Child`]; + } + return node; +} + +exports.getNextCursorPosition = getNextCursorPosition; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/getActiveElement.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/getActiveElement.js new file mode 100644 index 0000000000000000000000000000000000000000..d25f3a8ef67e856e43614559f73012899c0b53d7 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/getActiveElement.js @@ -0,0 +1,23 @@ +'use strict'; + +var isDisabled = require('../misc/isDisabled.js'); + +function getActiveElement(document) { + const activeElement = document.activeElement; + if (activeElement === null || activeElement === undefined ? undefined : activeElement.shadowRoot) { + return getActiveElement(activeElement.shadowRoot); + } else { + // Browser does not yield disabled elements as document.activeElement - jsdom does + if (isDisabled.isDisabled(activeElement)) { + return document.ownerDocument ? /* istanbul ignore next */ document.ownerDocument.body : document.body; + } + return activeElement; + } +} +function getActiveElementOrBody(document) { + var _getActiveElement; + return (_getActiveElement = getActiveElement(document)) !== null && _getActiveElement !== undefined ? _getActiveElement : /* istanbul ignore next */ document.body; +} + +exports.getActiveElement = getActiveElement; +exports.getActiveElementOrBody = getActiveElementOrBody; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/getTabDestination.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/getTabDestination.js new file mode 100644 index 0000000000000000000000000000000000000000..01505a57423975836c00909e89cc6ddb92bf03ad --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/getTabDestination.js @@ -0,0 +1,80 @@ +'use strict'; + +var isDisabled = require('../misc/isDisabled.js'); +var isElementType = require('../misc/isElementType.js'); +var isVisible = require('../misc/isVisible.js'); +var selector = require('./selector.js'); + +function getTabDestination(activeElement, shift) { + const document = activeElement.ownerDocument; + const focusableElements = document.querySelectorAll(selector.FOCUSABLE_SELECTOR); + const enabledElements = Array.from(focusableElements).filter((el)=>el === activeElement || !(Number(el.getAttribute('tabindex')) < 0 || isDisabled.isDisabled(el))); + // tabindex has no effect if the active element has negative tabindex + if (Number(activeElement.getAttribute('tabindex')) >= 0) { + enabledElements.sort((a, b)=>{ + const i = Number(a.getAttribute('tabindex')); + const j = Number(b.getAttribute('tabindex')); + if (i === j) { + return 0; + } else if (i === 0) { + return 1; + } else if (j === 0) { + return -1; + } + return i - j; + }); + } + const checkedRadio = {}; + let prunedElements = [ + document.body + ]; + const activeRadioGroup = isElementType.isElementType(activeElement, 'input', { + type: 'radio' + }) ? activeElement.name : undefined; + enabledElements.forEach((currentElement)=>{ + const el = currentElement; + // For radio groups keep only the active radio + // If there is no active radio, keep only the checked radio + // If there is no checked radio, treat like everything else + if (isElementType.isElementType(el, 'input', { + type: 'radio' + }) && el.name) { + // If the active element is part of the group, add only that + if (el === activeElement) { + prunedElements.push(el); + return; + } else if (el.name === activeRadioGroup) { + return; + } + // If we stumble upon a checked radio, remove the others + if (el.checked) { + prunedElements = prunedElements.filter((e)=>!isElementType.isElementType(e, 'input', { + type: 'radio', + name: el.name + })); + prunedElements.push(el); + checkedRadio[el.name] = el; + return; + } + // If we already found the checked one, skip + if (typeof checkedRadio[el.name] !== 'undefined') { + return; + } + } + prunedElements.push(el); + }); + for(let index = prunedElements.findIndex((el)=>el === activeElement);;){ + index += shift ? -1 : 1; + // loop at overflow + if (index === prunedElements.length) { + index = 0; + } else if (index === -1) { + index = prunedElements.length - 1; + } + if (prunedElements[index] === activeElement || prunedElements[index] === document.body || isVisible.isVisible(prunedElements[index])) { + return prunedElements[index]; + } + } +} + +exports.getTabDestination = getTabDestination; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/isFocusable.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/isFocusable.js new file mode 100644 index 0000000000000000000000000000000000000000..764a339935c6485597750647844cc065dcd077e9 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/isFocusable.js @@ -0,0 +1,9 @@ +'use strict'; + +var selector = require('./selector.js'); + +function isFocusable(element) { + return element.matches(selector.FOCUSABLE_SELECTOR); +} + +exports.isFocusable = isFocusable; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/selection.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/selection.js new file mode 100644 index 0000000000000000000000000000000000000000..cc8278eae59cbbb689356abaae98b6ee9baaed18 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/selection.js @@ -0,0 +1,20 @@ +'use strict'; + +var isClickableInput = require('../click/isClickableInput.js'); +var isEditable = require('../edit/isEditable.js'); + +/** + * Determine if the element has its own selection implementation + * and does not interact with the Document Selection API. + */ function hasOwnSelection(node) { + return isElement(node) && isEditable.isEditableInputOrTextArea(node); +} +function hasNoSelection(node) { + return isElement(node) && isClickableInput.isClickableInput(node); +} +function isElement(node) { + return node.nodeType === 1; +} + +exports.hasNoSelection = hasNoSelection; +exports.hasOwnSelection = hasOwnSelection; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/selector.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/selector.js new file mode 100644 index 0000000000000000000000000000000000000000..198e1f14bb38bdfbb4a011a232545937e37d2ea8 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/focus/selector.js @@ -0,0 +1,14 @@ +'use strict'; + +const FOCUSABLE_SELECTOR = [ + 'input:not([type=hidden]):not([disabled])', + 'button:not([disabled])', + 'select:not([disabled])', + 'textarea:not([disabled])', + '[contenteditable=""]', + '[contenteditable="true"]', + 'a[href]', + '[tabindex]:not([disabled])' +].join(', '); + +exports.FOCUSABLE_SELECTOR = FOCUSABLE_SELECTOR; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9d8285155ac915dae284b810c3596255f3733f89 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/index.js @@ -0,0 +1,78 @@ +'use strict'; + +var isClickableInput = require('./click/isClickableInput.js'); +var Blob = require('./dataTransfer/Blob.js'); +var DataTransfer = require('./dataTransfer/DataTransfer.js'); +var FileList = require('./dataTransfer/FileList.js'); +var Clipboard = require('./dataTransfer/Clipboard.js'); +var timeValue = require('./edit/timeValue.js'); +var isContentEditable = require('./edit/isContentEditable.js'); +var isEditable = require('./edit/isEditable.js'); +var maxLength = require('./edit/maxLength.js'); +var setFiles = require('./edit/setFiles.js'); +var cursor = require('./focus/cursor.js'); +var getActiveElement = require('./focus/getActiveElement.js'); +var getTabDestination = require('./focus/getTabDestination.js'); +var isFocusable = require('./focus/isFocusable.js'); +var selection = require('./focus/selection.js'); +var selector = require('./focus/selector.js'); +var readNextDescriptor = require('./keyDef/readNextDescriptor.js'); +var cloneEvent = require('./misc/cloneEvent.js'); +var findClosest = require('./misc/findClosest.js'); +var getDocumentFromNode = require('./misc/getDocumentFromNode.js'); +var getTreeDiff = require('./misc/getTreeDiff.js'); +var getWindow = require('./misc/getWindow.js'); +var isDescendantOrSelf = require('./misc/isDescendantOrSelf.js'); +var isElementType = require('./misc/isElementType.js'); +var isVisible = require('./misc/isVisible.js'); +var isDisabled = require('./misc/isDisabled.js'); +var level = require('./misc/level.js'); +var wait = require('./misc/wait.js'); +var cssPointerEvents = require('./pointer/cssPointerEvents.js'); + + + +exports.isClickableInput = isClickableInput.isClickableInput; +exports.readBlobText = Blob.readBlobText; +exports.createDataTransfer = DataTransfer.createDataTransfer; +exports.getBlobFromDataTransferItem = DataTransfer.getBlobFromDataTransferItem; +exports.createFileList = FileList.createFileList; +exports.attachClipboardStubToView = Clipboard.attachClipboardStubToView; +exports.createClipboardItem = Clipboard.createClipboardItem; +exports.detachClipboardStubFromView = Clipboard.detachClipboardStubFromView; +exports.readDataTransferFromClipboard = Clipboard.readDataTransferFromClipboard; +exports.resetClipboardStubOnView = Clipboard.resetClipboardStubOnView; +exports.writeDataTransferToClipboard = Clipboard.writeDataTransferToClipboard; +exports.buildTimeValue = timeValue.buildTimeValue; +exports.isValidDateOrTimeValue = timeValue.isValidDateOrTimeValue; +exports.getContentEditable = isContentEditable.getContentEditable; +exports.isContentEditable = isContentEditable.isContentEditable; +exports.isEditable = isEditable.isEditable; +exports.isEditableInputOrTextArea = isEditable.isEditableInputOrTextArea; +exports.getMaxLength = maxLength.getMaxLength; +exports.supportsMaxLength = maxLength.supportsMaxLength; +exports.setFiles = setFiles.setFiles; +exports.getNextCursorPosition = cursor.getNextCursorPosition; +exports.getActiveElement = getActiveElement.getActiveElement; +exports.getActiveElementOrBody = getActiveElement.getActiveElementOrBody; +exports.getTabDestination = getTabDestination.getTabDestination; +exports.isFocusable = isFocusable.isFocusable; +exports.hasNoSelection = selection.hasNoSelection; +exports.hasOwnSelection = selection.hasOwnSelection; +exports.FOCUSABLE_SELECTOR = selector.FOCUSABLE_SELECTOR; +exports.readNextDescriptor = readNextDescriptor.readNextDescriptor; +exports.cloneEvent = cloneEvent.cloneEvent; +exports.findClosest = findClosest.findClosest; +exports.getDocumentFromNode = getDocumentFromNode.getDocumentFromNode; +exports.getTreeDiff = getTreeDiff.getTreeDiff; +exports.getWindow = getWindow.getWindow; +exports.isDescendantOrSelf = isDescendantOrSelf.isDescendantOrSelf; +exports.isElementType = isElementType.isElementType; +exports.isVisible = isVisible.isVisible; +exports.isDisabled = isDisabled.isDisabled; +exports.ApiLevel = level.ApiLevel; +exports.getLevelRef = level.getLevelRef; +exports.setLevelRef = level.setLevelRef; +exports.wait = wait.wait; +exports.assertPointerEvents = cssPointerEvents.assertPointerEvents; +exports.hasPointerEvents = cssPointerEvents.hasPointerEvents; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/keyDef/readNextDescriptor.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/keyDef/readNextDescriptor.js new file mode 100644 index 0000000000000000000000000000000000000000..624bd17580778211244bde3b0f151195e7ac29a6 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/keyDef/readNextDescriptor.js @@ -0,0 +1,92 @@ +'use strict'; + +var bracketDict = /*#__PURE__*/ function(bracketDict) { + bracketDict["{"] = "}"; + bracketDict["["] = "]"; + return bracketDict; +}(bracketDict || {}); +/** + * Read the next key definition from user input + * + * Describe key per `{descriptor}` or `[descriptor]`. + * Everything else will be interpreted as a single character as descriptor - e.g. `a`. + * Brackets `{` and `[` can be escaped by doubling - e.g. `foo[[bar` translates to `foo[bar`. + * A previously pressed key can be released per `{/descriptor}`. + * Keeping the key pressed can be written as `{descriptor>}`. + * When keeping the key pressed you can choose how long the key is pressed `{descriptor>3}`. + * You can then release the key per `{descriptor>3/}` or keep it pressed and continue with the next key. + */ function readNextDescriptor(text, context) { + let pos = 0; + const startBracket = text[pos] in bracketDict ? text[pos] : ''; + pos += startBracket.length; + const isEscapedChar = new RegExp(`^\\${startBracket}{2}`).test(text); + const type = isEscapedChar ? '' : startBracket; + return { + type, + ...type === '' ? readPrintableChar(text, pos, context) : readTag(text, pos, type, context) + }; +} +function readPrintableChar(text, pos, context) { + const descriptor = text[pos]; + assertDescriptor(descriptor, text, pos, context); + pos += descriptor.length; + return { + consumedLength: pos, + descriptor, + releasePrevious: false, + releaseSelf: true, + repeat: 1 + }; +} +function readTag(text, pos, startBracket, context) { + var _text_slice_match, _text_slice_match1; + const releasePreviousModifier = text[pos] === '/' ? '/' : ''; + pos += releasePreviousModifier.length; + const escapedDescriptor = startBracket === '{' && text[pos] === '\\'; + pos += Number(escapedDescriptor); + const descriptor = escapedDescriptor ? text[pos] : (_text_slice_match = text.slice(pos).match(startBracket === '{' ? /^\w+|^[^}>/]/ : /^\w+/)) === null || _text_slice_match === undefined ? undefined : _text_slice_match[0]; + assertDescriptor(descriptor, text, pos, context); + pos += descriptor.length; + var _text_slice_match_; + const repeatModifier = (_text_slice_match_ = (_text_slice_match1 = text.slice(pos).match(/^>\d+/)) === null || _text_slice_match1 === undefined ? undefined : _text_slice_match1[0]) !== null && _text_slice_match_ !== undefined ? _text_slice_match_ : ''; + pos += repeatModifier.length; + const releaseSelfModifier = text[pos] === '/' || !repeatModifier && text[pos] === '>' ? text[pos] : ''; + pos += releaseSelfModifier.length; + const expectedEndBracket = bracketDict[startBracket]; + const endBracket = text[pos] === expectedEndBracket ? expectedEndBracket : ''; + if (!endBracket) { + throw new Error(getErrorMessage([ + !repeatModifier && 'repeat modifier', + !releaseSelfModifier && 'release modifier', + `"${expectedEndBracket}"` + ].filter(Boolean).join(' or '), text[pos], text, context)); + } + pos += endBracket.length; + return { + consumedLength: pos, + descriptor, + releasePrevious: !!releasePreviousModifier, + repeat: repeatModifier ? Math.max(Number(repeatModifier.substr(1)), 1) : 1, + releaseSelf: hasReleaseSelf(releaseSelfModifier, repeatModifier) + }; +} +function assertDescriptor(descriptor, text, pos, context) { + if (!descriptor) { + throw new Error(getErrorMessage('key descriptor', text[pos], text, context)); + } +} +function hasReleaseSelf(releaseSelfModifier, repeatModifier) { + if (releaseSelfModifier) { + return releaseSelfModifier === '/'; + } + if (repeatModifier) { + return false; + } +} +function getErrorMessage(expected, found, text, context) { + return `Expected ${expected} but found "${found !== null && found !== undefined ? found : ''}" in "${text}" + See ${context === 'pointer' ? `https://testing-library.com/docs/user-event/pointer#pressing-a-button-or-touching-the-screen` : `https://testing-library.com/docs/user-event/keyboard`} + for more information about how userEvent parses your input.`; +} + +exports.readNextDescriptor = readNextDescriptor; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/cloneEvent.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/cloneEvent.js new file mode 100644 index 0000000000000000000000000000000000000000..a74b5cedb44ebbcfe7cdf7c657e69734f04899d1 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/cloneEvent.js @@ -0,0 +1,7 @@ +'use strict'; + +function cloneEvent(event) { + return new event.constructor(event.type, event); +} + +exports.cloneEvent = cloneEvent; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/findClosest.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/findClosest.js new file mode 100644 index 0000000000000000000000000000000000000000..83eab359be75ddf98ac1455cf0f15cb5d4bcef6b --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/findClosest.js @@ -0,0 +1,14 @@ +'use strict'; + +function findClosest(element, callback) { + let el = element; + do { + if (callback(el)) { + return el; + } + el = el.parentElement; + }while (el && el !== element.ownerDocument.body) + return undefined; +} + +exports.findClosest = findClosest; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/getDocumentFromNode.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/getDocumentFromNode.js new file mode 100644 index 0000000000000000000000000000000000000000..22d2bcc1250ef66023e4dea01714b8c6b537d841 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/getDocumentFromNode.js @@ -0,0 +1,10 @@ +'use strict'; + +function getDocumentFromNode(el) { + return isDocument(el) ? el : el.ownerDocument; +} +function isDocument(node) { + return node.nodeType === 9; +} + +exports.getDocumentFromNode = getDocumentFromNode; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/getTreeDiff.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/getTreeDiff.js new file mode 100644 index 0000000000000000000000000000000000000000..667e66a4fe80cb79bee55f673f7bca2cd07d60dc --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/getTreeDiff.js @@ -0,0 +1,25 @@ +'use strict'; + +function getTreeDiff(a, b) { + const treeA = []; + for(let el = a; el; el = el.parentElement){ + treeA.push(el); + } + const treeB = []; + for(let el = b; el; el = el.parentElement){ + treeB.push(el); + } + let i = 0; + for(;; i++){ + if (i >= treeA.length || i >= treeB.length || treeA[treeA.length - 1 - i] !== treeB[treeB.length - 1 - i]) { + break; + } + } + return [ + treeA.slice(0, treeA.length - i), + treeB.slice(0, treeB.length - i), + treeB.slice(treeB.length - i) + ]; +} + +exports.getTreeDiff = getTreeDiff; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/getWindow.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/getWindow.js new file mode 100644 index 0000000000000000000000000000000000000000..44945504ee672d2fae21a8b4611dc83648ecd2ce --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/getWindow.js @@ -0,0 +1,19 @@ +'use strict'; + +function getWindow(node) { + var _node_ownerDocument; + if (isDocument(node) && node.defaultView) { + return node.defaultView; + } else if ((_node_ownerDocument = node.ownerDocument) === null || _node_ownerDocument === undefined ? undefined : _node_ownerDocument.defaultView) { + return node.ownerDocument.defaultView; + } + throw new Error(`Could not determine window of node. Node was ${describe(node)}`); +} +function isDocument(node) { + return node.nodeType === 9; +} +function describe(val) { + return typeof val === 'function' ? `function ${val.name}` : val === null ? 'null' : String(val); +} + +exports.getWindow = getWindow; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/isDescendantOrSelf.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/isDescendantOrSelf.js new file mode 100644 index 0000000000000000000000000000000000000000..0bbf23dfd0bc5253507f17cc88984e4ee1eb6eb3 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/isDescendantOrSelf.js @@ -0,0 +1,14 @@ +'use strict'; + +function isDescendantOrSelf(potentialDescendant, potentialAncestor) { + let el = potentialDescendant; + do { + if (el === potentialAncestor) { + return true; + } + el = el.parentElement; + }while (el) + return false; +} + +exports.isDescendantOrSelf = isDescendantOrSelf; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/isDisabled.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/isDisabled.js new file mode 100644 index 0000000000000000000000000000000000000000..5d2a8658474eb6b66330f5f988ed929c5da78115 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/isDisabled.js @@ -0,0 +1,33 @@ +'use strict'; + +var isElementType = require('./isElementType.js'); + +// This should probably just rely on the :disabled pseudo-class, but JSDOM doesn't implement it properly. +function isDisabled(element) { + for(let el = element; el; el = el.parentElement){ + if (isElementType.isElementType(el, [ + 'button', + 'input', + 'select', + 'textarea', + 'optgroup', + 'option' + ])) { + if (el.hasAttribute('disabled')) { + return true; + } + } else if (isElementType.isElementType(el, 'fieldset')) { + var _el_querySelector; + if (el.hasAttribute('disabled') && !((_el_querySelector = el.querySelector(':scope > legend')) === null || _el_querySelector === undefined ? undefined : _el_querySelector.contains(element))) { + return true; + } + } else if (el.tagName.includes('-')) { + if (el.constructor.formAssociated && el.hasAttribute('disabled')) { + return true; + } + } + } + return false; +} + +exports.isDisabled = isDisabled; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/isElementType.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/isElementType.js new file mode 100644 index 0000000000000000000000000000000000000000..2790a0ae56bdd008ff4f18b54aeb164184a92b67 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/isElementType.js @@ -0,0 +1,20 @@ +'use strict'; + +function isElementType(element, tag, props) { + if (element.namespaceURI && element.namespaceURI !== 'http://www.w3.org/1999/xhtml') { + return false; + } + tag = Array.isArray(tag) ? tag : [ + tag + ]; + // tagName is uppercase in HTMLDocument and lowercase in XMLDocument + if (!tag.includes(element.tagName.toLowerCase())) { + return false; + } + if (props) { + return Object.entries(props).every(([k, v])=>element[k] === v); + } + return true; +} + +exports.isElementType = isElementType; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/isVisible.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/isVisible.js new file mode 100644 index 0000000000000000000000000000000000000000..4aef16792aa89da744173321ee9b520608d75aff --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/isVisible.js @@ -0,0 +1,19 @@ +'use strict'; + +var getWindow = require('./getWindow.js'); + +function isVisible(element) { + const window = getWindow.getWindow(element); + for(let el = element; el === null || el === undefined ? undefined : el.ownerDocument; el = el.parentElement){ + const { display, visibility } = window.getComputedStyle(el); + if (display === 'none') { + return false; + } + if (visibility === 'hidden') { + return false; + } + } + return true; +} + +exports.isVisible = isVisible; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/level.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/level.js new file mode 100644 index 0000000000000000000000000000000000000000..4564d85e7efb9193c1e3fd5d1b4c731eaa52d330 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/level.js @@ -0,0 +1,17 @@ +'use strict'; + +var ApiLevel = /*#__PURE__*/ function(ApiLevel) { + ApiLevel[ApiLevel["Trigger"] = 2] = "Trigger"; + ApiLevel[ApiLevel["Call"] = 1] = "Call"; + return ApiLevel; +}({}); +function setLevelRef(instance, level) { + instance.levelRefs[level] = {}; +} +function getLevelRef(instance, level) { + return instance.levelRefs[level]; +} + +exports.ApiLevel = ApiLevel; +exports.getLevelRef = getLevelRef; +exports.setLevelRef = setLevelRef; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/wait.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/wait.js new file mode 100644 index 0000000000000000000000000000000000000000..c4acc2f8cbce271821ca0657eca04ae35ccfcfe9 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/misc/wait.js @@ -0,0 +1,14 @@ +'use strict'; + +function wait(config) { + const delay = config.delay; + if (typeof delay !== 'number') { + return; + } + return Promise.all([ + new Promise((resolve)=>globalThis.setTimeout(()=>resolve(), delay)), + config.advanceTimers(delay) + ]); +} + +exports.wait = wait; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/pointer/cssPointerEvents.js b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/pointer/cssPointerEvents.js new file mode 100644 index 0000000000000000000000000000000000000000..cbc4842f39e1dc571cf1246a1657a85286331b51 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/cjs/utils/pointer/cssPointerEvents.js @@ -0,0 +1,103 @@ +'use strict'; + +var options = require('../../options.js'); +var getWindow = require('../misc/getWindow.js'); +var isElementType = require('../misc/isElementType.js'); +var level = require('../misc/level.js'); + +function hasPointerEvents(instance, element) { + var _checkPointerEvents; + return ((_checkPointerEvents = checkPointerEvents(instance, element)) === null || _checkPointerEvents === undefined ? undefined : _checkPointerEvents.pointerEvents) !== 'none'; +} +function closestPointerEventsDeclaration(element) { + const window = getWindow.getWindow(element); + for(let el = element, tree = []; el === null || el === undefined ? undefined : el.ownerDocument; el = el.parentElement){ + tree.push(el); + const pointerEvents = window.getComputedStyle(el).pointerEvents; + if (pointerEvents && ![ + 'inherit', + 'unset' + ].includes(pointerEvents)) { + return { + pointerEvents, + tree + }; + } + } + return undefined; +} +const PointerEventsCheck = Symbol('Last check for pointer-events'); +function checkPointerEvents(instance, element) { + const lastCheck = element[PointerEventsCheck]; + const needsCheck = instance.config.pointerEventsCheck !== options.PointerEventsCheckLevel.Never && (!lastCheck || hasBitFlag(instance.config.pointerEventsCheck, options.PointerEventsCheckLevel.EachApiCall) && lastCheck[level.ApiLevel.Call] !== level.getLevelRef(instance, level.ApiLevel.Call) || hasBitFlag(instance.config.pointerEventsCheck, options.PointerEventsCheckLevel.EachTrigger) && lastCheck[level.ApiLevel.Trigger] !== level.getLevelRef(instance, level.ApiLevel.Trigger)); + if (!needsCheck) { + return lastCheck === null || lastCheck === undefined ? undefined : lastCheck.result; + } + const declaration = closestPointerEventsDeclaration(element); + element[PointerEventsCheck] = { + [level.ApiLevel.Call]: level.getLevelRef(instance, level.ApiLevel.Call), + [level.ApiLevel.Trigger]: level.getLevelRef(instance, level.ApiLevel.Trigger), + result: declaration + }; + return declaration; +} +function assertPointerEvents(instance, element) { + const declaration = checkPointerEvents(instance, element); + if ((declaration === null || declaration === undefined ? undefined : declaration.pointerEvents) === 'none') { + throw new Error([ + `Unable to perform pointer interaction as the element ${declaration.tree.length > 1 ? 'inherits' : 'has'} \`pointer-events: none\`:`, + '', + printTree(declaration.tree) + ].join('\n')); + } +} +function printTree(tree) { + return tree.reverse().map((el, i)=>[ + ''.padEnd(i), + el.tagName, + el.id && `#${el.id}`, + el.hasAttribute('data-testid') && `(testId=${el.getAttribute('data-testid')})`, + getLabelDescr(el), + tree.length > 1 && i === 0 && ' <-- This element declared `pointer-events: none`', + tree.length > 1 && i === tree.length - 1 && ' <-- Asserted pointer events here' + ].filter(Boolean).join('')).join('\n'); +} +function getLabelDescr(element) { + var _element_labels; + let label; + if (element.hasAttribute('aria-label')) { + label = element.getAttribute('aria-label'); + } else if (element.hasAttribute('aria-labelledby')) { + var _element_ownerDocument_getElementById_textContent, _element_ownerDocument_getElementById; + label = (_element_ownerDocument_getElementById = element.ownerDocument.getElementById(element.getAttribute('aria-labelledby'))) === null || _element_ownerDocument_getElementById === undefined ? undefined : (_element_ownerDocument_getElementById_textContent = _element_ownerDocument_getElementById.textContent) === null || _element_ownerDocument_getElementById_textContent === undefined ? undefined : _element_ownerDocument_getElementById_textContent.trim(); + } else if (isElementType.isElementType(element, [ + 'button', + 'input', + 'meter', + 'output', + 'progress', + 'select', + 'textarea' + ]) && ((_element_labels = element.labels) === null || _element_labels === undefined ? undefined : _element_labels.length)) { + label = Array.from(element.labels).map((el)=>{ + var _el_textContent; + return (_el_textContent = el.textContent) === null || _el_textContent === undefined ? undefined : _el_textContent.trim(); + }).join('|'); + } else if (isElementType.isElementType(element, 'button')) { + var _element_textContent; + label = (_element_textContent = element.textContent) === null || _element_textContent === undefined ? undefined : _element_textContent.trim(); + } + label = label === null || label === undefined ? undefined : label.replace(/\n/g, ' '); + if (Number(label === null || label === undefined ? undefined : label.length) > 30) { + label = `${label === null || label === undefined ? undefined : label.substring(0, 29)}…`; + } + return label ? `(label=${label})` : ''; +} +// With the eslint rule and prettier the bitwise operation isn't nice to read +function hasBitFlag(conf, flag) { + // eslint-disable-next-line no-bitwise + return (conf & flag) > 0; +} + +exports.assertPointerEvents = assertPointerEvents; +exports.hasPointerEvents = hasPointerEvents; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/clipboard/copy.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/clipboard/copy.js new file mode 100644 index 0000000000000000000000000000000000000000..fca41cdcc9f52ae382672c5dbe0f150eadfcf3cb --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/clipboard/copy.js @@ -0,0 +1,20 @@ +import { writeDataTransferToClipboard } from '../utils/dataTransfer/Clipboard.js'; +import { copySelection } from '../document/copySelection.js'; + +async function copy() { + const doc = this.config.document; + var _doc_activeElement; + const target = (_doc_activeElement = doc.activeElement) !== null && _doc_activeElement !== undefined ? _doc_activeElement : /* istanbul ignore next */ doc.body; + const clipboardData = copySelection(target); + if (clipboardData.items.length === 0) { + return; + } + if (this.dispatchUIEvent(target, 'copy', { + clipboardData + }) && this.config.writeToClipboard) { + await writeDataTransferToClipboard(doc, clipboardData); + } + return clipboardData; +} + +export { copy }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/clipboard/cut.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/clipboard/cut.js new file mode 100644 index 0000000000000000000000000000000000000000..b3870db9d0f3564e19a9790dc4a38d1eaf76a03f --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/clipboard/cut.js @@ -0,0 +1,20 @@ +import { writeDataTransferToClipboard } from '../utils/dataTransfer/Clipboard.js'; +import { copySelection } from '../document/copySelection.js'; + +async function cut() { + const doc = this.config.document; + var _doc_activeElement; + const target = (_doc_activeElement = doc.activeElement) !== null && _doc_activeElement !== undefined ? _doc_activeElement : /* istanbul ignore next */ doc.body; + const clipboardData = copySelection(target); + if (clipboardData.items.length === 0) { + return; + } + if (this.dispatchUIEvent(target, 'cut', { + clipboardData + }) && this.config.writeToClipboard) { + await writeDataTransferToClipboard(target.ownerDocument, clipboardData); + } + return clipboardData; +} + +export { cut }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/clipboard/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/clipboard/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6785994fa17dc107f9a8c7725d5df928b9165b4c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/clipboard/index.js @@ -0,0 +1,3 @@ +export { copy } from './copy.js'; +export { cut } from './cut.js'; +export { paste } from './paste.js'; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/clipboard/paste.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/clipboard/paste.js new file mode 100644 index 0000000000000000000000000000000000000000..df710a54751cedc6b4208bf8a098e4192e00006f --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/clipboard/paste.js @@ -0,0 +1,23 @@ +import { createDataTransfer } from '../utils/dataTransfer/DataTransfer.js'; +import { readDataTransferFromClipboard } from '../utils/dataTransfer/Clipboard.js'; +import { getWindow } from '../utils/misc/getWindow.js'; + +async function paste(clipboardData) { + const doc = this.config.document; + var _doc_activeElement; + const target = (_doc_activeElement = doc.activeElement) !== null && _doc_activeElement !== undefined ? _doc_activeElement : /* istanbul ignore next */ doc.body; + var _ref; + const dataTransfer = (_ref = typeof clipboardData === 'string' ? getClipboardDataFromString(doc, clipboardData) : clipboardData) !== null && _ref !== undefined ? _ref : await readDataTransferFromClipboard(doc).catch(()=>{ + throw new Error('`userEvent.paste()` without `clipboardData` requires the `ClipboardAPI` to be available.'); + }); + this.dispatchUIEvent(target, 'paste', { + clipboardData: dataTransfer + }); +} +function getClipboardDataFromString(doc, text) { + const dt = createDataTransfer(getWindow(doc)); + dt.setData('text', text); + return dt; +} + +export { paste }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/convenience/click.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/convenience/click.js new file mode 100644 index 0000000000000000000000000000000000000000..322e672dc16295b3ac7470cec70fdad6545aa7e1 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/convenience/click.js @@ -0,0 +1,31 @@ +async function click(element) { + const pointerIn = []; + if (!this.config.skipHover) { + pointerIn.push({ + target: element + }); + } + pointerIn.push({ + keys: '[MouseLeft]', + target: element + }); + return this.pointer(pointerIn); +} +async function dblClick(element) { + return this.pointer([ + { + target: element + }, + '[MouseLeft][MouseLeft]' + ]); +} +async function tripleClick(element) { + return this.pointer([ + { + target: element + }, + '[MouseLeft][MouseLeft][MouseLeft]' + ]); +} + +export { click, dblClick, tripleClick }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/convenience/hover.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/convenience/hover.js new file mode 100644 index 0000000000000000000000000000000000000000..0e3abb98639177bdfa4f5f0ab16f27c2714604d3 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/convenience/hover.js @@ -0,0 +1,16 @@ +import '../utils/dataTransfer/Clipboard.js'; +import { assertPointerEvents } from '../utils/pointer/cssPointerEvents.js'; + +async function hover(element) { + return this.pointer({ + target: element + }); +} +async function unhover(element) { + assertPointerEvents(this, this.system.pointer.getMouseTarget(this)); + return this.pointer({ + target: element.ownerDocument.body + }); +} + +export { hover, unhover }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/convenience/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/convenience/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e91fcd93e7bfc10179a86683dcdd6045b49ea4fb --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/convenience/index.js @@ -0,0 +1,3 @@ +export { click, dblClick, tripleClick } from './click.js'; +export { hover, unhover } from './hover.js'; +export { tab } from './tab.js'; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/convenience/tab.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/convenience/tab.js new file mode 100644 index 0000000000000000000000000000000000000000..248552b04840dfb11a75e8a19b79d745c9b895fc --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/convenience/tab.js @@ -0,0 +1,5 @@ +async function tab({ shift } = {}) { + return this.keyboard(shift === true ? '{Shift>}{Tab}{/Shift}' : shift === false ? '[/ShiftLeft][/ShiftRight]{Tab}' : '{Tab}'); +} + +export { tab }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/UI.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/UI.js new file mode 100644 index 0000000000000000000000000000000000000000..3ff73cf39598f9d3f19360c58c02b7e8ef5091e4 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/UI.js @@ -0,0 +1,79 @@ +const UIValue = Symbol('Displayed value in UI'); +const UISelection = Symbol('Displayed selection in UI'); +const InitialValue = Symbol('Initial value to compare on blur'); +function isUIValue(value) { + return typeof value === 'object' && UIValue in value; +} +function isUISelectionStart(start) { + return !!start && typeof start === 'object' && UISelection in start; +} +function setUIValue(element, value) { + if (element[InitialValue] === undefined) { + element[InitialValue] = element.value; + } + element[UIValue] = value; + // eslint-disable-next-line no-new-wrappers + element.value = Object.assign(new String(value), { + [UIValue]: true + }); +} +function getUIValue(element) { + return element[UIValue] === undefined ? element.value : String(element[UIValue]); +} +/** Flag the IDL value as clean. This does not change the value.*/ function setUIValueClean(element) { + element[UIValue] = undefined; +} +function clearInitialValue(element) { + element[InitialValue] = undefined; +} +function getInitialValue(element) { + return element[InitialValue]; +} +function setUISelectionRaw(element, selection) { + element[UISelection] = selection; +} +function setUISelection(element, { focusOffset: focusOffsetParam, anchorOffset: anchorOffsetParam = focusOffsetParam }, mode = 'replace') { + const valueLength = getUIValue(element).length; + const sanitizeOffset = (o)=>Math.max(0, Math.min(valueLength, o)); + const anchorOffset = mode === 'replace' || element[UISelection] === undefined ? sanitizeOffset(anchorOffsetParam) : element[UISelection].anchorOffset; + const focusOffset = sanitizeOffset(focusOffsetParam); + const startOffset = Math.min(anchorOffset, focusOffset); + const endOffset = Math.max(anchorOffset, focusOffset); + element[UISelection] = { + anchorOffset, + focusOffset + }; + if (element.selectionStart === startOffset && element.selectionEnd === endOffset) { + return; + } + // eslint-disable-next-line no-new-wrappers + const startObj = Object.assign(new Number(startOffset), { + [UISelection]: true + }); + try { + element.setSelectionRange(startObj, endOffset); + } catch { + // DOMException for invalid state is expected when calling this + // on an element without support for setSelectionRange + } +} +function getUISelection(element) { + var _element_selectionStart, _element_selectionEnd, _element_UISelection; + const sel = (_element_UISelection = element[UISelection]) !== null && _element_UISelection !== undefined ? _element_UISelection : { + anchorOffset: (_element_selectionStart = element.selectionStart) !== null && _element_selectionStart !== undefined ? _element_selectionStart : 0, + focusOffset: (_element_selectionEnd = element.selectionEnd) !== null && _element_selectionEnd !== undefined ? _element_selectionEnd : 0 + }; + return { + ...sel, + startOffset: Math.min(sel.anchorOffset, sel.focusOffset), + endOffset: Math.max(sel.anchorOffset, sel.focusOffset) + }; +} +function hasUISelection(element) { + return !!element[UISelection]; +} +/** Flag the IDL selection as clean. This does not change the selection. */ function setUISelectionClean(element) { + element[UISelection] = undefined; +} + +export { clearInitialValue, getInitialValue, getUISelection, getUIValue, hasUISelection, isUISelectionStart, isUIValue, setUISelection, setUISelectionClean, setUISelectionRaw, setUIValue, setUIValueClean }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/copySelection.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/copySelection.js new file mode 100644 index 0000000000000000000000000000000000000000..5414dad608ca48205dd13e1f514b66c76ce44c02 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/copySelection.js @@ -0,0 +1,27 @@ +import { createDataTransfer } from '../utils/dataTransfer/DataTransfer.js'; +import '../utils/dataTransfer/Clipboard.js'; +import { getWindow } from '../utils/misc/getWindow.js'; +import { hasOwnSelection } from '../utils/focus/selection.js'; +import { getUISelection, getUIValue } from './UI.js'; + +function copySelection(target) { + const data = hasOwnSelection(target) ? { + 'text/plain': readSelectedValueFromInput(target) + } : { + 'text/plain': String(target.ownerDocument.getSelection()) + }; + const dt = createDataTransfer(getWindow(target)); + for(const type in data){ + if (data[type]) { + dt.setData(type, data[type]); + } + } + return dt; +} +function readSelectedValueFromInput(target) { + const sel = getUISelection(target); + const val = getUIValue(target); + return val.substring(sel.startOffset, sel.endOffset); +} + +export { copySelection }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/getValueOrTextContent.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/getValueOrTextContent.js new file mode 100644 index 0000000000000000000000000000000000000000..be5a402947c109cc1d0f712d7452faf543eca2b6 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/getValueOrTextContent.js @@ -0,0 +1,16 @@ +import '../utils/dataTransfer/Clipboard.js'; +import { isContentEditable } from '../utils/edit/isContentEditable.js'; +import { getUIValue } from './UI.js'; + +function getValueOrTextContent(element) { + // istanbul ignore if + if (!element) { + return null; + } + if (isContentEditable(element)) { + return element.textContent; + } + return getUIValue(element); +} + +export { getValueOrTextContent }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c306500430453b9441fd50b42fad6bfa45b71d7b --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/index.js @@ -0,0 +1,4 @@ +export { clearInitialValue, getUISelection, getUIValue, setUISelection, setUIValue } from './UI.js'; +export { getValueOrTextContent } from './getValueOrTextContent.js'; +export { copySelection } from './copySelection.js'; +export { commitValueAfterInput } from './trackValue.js'; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/interceptor.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/interceptor.js new file mode 100644 index 0000000000000000000000000000000000000000..e5d12e18e78a97a19558e24b69b57b0eb79a9791 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/interceptor.js @@ -0,0 +1,99 @@ +import { isElementType } from '../utils/misc/isElementType.js'; +import '../utils/dataTransfer/Clipboard.js'; +import { startTrackValue, trackOrSetValue } from './trackValue.js'; +import { setUISelectionClean, setUISelectionRaw, getUIValue, setUIValueClean, isUIValue, isUISelectionStart } from './UI.js'; + +const Interceptor = Symbol('Interceptor for programmatical calls'); +function prepareInterceptor(element, propName, interceptorImpl) { + const prototypeDescriptor = Object.getOwnPropertyDescriptor(element.constructor.prototype, propName); + const objectDescriptor = Object.getOwnPropertyDescriptor(element, propName); + const target = (prototypeDescriptor === null || prototypeDescriptor === undefined ? undefined : prototypeDescriptor.set) ? 'set' : 'value'; + /* istanbul ignore if */ if (typeof (prototypeDescriptor === null || prototypeDescriptor === undefined ? undefined : prototypeDescriptor[target]) !== 'function' || prototypeDescriptor[target][Interceptor]) { + throw new Error(`Element ${element.tagName} does not implement "${String(propName)}".`); + } + function intercept(...args) { + const { applyNative = false, realArgs, then } = interceptorImpl.call(this, ...args); + const realFunc = (!applyNative && objectDescriptor || prototypeDescriptor)[target]; + if (target === 'set') { + realFunc.call(this, realArgs); + } else { + realFunc.call(this, ...realArgs); + } + then === null || then === undefined ? undefined : then(); + } + intercept[Interceptor] = Interceptor; + Object.defineProperty(element, propName, { + ...objectDescriptor !== null && objectDescriptor !== undefined ? objectDescriptor : prototypeDescriptor, + [target]: intercept + }); +} +function prepareValueInterceptor(element) { + prepareInterceptor(element, 'value', function interceptorImpl(v) { + const isUI = isUIValue(v); + if (isUI) { + startTrackValue(this); + } + return { + applyNative: !!isUI, + realArgs: sanitizeValue(this, v), + then: isUI ? undefined : ()=>trackOrSetValue(this, String(v)) + }; + }); +} +function sanitizeValue(element, v) { + // Workaround for JSDOM + if (isElementType(element, 'input', { + type: 'number' + }) && String(v) !== '' && !Number.isNaN(Number(v))) { + // Setting value to "1." results in `null` in JSDOM + return String(Number(v)); + } + return String(v); +} +function prepareSelectionInterceptor(element) { + prepareInterceptor(element, 'setSelectionRange', function interceptorImpl(start, ...others) { + const isUI = isUISelectionStart(start); + return { + applyNative: !!isUI, + realArgs: [ + Number(start), + ...others + ], + then: ()=>isUI ? undefined : setUISelectionClean(element) + }; + }); + prepareInterceptor(element, 'selectionStart', function interceptorImpl(v) { + return { + realArgs: v, + then: ()=>setUISelectionClean(element) + }; + }); + prepareInterceptor(element, 'selectionEnd', function interceptorImpl(v) { + return { + realArgs: v, + then: ()=>setUISelectionClean(element) + }; + }); + prepareInterceptor(element, 'select', function interceptorImpl() { + return { + realArgs: [], + then: ()=>setUISelectionRaw(element, { + anchorOffset: 0, + focusOffset: getUIValue(element).length + }) + }; + }); +} +function prepareRangeTextInterceptor(element) { + prepareInterceptor(element, 'setRangeText', function interceptorImpl(...realArgs) { + return { + realArgs, + then: ()=>{ + setUIValueClean(element); + setUISelectionClean(element); + } + }; + }); +} + +export { prepareInterceptor, prepareRangeTextInterceptor, prepareSelectionInterceptor, prepareValueInterceptor }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/patchFocus.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/patchFocus.js new file mode 100644 index 0000000000000000000000000000000000000000..be6bfb0bf406dd033046b1cc5c297c7a60b78f69 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/patchFocus.js @@ -0,0 +1,101 @@ +import { dispatchDOMEvent } from '../event/dispatchEvent.js'; +import '../utils/dataTransfer/Clipboard.js'; +import { getActiveElement } from '../utils/focus/getActiveElement.js'; +import '@testing-library/dom'; + +const patched = Symbol('patched focus/blur methods'); +function patchFocus(HTMLElement) { + if (HTMLElement.prototype[patched]) { + return; + } + // eslint-disable-next-line @typescript-eslint/unbound-method + const { focus, blur } = HTMLElement.prototype; + Object.defineProperties(HTMLElement.prototype, { + focus: { + configurable: true, + get: ()=>patchedFocus + }, + blur: { + configurable: true, + get: ()=>patchedBlur + }, + [patched]: { + configurable: true, + get: ()=>({ + focus, + blur + }) + } + }); + let activeCall; + function patchedFocus(options) { + if (this.ownerDocument.visibilityState !== 'hidden') { + return focus.call(this, options); + } + const blurred = getActiveTarget(this.ownerDocument); + if (blurred === this) { + return; + } + const thisCall = Symbol('focus call'); + activeCall = thisCall; + if (blurred) { + blur.call(blurred); + dispatchDOMEvent(blurred, 'blur', { + relatedTarget: this + }); + dispatchDOMEvent(blurred, 'focusout', { + relatedTarget: activeCall === thisCall ? this : null + }); + } + if (activeCall === thisCall) { + focus.call(this, options); + dispatchDOMEvent(this, 'focus', { + relatedTarget: blurred + }); + } + if (activeCall === thisCall) { + dispatchDOMEvent(this, 'focusin', { + relatedTarget: blurred + }); + } + } + function patchedBlur() { + if (this.ownerDocument.visibilityState !== 'hidden') { + return blur.call(this); + } + const blurred = getActiveTarget(this.ownerDocument); + if (blurred !== this) { + return; + } + const thisCall = Symbol('blur call'); + activeCall = thisCall; + blur.call(this); + dispatchDOMEvent(blurred, 'blur', { + relatedTarget: null + }); + dispatchDOMEvent(blurred, 'focusout', { + relatedTarget: null + }); + } +} +function getActiveTarget(document) { + const active = getActiveElement(document); + return (active === null || active === undefined ? undefined : active.tagName) === 'BODY' ? null : active; +} +function restoreFocus(HTMLElement) { + if (HTMLElement.prototype[patched]) { + const { focus, blur } = HTMLElement.prototype[patched]; + Object.defineProperties(HTMLElement.prototype, { + focus: { + configurable: true, + get: ()=>focus + }, + blur: { + configurable: true, + get: ()=>blur + } + }); + } +} + +export { patchFocus, restoreFocus }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/prepareDocument.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/prepareDocument.js new file mode 100644 index 0000000000000000000000000000000000000000..e1c0fcc77e638e43526f0a9452355932d0d6b05b --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/prepareDocument.js @@ -0,0 +1,56 @@ +import { dispatchDOMEvent } from '../event/dispatchEvent.js'; +import { isElementType } from '../utils/misc/isElementType.js'; +import '../utils/dataTransfer/Clipboard.js'; +import { getInitialValue, clearInitialValue } from './UI.js'; +import '@testing-library/dom'; +import { prepareValueInterceptor, prepareSelectionInterceptor, prepareRangeTextInterceptor } from './interceptor.js'; + +const isPrepared = Symbol('Node prepared with document state workarounds'); +function prepareDocument(document) { + if (document[isPrepared]) { + return; + } + document.addEventListener('focus', (e)=>{ + const el = e.target; + prepareElement(el); + }, { + capture: true, + passive: true + }); + // Our test environment defaults to `document.body` as `activeElement`. + // In other environments this might be `null` when preparing. + // istanbul ignore else + if (document.activeElement) { + prepareElement(document.activeElement); + } + document.addEventListener('blur', (e)=>{ + const el = e.target; + const initialValue = getInitialValue(el); + if (initialValue !== undefined) { + if (el.value !== initialValue) { + dispatchDOMEvent(el, 'change'); + } + clearInitialValue(el); + } + }, { + capture: true, + passive: true + }); + document[isPrepared] = isPrepared; +} +function prepareElement(el) { + if (el[isPrepared]) { + return; + } + if (isElementType(el, [ + 'input', + 'textarea' + ])) { + prepareValueInterceptor(el); + prepareSelectionInterceptor(el); + prepareRangeTextInterceptor(el); + } + el[isPrepared] = isPrepared; +} + +export { prepareDocument }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/trackValue.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/trackValue.js new file mode 100644 index 0000000000000000000000000000000000000000..3fe12e541bf894b1f1946db05c98b49535ba31bc --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/document/trackValue.js @@ -0,0 +1,53 @@ +import '../utils/dataTransfer/Clipboard.js'; +import { getWindow } from '../utils/misc/getWindow.js'; +import { setUIValueClean, setUISelection, hasUISelection } from './UI.js'; + +const TrackChanges = Symbol('Track programmatic changes for React workaround'); +// When the input event happens in the browser, React executes all event handlers +// and if they change state of a controlled value, nothing happens. +// But when we trigger the event handlers in test environment with React@17, +// the changes are rolled back before the state update is applied. +// This results in a reset cursor. +// There might be a better way to work around if we figure out +// why the batched update is executed differently in our test environment. +function isReact17Element(element) { + return Object.getOwnPropertyNames(element).some((k)=>k.startsWith('__react')) && getWindow(element).REACT_VERSION === 17; +} +function startTrackValue(element) { + if (!isReact17Element(element)) { + return; + } + element[TrackChanges] = { + previousValue: String(element.value), + tracked: [] + }; +} +function trackOrSetValue(element, v) { + var _element_TrackChanges_tracked, _element_TrackChanges; + (_element_TrackChanges = element[TrackChanges]) === null || _element_TrackChanges === undefined ? undefined : (_element_TrackChanges_tracked = _element_TrackChanges.tracked) === null || _element_TrackChanges_tracked === undefined ? undefined : _element_TrackChanges_tracked.push(v); + if (!element[TrackChanges]) { + setUIValueClean(element); + setUISelection(element, { + focusOffset: v.length + }); + } +} +function commitValueAfterInput(element, cursorOffset) { + var _changes_tracked; + const changes = element[TrackChanges]; + element[TrackChanges] = undefined; + if (!(changes === null || changes === undefined ? undefined : (_changes_tracked = changes.tracked) === null || _changes_tracked === undefined ? undefined : _changes_tracked.length)) { + return; + } + const isJustReactStateUpdate = changes.tracked.length === 2 && changes.tracked[0] === changes.previousValue && changes.tracked[1] === element.value; + if (!isJustReactStateUpdate) { + setUIValueClean(element); + } + if (hasUISelection(element)) { + setUISelection(element, { + focusOffset: isJustReactStateUpdate ? cursorOffset : element.value.length + }); + } +} + +export { commitValueAfterInput, startTrackValue, trackOrSetValue }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/click.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/click.js new file mode 100644 index 0000000000000000000000000000000000000000..5dbc76db6f4f4c7398975d634d8e6752e6b754c7 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/click.js @@ -0,0 +1,30 @@ +import { isElementType } from '../../utils/misc/isElementType.js'; +import '../../utils/dataTransfer/Clipboard.js'; +import { getWindow } from '../../utils/misc/getWindow.js'; +import { isFocusable } from '../../utils/focus/isFocusable.js'; +import { cloneEvent } from '../../utils/misc/cloneEvent.js'; +import { focusElement, blurElement } from '../focus.js'; +import { behavior } from './registry.js'; + +behavior.click = (event, target, instance)=>{ + const context = target.closest('button,input,label,select,textarea'); + const control = context && isElementType(context, 'label') && context.control; + if (control && control !== target) { + return ()=>{ + if (isFocusable(control)) { + focusElement(control); + instance.dispatchEvent(control, cloneEvent(event)); + } + }; + } else if (isElementType(target, 'input', { + type: 'file' + })) { + return ()=>{ + // blur fires when the file selector pops up + blurElement(target); + target.dispatchEvent(new (getWindow(target)).Event('fileDialog')); + // focus fires after the file selector has been closed + focusElement(target); + }; + } +}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/cut.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/cut.js new file mode 100644 index 0000000000000000000000000000000000000000..ff8a956b00654be0122036ed683fe0b290efd933 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/cut.js @@ -0,0 +1,12 @@ +import '../../utils/dataTransfer/Clipboard.js'; +import { isEditable } from '../../utils/edit/isEditable.js'; +import { input } from '../input.js'; +import { behavior } from './registry.js'; + +behavior.cut = (event, target, instance)=>{ + return ()=>{ + if (isEditable(target)) { + input(instance, target, '', 'deleteByCut'); + } + }; +}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3d9c54cd637763e1695b375b7034286c43787313 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/index.js @@ -0,0 +1,7 @@ +import './click.js'; +import './cut.js'; +import './keydown.js'; +import './keypress.js'; +import './keyup.js'; +import './paste.js'; +export { behavior } from './registry.js'; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/keydown.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/keydown.js new file mode 100644 index 0000000000000000000000000000000000000000..a4ff94227607693f08b854498973d6b7cee094f4 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/keydown.js @@ -0,0 +1,126 @@ +import { getUIValue, setUISelection } from '../../document/UI.js'; +import { getValueOrTextContent } from '../../document/getValueOrTextContent.js'; +import { isElementType } from '../../utils/misc/isElementType.js'; +import '../../utils/dataTransfer/Clipboard.js'; +import { isContentEditable } from '../../utils/edit/isContentEditable.js'; +import { isEditable } from '../../utils/edit/isEditable.js'; +import { getTabDestination } from '../../utils/focus/getTabDestination.js'; +import { hasOwnSelection } from '../../utils/focus/selection.js'; +import { focusElement } from '../focus.js'; +import { input } from '../input.js'; +import { moveSelection } from '../selection/moveSelection.js'; +import { selectAll } from '../selection/selectAll.js'; +import { setSelectionRange } from '../selection/setSelectionRange.js'; +import { walkRadio } from '../radio.js'; +import { behavior } from './registry.js'; + +behavior.keydown = (event, target, instance)=>{ + var _keydownBehavior_event_key; + var _keydownBehavior_event_key1; + return (_keydownBehavior_event_key1 = (_keydownBehavior_event_key = keydownBehavior[event.key]) === null || _keydownBehavior_event_key === undefined ? undefined : _keydownBehavior_event_key.call(keydownBehavior, event, target, instance)) !== null && _keydownBehavior_event_key1 !== undefined ? _keydownBehavior_event_key1 : combinationBehavior(event, target, instance); +}; +const keydownBehavior = { + ArrowDown: (event, target, instance)=>{ + /* istanbul ignore else */ if (isElementType(target, 'input', { + type: 'radio' + })) { + return ()=>walkRadio(instance, target, 1); + } + }, + ArrowLeft: (event, target, instance)=>{ + if (isElementType(target, 'input', { + type: 'radio' + })) { + return ()=>walkRadio(instance, target, -1); + } + return ()=>moveSelection(target, -1); + }, + ArrowRight: (event, target, instance)=>{ + if (isElementType(target, 'input', { + type: 'radio' + })) { + return ()=>walkRadio(instance, target, 1); + } + return ()=>moveSelection(target, 1); + }, + ArrowUp: (event, target, instance)=>{ + /* istanbul ignore else */ if (isElementType(target, 'input', { + type: 'radio' + })) { + return ()=>walkRadio(instance, target, -1); + } + }, + Backspace: (event, target, instance)=>{ + if (isEditable(target)) { + return ()=>{ + input(instance, target, '', 'deleteContentBackward'); + }; + } + }, + Delete: (event, target, instance)=>{ + if (isEditable(target)) { + return ()=>{ + input(instance, target, '', 'deleteContentForward'); + }; + } + }, + End: (event, target)=>{ + if (isElementType(target, [ + 'input', + 'textarea' + ]) || isContentEditable(target)) { + return ()=>{ + var _getValueOrTextContent; + var _getValueOrTextContent_length; + const newPos = (_getValueOrTextContent_length = (_getValueOrTextContent = getValueOrTextContent(target)) === null || _getValueOrTextContent === undefined ? undefined : _getValueOrTextContent.length) !== null && _getValueOrTextContent_length !== undefined ? _getValueOrTextContent_length : /* istanbul ignore next */ 0; + setSelectionRange(target, newPos, newPos); + }; + } + }, + Home: (event, target)=>{ + if (isElementType(target, [ + 'input', + 'textarea' + ]) || isContentEditable(target)) { + return ()=>{ + setSelectionRange(target, 0, 0); + }; + } + }, + PageDown: (event, target)=>{ + if (isElementType(target, [ + 'input' + ])) { + return ()=>{ + const newPos = getUIValue(target).length; + setSelectionRange(target, newPos, newPos); + }; + } + }, + PageUp: (event, target)=>{ + if (isElementType(target, [ + 'input' + ])) { + return ()=>{ + setSelectionRange(target, 0, 0); + }; + } + }, + Tab: (event, target, instance)=>{ + return ()=>{ + const dest = getTabDestination(target, instance.system.keyboard.modifiers.Shift); + focusElement(dest); + if (hasOwnSelection(dest)) { + setUISelection(dest, { + anchorOffset: 0, + focusOffset: dest.value.length + }); + } + }; + } +}; +const combinationBehavior = (event, target, instance)=>{ + if (event.code === 'KeyA' && instance.system.keyboard.modifiers.Control) { + return ()=>selectAll(target); + } +}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/keypress.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/keypress.js new file mode 100644 index 0000000000000000000000000000000000000000..17dcdf0998f96c1d4277c95f85e1999eb62bae08 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/keypress.js @@ -0,0 +1,49 @@ +import { isElementType } from '../../utils/misc/isElementType.js'; +import '../../utils/dataTransfer/Clipboard.js'; +import { isContentEditable } from '../../utils/edit/isContentEditable.js'; +import { isEditable } from '../../utils/edit/isEditable.js'; +import { input } from '../input.js'; +import { behavior } from './registry.js'; + +behavior.keypress = (event, target, instance)=>{ + if (event.key === 'Enter') { + if (isElementType(target, 'button') || isElementType(target, 'input') && ClickInputOnEnter.includes(target.type) || isElementType(target, 'a') && Boolean(target.href)) { + return ()=>{ + instance.dispatchUIEvent(target, 'click'); + }; + } else if (isElementType(target, 'input')) { + const form = target.form; + const submit = form === null || form === undefined ? undefined : form.querySelector('input[type="submit"], button:not([type]), button[type="submit"]'); + if (submit) { + return ()=>instance.dispatchUIEvent(submit, 'click'); + } else if (form && SubmitSingleInputOnEnter.includes(target.type) && form.querySelectorAll('input').length === 1) { + return ()=>instance.dispatchUIEvent(form, 'submit'); + } else { + return; + } + } + } + if (isEditable(target)) { + const inputType = event.key === 'Enter' ? isContentEditable(target) && !instance.system.keyboard.modifiers.Shift ? 'insertParagraph' : 'insertLineBreak' : 'insertText'; + const inputData = event.key === 'Enter' ? '\n' : event.key; + return ()=>input(instance, target, inputData, inputType); + } +}; +const ClickInputOnEnter = [ + 'button', + 'color', + 'file', + 'image', + 'reset', + 'submit' +]; +const SubmitSingleInputOnEnter = [ + 'email', + 'month', + 'password', + 'search', + 'tel', + 'text', + 'url', + 'week' +]; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/keyup.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/keyup.js new file mode 100644 index 0000000000000000000000000000000000000000..0a3db402bd7d041022557e4548864c82f23cc552 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/keyup.js @@ -0,0 +1,15 @@ +import { isClickableInput } from '../../utils/click/isClickableInput.js'; +import '../../utils/dataTransfer/Clipboard.js'; +import { behavior } from './registry.js'; + +behavior.keyup = (event, target, instance)=>{ + var _keyupBehavior_event_key; + return (_keyupBehavior_event_key = keyupBehavior[event.key]) === null || _keyupBehavior_event_key === undefined ? undefined : _keyupBehavior_event_key.call(keyupBehavior, event, target, instance); +}; +const keyupBehavior = { + ' ': (event, target, instance)=>{ + if (isClickableInput(target)) { + return ()=>instance.dispatchUIEvent(target, 'click'); + } + } +}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/paste.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/paste.js new file mode 100644 index 0000000000000000000000000000000000000000..28eefa3a5b34bfa453344d53e1588faeda7c3adb --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/paste.js @@ -0,0 +1,16 @@ +import '../../utils/dataTransfer/Clipboard.js'; +import { isEditable } from '../../utils/edit/isEditable.js'; +import { input } from '../input.js'; +import { behavior } from './registry.js'; + +behavior.paste = (event, target, instance)=>{ + if (isEditable(target)) { + return ()=>{ + var _event_clipboardData; + const insertData = (_event_clipboardData = event.clipboardData) === null || _event_clipboardData === undefined ? undefined : _event_clipboardData.getData('text'); + if (insertData) { + input(instance, target, insertData, 'insertFromPaste'); + } + }; + } +}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/registry.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/registry.js new file mode 100644 index 0000000000000000000000000000000000000000..3334fa1f59e291ae92a65704a64bc0a7ca203e31 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/behavior/registry.js @@ -0,0 +1,3 @@ +const behavior = {}; + +export { behavior }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/createEvent.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/createEvent.js new file mode 100644 index 0000000000000000000000000000000000000000..1c741ba446f40917727236e9e4ad29a20357d03a --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/createEvent.js @@ -0,0 +1,205 @@ +import '../utils/dataTransfer/Clipboard.js'; +import { getWindow } from '../utils/misc/getWindow.js'; +import { eventMap } from './eventMap.js'; + +const eventInitializer = { + ClipboardEvent: [ + initClipboardEvent + ], + Event: [], + FocusEvent: [ + initUIEvent, + initFocusEvent + ], + InputEvent: [ + initUIEvent, + initInputEvent + ], + MouseEvent: [ + initUIEvent, + initUIEventModifiers, + initMouseEvent + ], + PointerEvent: [ + initUIEvent, + initUIEventModifiers, + initMouseEvent, + initPointerEvent + ], + KeyboardEvent: [ + initUIEvent, + initUIEventModifiers, + initKeyboardEvent + ] +}; +function createEvent(type, target, init) { + const window = getWindow(target); + const { EventType, defaultInit } = eventMap[type]; + const event = new (getEventConstructors(window))[EventType](type, defaultInit); + eventInitializer[EventType].forEach((f)=>f(event, init !== null && init !== undefined ? init : {})); + return event; +} +/* istanbul ignore next */ function getEventConstructors(window) { + var _window_Event; + /* eslint-disable @typescript-eslint/no-unnecessary-condition, @typescript-eslint/no-extraneous-class */ const Event = (_window_Event = window.Event) !== null && _window_Event !== undefined ? _window_Event : class Event { + }; + var _window_AnimationEvent; + const AnimationEvent = (_window_AnimationEvent = window.AnimationEvent) !== null && _window_AnimationEvent !== undefined ? _window_AnimationEvent : class AnimationEvent extends Event { + }; + var _window_ClipboardEvent; + const ClipboardEvent = (_window_ClipboardEvent = window.ClipboardEvent) !== null && _window_ClipboardEvent !== undefined ? _window_ClipboardEvent : class ClipboardEvent extends Event { + }; + var _window_PopStateEvent; + const PopStateEvent = (_window_PopStateEvent = window.PopStateEvent) !== null && _window_PopStateEvent !== undefined ? _window_PopStateEvent : class PopStateEvent extends Event { + }; + var _window_ProgressEvent; + const ProgressEvent = (_window_ProgressEvent = window.ProgressEvent) !== null && _window_ProgressEvent !== undefined ? _window_ProgressEvent : class ProgressEvent extends Event { + }; + var _window_TransitionEvent; + const TransitionEvent = (_window_TransitionEvent = window.TransitionEvent) !== null && _window_TransitionEvent !== undefined ? _window_TransitionEvent : class TransitionEvent extends Event { + }; + var _window_UIEvent; + const UIEvent = (_window_UIEvent = window.UIEvent) !== null && _window_UIEvent !== undefined ? _window_UIEvent : class UIEvent extends Event { + }; + var _window_CompositionEvent; + const CompositionEvent = (_window_CompositionEvent = window.CompositionEvent) !== null && _window_CompositionEvent !== undefined ? _window_CompositionEvent : class CompositionEvent extends UIEvent { + }; + var _window_FocusEvent; + const FocusEvent = (_window_FocusEvent = window.FocusEvent) !== null && _window_FocusEvent !== undefined ? _window_FocusEvent : class FocusEvent extends UIEvent { + }; + var _window_InputEvent; + const InputEvent = (_window_InputEvent = window.InputEvent) !== null && _window_InputEvent !== undefined ? _window_InputEvent : class InputEvent extends UIEvent { + }; + var _window_KeyboardEvent; + const KeyboardEvent = (_window_KeyboardEvent = window.KeyboardEvent) !== null && _window_KeyboardEvent !== undefined ? _window_KeyboardEvent : class KeyboardEvent extends UIEvent { + }; + var _window_MouseEvent; + const MouseEvent = (_window_MouseEvent = window.MouseEvent) !== null && _window_MouseEvent !== undefined ? _window_MouseEvent : class MouseEvent extends UIEvent { + }; + var _window_DragEvent; + const DragEvent = (_window_DragEvent = window.DragEvent) !== null && _window_DragEvent !== undefined ? _window_DragEvent : class DragEvent extends MouseEvent { + }; + var _window_PointerEvent; + const PointerEvent = (_window_PointerEvent = window.PointerEvent) !== null && _window_PointerEvent !== undefined ? _window_PointerEvent : class PointerEvent extends MouseEvent { + }; + var _window_TouchEvent; + const TouchEvent = (_window_TouchEvent = window.TouchEvent) !== null && _window_TouchEvent !== undefined ? _window_TouchEvent : class TouchEvent extends UIEvent { + }; + /* eslint-enable @typescript-eslint/no-unnecessary-condition, @typescript-eslint/no-extraneous-class */ return { + Event, + AnimationEvent, + ClipboardEvent, + PopStateEvent, + ProgressEvent, + TransitionEvent, + UIEvent, + CompositionEvent, + FocusEvent, + InputEvent, + KeyboardEvent, + MouseEvent, + DragEvent, + PointerEvent, + TouchEvent + }; +} +function assignProps(obj, props) { + for (const [key, value] of Object.entries(props)){ + Object.defineProperty(obj, key, { + get: ()=>value !== null && value !== undefined ? value : null + }); + } +} +function sanitizeNumber(n) { + return Number(n !== null && n !== undefined ? n : 0); +} +function initClipboardEvent(event, { clipboardData }) { + assignProps(event, { + clipboardData + }); +} +function initFocusEvent(event, { relatedTarget }) { + assignProps(event, { + relatedTarget + }); +} +function initInputEvent(event, { data, inputType, isComposing }) { + assignProps(event, { + data, + isComposing: Boolean(isComposing), + inputType: String(inputType) + }); +} +function initUIEvent(event, { view, detail }) { + assignProps(event, { + view, + detail: sanitizeNumber(detail !== null && detail !== undefined ? detail : 0) + }); +} +function initUIEventModifiers(event, { altKey, ctrlKey, metaKey, shiftKey, modifierAltGraph, modifierCapsLock, modifierFn, modifierFnLock, modifierNumLock, modifierScrollLock, modifierSymbol, modifierSymbolLock }) { + assignProps(event, { + altKey: Boolean(altKey), + ctrlKey: Boolean(ctrlKey), + metaKey: Boolean(metaKey), + shiftKey: Boolean(shiftKey), + getModifierState (k) { + return Boolean({ + Alt: altKey, + AltGraph: modifierAltGraph, + CapsLock: modifierCapsLock, + Control: ctrlKey, + Fn: modifierFn, + FnLock: modifierFnLock, + Meta: metaKey, + NumLock: modifierNumLock, + ScrollLock: modifierScrollLock, + Shift: shiftKey, + Symbol: modifierSymbol, + SymbolLock: modifierSymbolLock + }[k]); + } + }); +} +function initKeyboardEvent(event, { key, code, location, repeat, isComposing, charCode }) { + assignProps(event, { + key: String(key), + code: String(code), + location: sanitizeNumber(location), + repeat: Boolean(repeat), + isComposing: Boolean(isComposing), + charCode + }); +} +function initMouseEvent(event, { x, y, screenX, screenY, clientX = x, clientY = y, button, buttons, relatedTarget, offsetX, offsetY, pageX, pageY }) { + assignProps(event, { + screenX: sanitizeNumber(screenX), + screenY: sanitizeNumber(screenY), + clientX: sanitizeNumber(clientX), + x: sanitizeNumber(clientX), + clientY: sanitizeNumber(clientY), + y: sanitizeNumber(clientY), + button: sanitizeNumber(button), + buttons: sanitizeNumber(buttons), + relatedTarget, + offsetX: sanitizeNumber(offsetX), + offsetY: sanitizeNumber(offsetY), + pageX: sanitizeNumber(pageX), + pageY: sanitizeNumber(pageY) + }); +} +function initPointerEvent(event, { pointerId, width, height, pressure, tangentialPressure, tiltX, tiltY, twist, pointerType, isPrimary }) { + assignProps(event, { + pointerId: sanitizeNumber(pointerId), + width: sanitizeNumber(width !== null && width !== undefined ? width : 1), + height: sanitizeNumber(height !== null && height !== undefined ? height : 1), + pressure: sanitizeNumber(pressure), + tangentialPressure: sanitizeNumber(tangentialPressure), + tiltX: sanitizeNumber(tiltX), + tiltY: sanitizeNumber(tiltY), + twist: sanitizeNumber(twist), + pointerType: String(pointerType), + isPrimary: Boolean(isPrimary) + }); +} + +export { createEvent }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/dispatchEvent.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/dispatchEvent.js new file mode 100644 index 0000000000000000000000000000000000000000..80939fb7d7181b9c33d76f5e1315b16d0ab458d3 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/dispatchEvent.js @@ -0,0 +1,50 @@ +import './behavior/click.js'; +import './behavior/cut.js'; +import './behavior/keydown.js'; +import './behavior/keypress.js'; +import './behavior/keyup.js'; +import './behavior/paste.js'; +import { behavior } from './behavior/registry.js'; +import { wrapEvent } from './wrapEvent.js'; +import { isMouseEvent, isKeyboardEvent } from './eventMap.js'; +import { createEvent } from './createEvent.js'; + +function dispatchUIEvent(target, type, init, preventDefault = false) { + if (isMouseEvent(type) || isKeyboardEvent(type)) { + init = { + ...init, + ...this.system.getUIEventModifiers() + }; + } + const event = createEvent(type, target, init); + return dispatchEvent.call(this, target, event, preventDefault); +} +function dispatchEvent(target, event, preventDefault = false) { + var _behavior_type; + const type = event.type; + const behaviorImplementation = preventDefault ? ()=>{} : (_behavior_type = behavior[type]) === null || _behavior_type === undefined ? undefined : _behavior_type.call(behavior, event, target, this); + if (behaviorImplementation) { + event.preventDefault(); + let defaultPrevented = false; + Object.defineProperty(event, 'defaultPrevented', { + get: ()=>defaultPrevented + }); + Object.defineProperty(event, 'preventDefault', { + value: ()=>{ + defaultPrevented = event.cancelable; + } + }); + wrapEvent(()=>target.dispatchEvent(event)); + if (!defaultPrevented) { + behaviorImplementation(); + } + return !defaultPrevented; + } + return wrapEvent(()=>target.dispatchEvent(event)); +} +function dispatchDOMEvent(target, type, init) { + const event = createEvent(type, target, init); + wrapEvent(()=>target.dispatchEvent(event)); +} + +export { dispatchDOMEvent, dispatchEvent, dispatchUIEvent }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/eventMap.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/eventMap.js new file mode 100644 index 0000000000000000000000000000000000000000..2d65705556f5a004e7766916faca27b6836e5b7b --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/eventMap.js @@ -0,0 +1,277 @@ +const eventMap = { + auxclick: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + beforeinput: { + EventType: 'InputEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + blur: { + EventType: 'FocusEvent', + defaultInit: { + bubbles: false, + cancelable: false, + composed: true + } + }, + click: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + contextmenu: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + copy: { + EventType: 'ClipboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + change: { + EventType: 'Event', + defaultInit: { + bubbles: true, + cancelable: false + } + }, + cut: { + EventType: 'ClipboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + dblclick: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + focus: { + EventType: 'FocusEvent', + defaultInit: { + bubbles: false, + cancelable: false, + composed: true + } + }, + focusin: { + EventType: 'FocusEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + focusout: { + EventType: 'FocusEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + keydown: { + EventType: 'KeyboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + keypress: { + EventType: 'KeyboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + keyup: { + EventType: 'KeyboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + paste: { + EventType: 'ClipboardEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + input: { + EventType: 'InputEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + mousedown: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseenter: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: false, + cancelable: false, + composed: true + } + }, + mouseleave: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: false, + cancelable: false, + composed: true + } + }, + mousemove: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseout: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseover: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + mouseup: { + EventType: 'MouseEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + pointerover: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + pointerenter: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + pointerdown: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + pointermove: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + pointerup: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + pointercancel: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: false, + composed: true + } + }, + pointerout: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: true, + cancelable: true, + composed: true + } + }, + pointerleave: { + EventType: 'PointerEvent', + defaultInit: { + bubbles: false, + cancelable: false + } + }, + submit: { + EventType: 'Event', + defaultInit: { + bubbles: true, + cancelable: true + } + } +}; +function getEventClass(type) { + return eventMap[type].EventType; +} +const mouseEvents = [ + 'MouseEvent', + 'PointerEvent' +]; +function isMouseEvent(type) { + return mouseEvents.includes(getEventClass(type)); +} +function isKeyboardEvent(type) { + return getEventClass(type) === 'KeyboardEvent'; +} + +export { eventMap, isKeyboardEvent, isMouseEvent }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/focus.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/focus.js new file mode 100644 index 0000000000000000000000000000000000000000..13b85f0cc93c5b017e92e9af736869a6cd3fca44 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/focus.js @@ -0,0 +1,31 @@ +import '../utils/dataTransfer/Clipboard.js'; +import { getActiveElement } from '../utils/focus/getActiveElement.js'; +import { isFocusable } from '../utils/focus/isFocusable.js'; +import { findClosest } from '../utils/misc/findClosest.js'; +import { updateSelectionOnFocus } from './selection/updateSelectionOnFocus.js'; +import { wrapEvent } from './wrapEvent.js'; + +// Browsers do not dispatch FocusEvent if the document does not have focus. +// TODO: simulate FocusEvent in browsers +/** + * Focus closest focusable element. + */ function focusElement(element) { + const target = findClosest(element, isFocusable); + const activeElement = getActiveElement(element.ownerDocument); + if ((target !== null && target !== undefined ? target : element.ownerDocument.body) === activeElement) { + return; + } else if (target) { + wrapEvent(()=>target.focus()); + } else { + wrapEvent(()=>activeElement === null || activeElement === undefined ? undefined : activeElement.blur()); + } + updateSelectionOnFocus(target !== null && target !== undefined ? target : element.ownerDocument.body); +} +function blurElement(element) { + if (!isFocusable(element)) return; + const wasActive = getActiveElement(element.ownerDocument) === element; + if (!wasActive) return; + wrapEvent(()=>element.blur()); +} + +export { blurElement, focusElement }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0d18a193987b9f5e3391be7dcdccd671229f2754 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/index.js @@ -0,0 +1,7 @@ +export { dispatchDOMEvent, dispatchEvent, dispatchUIEvent } from './dispatchEvent.js'; +export { blurElement, focusElement } from './focus.js'; +export { input } from './input.js'; +import '../utils/dataTransfer/Clipboard.js'; +export { setSelectionPerMouseDown } from './selection/setSelectionPerMouse.js'; +export { modifySelectionPerMouseMove } from './selection/modifySelectionPerMouse.js'; +export { isAllSelected, selectAll } from './selection/selectAll.js'; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/input.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/input.js new file mode 100644 index 0000000000000000000000000000000000000000..ab5ab60c5940d3b7c9a96168577d7e6d6eb8f769 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/input.js @@ -0,0 +1,155 @@ +import { setUIValue, clearInitialValue, getUIValue } from '../document/UI.js'; +import { isElementType } from '../utils/misc/isElementType.js'; +import '../utils/dataTransfer/Clipboard.js'; +import { isValidDateOrTimeValue, buildTimeValue } from '../utils/edit/timeValue.js'; +import { supportsMaxLength, getMaxLength } from '../utils/edit/maxLength.js'; +import { getNextCursorPosition } from '../utils/focus/cursor.js'; +import { commitValueAfterInput } from '../document/trackValue.js'; +import { getInputRange } from './selection/getInputRange.js'; +import { setSelection } from './selection/setSelection.js'; + +function isDateOrTime(element) { + return isElementType(element, 'input') && [ + 'date', + 'time' + ].includes(element.type); +} +function input(instance, element, data, inputType = 'insertText') { + const inputRange = getInputRange(element); + /* istanbul ignore if */ if (!inputRange) { + return; + } + // There is no `beforeinput` event on `date` and `time` input + if (!isDateOrTime(element)) { + const unprevented = instance.dispatchUIEvent(element, 'beforeinput', { + inputType, + data + }); + if (!unprevented) { + return; + } + } + if ('startContainer' in inputRange) { + editContenteditable(instance, element, inputRange, data, inputType); + } else { + editInputElement(instance, element, inputRange, data, inputType); + } +} +function editContenteditable(instance, element, inputRange, data, inputType) { + let del = false; + if (!inputRange.collapsed) { + del = true; + inputRange.deleteContents(); + } else if ([ + 'deleteContentBackward', + 'deleteContentForward' + ].includes(inputType)) { + const nextPosition = getNextCursorPosition(inputRange.startContainer, inputRange.startOffset, inputType === 'deleteContentBackward' ? -1 : 1, inputType); + if (nextPosition) { + del = true; + const delRange = inputRange.cloneRange(); + if (delRange.comparePoint(nextPosition.node, nextPosition.offset) < 0) { + delRange.setStart(nextPosition.node, nextPosition.offset); + } else { + delRange.setEnd(nextPosition.node, nextPosition.offset); + } + delRange.deleteContents(); + } + } + if (data) { + if (inputRange.endContainer.nodeType === 3) { + const offset = inputRange.endOffset; + inputRange.endContainer.insertData(offset, data); + inputRange.setStart(inputRange.endContainer, offset + data.length); + inputRange.setEnd(inputRange.endContainer, offset + data.length); + } else { + const text = element.ownerDocument.createTextNode(data); + inputRange.insertNode(text); + inputRange.setStart(text, data.length); + inputRange.setEnd(text, data.length); + } + } + if (del || data) { + instance.dispatchUIEvent(element, 'input', { + inputType + }); + } +} +function editInputElement(instance, element, inputRange, data, inputType) { + let dataToInsert = data; + if (supportsMaxLength(element)) { + const maxLength = getMaxLength(element); + if (maxLength !== undefined && data.length > 0) { + const spaceUntilMaxLength = maxLength - element.value.length; + if (spaceUntilMaxLength > 0) { + dataToInsert = data.substring(0, spaceUntilMaxLength); + } else { + return; + } + } + } + const { newValue, newOffset, oldValue } = calculateNewValue(dataToInsert, element, inputRange, inputType); + if (newValue === oldValue && newOffset === inputRange.startOffset && newOffset === inputRange.endOffset) { + return; + } + if (isElementType(element, 'input', { + type: 'number' + }) && !isValidNumberInput(newValue)) { + return; + } + setUIValue(element, newValue); + setSelection({ + focusNode: element, + anchorOffset: newOffset, + focusOffset: newOffset + }); + if (isDateOrTime(element)) { + if (isValidDateOrTimeValue(element, newValue)) { + commitInput(instance, element, newOffset, {}); + instance.dispatchUIEvent(element, 'change'); + clearInitialValue(element); + } + } else { + commitInput(instance, element, newOffset, { + data, + inputType + }); + } +} +function calculateNewValue(inputData, node, { startOffset, endOffset }, inputType) { + const value = getUIValue(node); + const prologEnd = Math.max(0, startOffset === endOffset && inputType === 'deleteContentBackward' ? startOffset - 1 : startOffset); + const prolog = value.substring(0, prologEnd); + const epilogStart = Math.min(value.length, startOffset === endOffset && inputType === 'deleteContentForward' ? startOffset + 1 : endOffset); + const epilog = value.substring(epilogStart, value.length); + let newValue = `${prolog}${inputData}${epilog}`; + let newOffset = prologEnd + inputData.length; + if (isElementType(node, 'input', { + type: 'time' + })) { + const builtValue = buildTimeValue(newValue); + if (builtValue !== '' && isValidDateOrTimeValue(node, builtValue)) { + newValue = builtValue; + newOffset = builtValue.length; + } + } + return { + oldValue: value, + newValue, + newOffset + }; +} +function commitInput(instance, element, newOffset, inputInit) { + instance.dispatchUIEvent(element, 'input', inputInit); + commitValueAfterInput(element, newOffset); +} +function isValidNumberInput(value) { + var _value_match, _value_match1; + // the browser allows some invalid input but not others + // it allows up to two '-' at any place before any 'e' or one directly following 'e' + // it allows one '.' at any place before e + const valueParts = value.split('e', 2); + return !(/[^\d.\-e]/.test(value) || Number((_value_match = value.match(/-/g)) === null || _value_match === undefined ? undefined : _value_match.length) > 2 || Number((_value_match1 = value.match(/\./g)) === null || _value_match1 === undefined ? undefined : _value_match1.length) > 1 || valueParts[1] && !/^-?\d*$/.test(valueParts[1])); +} + +export { input }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/radio.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/radio.js new file mode 100644 index 0000000000000000000000000000000000000000..4f4f874ac8e89091d51d8a9e13ffcc79a2624c6d --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/radio.js @@ -0,0 +1,25 @@ +import '../utils/dataTransfer/Clipboard.js'; +import { isDisabled } from '../utils/misc/isDisabled.js'; +import { getWindow } from '../utils/misc/getWindow.js'; +import { focusElement } from './focus.js'; + +function walkRadio(instance, el, direction) { + const window = getWindow(el); + const group = Array.from(el.ownerDocument.querySelectorAll(el.name ? `input[type="radio"][name="${window.CSS.escape(el.name)}"]` : `input[type="radio"][name=""], input[type="radio"]:not([name])`)); + for(let i = group.findIndex((e)=>e === el) + direction;; i += direction){ + if (!group[i]) { + i = direction > 0 ? 0 : group.length - 1; + } + if (group[i] === el) { + return; + } + if (isDisabled(group[i])) { + continue; + } + focusElement(group[i]); + instance.dispatchUIEvent(group[i], 'click'); + return; + } +} + +export { walkRadio }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/getInputRange.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/getInputRange.js new file mode 100644 index 0000000000000000000000000000000000000000..b766f66f7e31160e5c68b6f3ccc2724ef5dc0965 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/getInputRange.js @@ -0,0 +1,16 @@ +import { getTargetTypeAndSelection } from './getTargetTypeAndSelection.js'; + +/** + * Get the range that would be overwritten by input. + */ function getInputRange(focusNode) { + const typeAndSelection = getTargetTypeAndSelection(focusNode); + if (typeAndSelection.type === 'input') { + return typeAndSelection.selection; + } else if (typeAndSelection.type === 'contenteditable') { + var _typeAndSelection_selection; + // Multi-range on contenteditable edits the first selection instead of the last + return (_typeAndSelection_selection = typeAndSelection.selection) === null || _typeAndSelection_selection === undefined ? undefined : _typeAndSelection_selection.getRangeAt(0); + } +} + +export { getInputRange }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/getTargetTypeAndSelection.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/getTargetTypeAndSelection.js new file mode 100644 index 0000000000000000000000000000000000000000..80c7875078269301c40cb7ea520984edc3139e6e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/getTargetTypeAndSelection.js @@ -0,0 +1,29 @@ +import { getUISelection } from '../../document/UI.js'; +import '../../utils/dataTransfer/Clipboard.js'; +import { getContentEditable } from '../../utils/edit/isContentEditable.js'; +import { hasOwnSelection } from '../../utils/focus/selection.js'; + +/** + * Determine which selection logic and selection ranges to consider. + */ function getTargetTypeAndSelection(node) { + const element = getElement(node); + if (element && hasOwnSelection(element)) { + return { + type: 'input', + selection: getUISelection(element) + }; + } + const selection = element === null || element === undefined ? undefined : element.ownerDocument.getSelection(); + // It is possible to extend a single-range selection into a contenteditable. + // This results in the range acting like a range outside of contenteditable. + const isCE = getContentEditable(node) && (selection === null || selection === undefined ? undefined : selection.anchorNode) && getContentEditable(selection.anchorNode); + return { + type: isCE ? 'contenteditable' : 'default', + selection + }; +} +function getElement(node) { + return node.nodeType === 1 ? node : node.parentElement; +} + +export { getTargetTypeAndSelection }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/index.js new file mode 100644 index 0000000000000000000000000000000000000000..13432b3cfe64cc17346d0ed5c6375b8693ee3af0 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/index.js @@ -0,0 +1,9 @@ +export { getInputRange } from './getInputRange.js'; +export { modifySelection } from './modifySelection.js'; +export { moveSelection } from './moveSelection.js'; +export { setSelectionPerMouseDown } from './setSelectionPerMouse.js'; +export { modifySelectionPerMouseMove } from './modifySelectionPerMouse.js'; +export { isAllSelected, selectAll } from './selectAll.js'; +export { setSelectionRange } from './setSelectionRange.js'; +export { setSelection } from './setSelection.js'; +export { updateSelectionOnFocus } from './updateSelectionOnFocus.js'; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/modifySelection.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/modifySelection.js new file mode 100644 index 0000000000000000000000000000000000000000..eac743cb9da0972701bf7876b4ec47d8691db2a3 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/modifySelection.js @@ -0,0 +1,19 @@ +import { setUISelection } from '../../document/UI.js'; +import '../../utils/dataTransfer/Clipboard.js'; +import { getTargetTypeAndSelection } from './getTargetTypeAndSelection.js'; + +/** + * Extend/shrink the selection like with Shift+Arrows or Shift+Mouse + */ function modifySelection({ focusNode, focusOffset }) { + var _focusNode_ownerDocument_getSelection, _focusNode_ownerDocument; + const typeAndSelection = getTargetTypeAndSelection(focusNode); + if (typeAndSelection.type === 'input') { + return setUISelection(focusNode, { + anchorOffset: typeAndSelection.selection.anchorOffset, + focusOffset + }, 'modify'); + } + (_focusNode_ownerDocument = focusNode.ownerDocument) === null || _focusNode_ownerDocument === undefined ? undefined : (_focusNode_ownerDocument_getSelection = _focusNode_ownerDocument.getSelection()) === null || _focusNode_ownerDocument_getSelection === undefined ? undefined : _focusNode_ownerDocument_getSelection.extend(focusNode, focusOffset); +} + +export { modifySelection }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/modifySelectionPerMouse.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/modifySelectionPerMouse.js new file mode 100644 index 0000000000000000000000000000000000000000..d3aa9657b87772c3b2f19d392edaae3ffb2ec112 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/modifySelectionPerMouse.js @@ -0,0 +1,38 @@ +import { setUISelection } from '../../document/UI.js'; +import '../../utils/dataTransfer/Clipboard.js'; +import { resolveCaretPosition } from './resolveCaretPosition.js'; + +function modifySelectionPerMouseMove(selectionRange, { document, target, node, offset }) { + const selectionFocus = resolveCaretPosition({ + target, + node, + offset + }); + if ('node' in selectionRange) { + // When the mouse is dragged outside of an input/textarea, + // the selection is extended to the beginning or end of the input + // depending on pointer position. + // TODO: extend selection according to pointer position + /* istanbul ignore else */ if (selectionFocus.node === selectionRange.node) { + const anchorOffset = selectionFocus.offset < selectionRange.start ? selectionRange.end : selectionRange.start; + const focusOffset = selectionFocus.offset > selectionRange.end || selectionFocus.offset < selectionRange.start ? selectionFocus.offset : selectionRange.end; + setUISelection(selectionRange.node, { + anchorOffset, + focusOffset + }); + } + } else { + const range = selectionRange.cloneRange(); + const cmp = range.comparePoint(selectionFocus.node, selectionFocus.offset); + if (cmp < 0) { + range.setStart(selectionFocus.node, selectionFocus.offset); + } else if (cmp > 0) { + range.setEnd(selectionFocus.node, selectionFocus.offset); + } + const selection = document.getSelection(); + selection === null || selection === undefined ? undefined : selection.removeAllRanges(); + selection === null || selection === undefined ? undefined : selection.addRange(range.cloneRange()); + } +} + +export { modifySelectionPerMouseMove }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/moveSelection.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/moveSelection.js new file mode 100644 index 0000000000000000000000000000000000000000..336295868ea66f3f337be435c4f389bfbdbd866a --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/moveSelection.js @@ -0,0 +1,36 @@ +import { getUISelection } from '../../document/UI.js'; +import '../../utils/dataTransfer/Clipboard.js'; +import { getNextCursorPosition } from '../../utils/focus/cursor.js'; +import { hasOwnSelection } from '../../utils/focus/selection.js'; +import { setSelection } from './setSelection.js'; + +/** + * Move the selection + */ function moveSelection(node, direction) { + // TODO: implement shift + if (hasOwnSelection(node)) { + const selection = getUISelection(node); + setSelection({ + focusNode: node, + focusOffset: selection.startOffset === selection.endOffset ? selection.focusOffset + direction : direction < 0 ? selection.startOffset : selection.endOffset + }); + } else { + const selection = node.ownerDocument.getSelection(); + if (!(selection === null || selection === undefined ? undefined : selection.focusNode)) { + return; + } + if (selection.isCollapsed) { + const nextPosition = getNextCursorPosition(selection.focusNode, selection.focusOffset, direction); + if (nextPosition) { + setSelection({ + focusNode: nextPosition.node, + focusOffset: nextPosition.offset + }); + } + } else { + selection[direction < 0 ? 'collapseToStart' : 'collapseToEnd'](); + } + } +} + +export { moveSelection }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/resolveCaretPosition.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/resolveCaretPosition.js new file mode 100644 index 0000000000000000000000000000000000000000..9ff8d3dac4f5899eae6d171a73dc3f8a98670efa --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/resolveCaretPosition.js @@ -0,0 +1,59 @@ +import { getUIValue } from '../../document/UI.js'; +import '../../utils/dataTransfer/Clipboard.js'; +import { hasOwnSelection } from '../../utils/focus/selection.js'; + +function resolveCaretPosition({ target, node, offset }) { + if (hasOwnSelection(target)) { + return { + node: target, + offset: offset !== null && offset !== undefined ? offset : getUIValue(target).length + }; + } else if (node) { + return { + node, + offset: offset !== null && offset !== undefined ? offset : node.nodeType === 3 ? node.nodeValue.length : node.childNodes.length + }; + } + return findNodeAtTextOffset(target, offset); +} +function findNodeAtTextOffset(node, offset, isRoot = true) { + // When clicking after the content the browser behavior can be complicated: + // 1. If there is textContent after the last element child, + // the cursor is moved there. + // 2. If there is textContent in the last element child, + // the browser moves the cursor to the last non-empty text node inside this element. + // 3. Otherwise the cursor is moved to the end of the target. + let i = offset === undefined ? node.childNodes.length - 1 : 0; + const step = offset === undefined ? -1 : 1; + while(offset === undefined ? i >= (isRoot ? Math.max(node.childNodes.length - 1, 0) : 0) : i <= node.childNodes.length){ + if (offset && i === node.childNodes.length) { + throw new Error('The given offset is out of bounds.'); + } + const c = node.childNodes.item(i); + const text = String(c.textContent); + if (text.length) { + if (offset !== undefined && text.length < offset) { + offset -= text.length; + } else if (c.nodeType === 1) { + return findNodeAtTextOffset(c, offset, false); + } else { + // The pre-commit hooks keeps changing this + // See https://github.com/kentcdodds/kcd-scripts/issues/218 + /* istanbul ignore else */ // eslint-disable-next-line no-lonely-if + if (c.nodeType === 3) { + return { + node: c, + offset: offset !== null && offset !== undefined ? offset : c.nodeValue.length + }; + } + } + } + i += step; + } + return { + node, + offset: node.childNodes.length + }; +} + +export { resolveCaretPosition }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/selectAll.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/selectAll.js new file mode 100644 index 0000000000000000000000000000000000000000..b25d98dd8216f478cd769eedd08677f25c34aeec --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/selectAll.js @@ -0,0 +1,35 @@ +import { getUIValue, getUISelection } from '../../document/UI.js'; +import '../../utils/dataTransfer/Clipboard.js'; +import { getContentEditable } from '../../utils/edit/isContentEditable.js'; +import { hasOwnSelection } from '../../utils/focus/selection.js'; +import { setSelection } from './setSelection.js'; + +/** + * Expand a selection like the browser does when pressing Ctrl+A. + */ function selectAll(target) { + if (hasOwnSelection(target)) { + return setSelection({ + focusNode: target, + anchorOffset: 0, + focusOffset: getUIValue(target).length + }); + } + var _getContentEditable; + const focusNode = (_getContentEditable = getContentEditable(target)) !== null && _getContentEditable !== undefined ? _getContentEditable : target.ownerDocument.body; + setSelection({ + focusNode, + anchorOffset: 0, + focusOffset: focusNode.childNodes.length + }); +} +function isAllSelected(target) { + if (hasOwnSelection(target)) { + return getUISelection(target).startOffset === 0 && getUISelection(target).endOffset === getUIValue(target).length; + } + var _getContentEditable; + const focusNode = (_getContentEditable = getContentEditable(target)) !== null && _getContentEditable !== undefined ? _getContentEditable : target.ownerDocument.body; + const selection = target.ownerDocument.getSelection(); + return (selection === null || selection === undefined ? undefined : selection.anchorNode) === focusNode && selection.focusNode === focusNode && selection.anchorOffset === 0 && selection.focusOffset === focusNode.childNodes.length; +} + +export { isAllSelected, selectAll }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/setSelection.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/setSelection.js new file mode 100644 index 0000000000000000000000000000000000000000..84ee04b212b285f069f86767bcb2ada4d2edd207 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/setSelection.js @@ -0,0 +1,19 @@ +import { setUISelection } from '../../document/UI.js'; +import '../../utils/dataTransfer/Clipboard.js'; +import { getTargetTypeAndSelection } from './getTargetTypeAndSelection.js'; + +/** + * Set the selection + */ function setSelection({ focusNode, focusOffset, anchorNode = focusNode, anchorOffset = focusOffset }) { + var _anchorNode_ownerDocument_getSelection, _anchorNode_ownerDocument; + const typeAndSelection = getTargetTypeAndSelection(focusNode); + if (typeAndSelection.type === 'input') { + return setUISelection(focusNode, { + anchorOffset, + focusOffset + }); + } + (_anchorNode_ownerDocument = anchorNode.ownerDocument) === null || _anchorNode_ownerDocument === undefined ? undefined : (_anchorNode_ownerDocument_getSelection = _anchorNode_ownerDocument.getSelection()) === null || _anchorNode_ownerDocument_getSelection === undefined ? undefined : _anchorNode_ownerDocument_getSelection.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset); +} + +export { setSelection }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/setSelectionPerMouse.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/setSelectionPerMouse.js new file mode 100644 index 0000000000000000000000000000000000000000..57c3b1d676c1000720bfd66eba5c41607427befd --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/setSelectionPerMouse.js @@ -0,0 +1,79 @@ +import { getUIValue, setUISelection } from '../../document/UI.js'; +import '../../utils/dataTransfer/Clipboard.js'; +import { hasNoSelection, hasOwnSelection } from '../../utils/focus/selection.js'; +import { resolveCaretPosition } from './resolveCaretPosition.js'; + +function setSelectionPerMouseDown({ document, target, clickCount, node, offset }) { + if (hasNoSelection(target)) { + return; + } + const targetHasOwnSelection = hasOwnSelection(target); + // On non-input elements the text selection per multiple click + // can extend beyond the target boundaries. + // The exact mechanism what is considered in the same line is unclear. + // Looks it might be every inline element. + // TODO: Check what might be considered part of the same line of text. + const text = String(targetHasOwnSelection ? getUIValue(target) : target.textContent); + const [start, end] = node ? // which elements might be considered in the same line of text. + // TODO: support expanding initial range on multiple clicks if node is given + [ + offset, + offset + ] : getTextRange(text, offset, clickCount); + // TODO: implement modifying selection per shift/ctrl+mouse + if (targetHasOwnSelection) { + setUISelection(target, { + anchorOffset: start !== null && start !== undefined ? start : text.length, + focusOffset: end !== null && end !== undefined ? end : text.length + }); + return { + node: target, + start: start !== null && start !== undefined ? start : 0, + end: end !== null && end !== undefined ? end : text.length + }; + } else { + const { node: startNode, offset: startOffset } = resolveCaretPosition({ + target, + node, + offset: start + }); + const { node: endNode, offset: endOffset } = resolveCaretPosition({ + target, + node, + offset: end + }); + const range = target.ownerDocument.createRange(); + try { + range.setStart(startNode, startOffset); + range.setEnd(endNode, endOffset); + } catch (e) { + throw new Error('The given offset is out of bounds.'); + } + const selection = document.getSelection(); + selection === null || selection === undefined ? undefined : selection.removeAllRanges(); + selection === null || selection === undefined ? undefined : selection.addRange(range.cloneRange()); + return range; + } +} +function getTextRange(text, pos, clickCount) { + if (clickCount % 3 === 1 || text.length === 0) { + return [ + pos, + pos + ]; + } + const textPos = pos !== null && pos !== undefined ? pos : text.length; + if (clickCount % 3 === 2) { + return [ + textPos - text.substr(0, pos).match(/(\w+|\s+|\W)?$/)[0].length, + pos === undefined ? pos : pos + text.substr(pos).match(/^(\w+|\s+|\W)?/)[0].length + ]; + } + // triple click + return [ + textPos - text.substr(0, pos).match(/[^\r\n]*$/)[0].length, + pos === undefined ? pos : pos + text.substr(pos).match(/^[^\r\n]*/)[0].length + ]; +} + +export { setSelectionPerMouseDown }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/setSelectionRange.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/setSelectionRange.js new file mode 100644 index 0000000000000000000000000000000000000000..d45166ce682dd26f0fa36b3df5b15f158d3cd318 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/setSelectionRange.js @@ -0,0 +1,29 @@ +import '../../utils/dataTransfer/Clipboard.js'; +import { isContentEditable } from '../../utils/edit/isContentEditable.js'; +import { hasOwnSelection } from '../../utils/focus/selection.js'; +import { setSelection } from './setSelection.js'; + +/** + * Backward-compatible selection. + * + * Handles input elements and contenteditable if it only contains a single text node. + */ function setSelectionRange(element, anchorOffset, focusOffset) { + var _element_firstChild; + if (hasOwnSelection(element)) { + return setSelection({ + focusNode: element, + anchorOffset, + focusOffset + }); + } + /* istanbul ignore else */ if (isContentEditable(element) && ((_element_firstChild = element.firstChild) === null || _element_firstChild === undefined ? undefined : _element_firstChild.nodeType) === 3) { + return setSelection({ + focusNode: element.firstChild, + anchorOffset, + focusOffset + }); + } + /* istanbul ignore next */ throw new Error('Not implemented. The result of this interaction is unreliable.'); +} + +export { setSelectionRange }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/updateSelectionOnFocus.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/updateSelectionOnFocus.js new file mode 100644 index 0000000000000000000000000000000000000000..7e10587c78ab95bf1ede9de1613bcdce0fe14c53 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/selection/updateSelectionOnFocus.js @@ -0,0 +1,38 @@ +import '../../utils/dataTransfer/Clipboard.js'; +import { getContentEditable } from '../../utils/edit/isContentEditable.js'; +import { hasOwnSelection } from '../../utils/focus/selection.js'; + +// The browser implementation seems to have changed. +// When focus is inside , +// Chrome updates Selection to be collapsed at the position of the input element. +// TODO: update implementation to match that of current browsers +/** + * Reset the Document Selection when moving focus into an element + * with own selection implementation. + */ function updateSelectionOnFocus(element) { + const selection = element.ownerDocument.getSelection(); + /* istanbul ignore if */ if (!(selection === null || selection === undefined ? undefined : selection.focusNode)) { + return; + } + // If the focus moves inside an element with own selection implementation, + // the document selection will be this element. + // But if the focused element is inside a contenteditable, + // 1) a collapsed selection will be retained. + // 2) other selections will be replaced by a cursor + // 2.a) at the start of the first child if it is a text node + // 2.b) at the start of the contenteditable. + if (hasOwnSelection(element)) { + const contenteditable = getContentEditable(selection.focusNode); + if (contenteditable) { + if (!selection.isCollapsed) { + var _contenteditable_firstChild; + const focusNode = ((_contenteditable_firstChild = contenteditable.firstChild) === null || _contenteditable_firstChild === undefined ? undefined : _contenteditable_firstChild.nodeType) === 3 ? contenteditable.firstChild : contenteditable; + selection.setBaseAndExtent(focusNode, 0, focusNode, 0); + } + } else { + selection.setBaseAndExtent(element, 0, element, 0); + } + } +} + +export { updateSelectionOnFocus }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/types.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/types.js new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/types.js @@ -0,0 +1 @@ + diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/wrapEvent.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/wrapEvent.js new file mode 100644 index 0000000000000000000000000000000000000000..e2ad93e1379462461263cca7b59547a8eba8e781 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/event/wrapEvent.js @@ -0,0 +1,7 @@ +import { getConfig } from '@testing-library/dom'; + +function wrapEvent(cb, _element) { + return getConfig().eventWrapper(cb); +} + +export { wrapEvent }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fe2f41f26469a8404d8c17b65971b266adfc9295 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/index.js @@ -0,0 +1,2 @@ +export { userEvent as default, userEvent } from './setup/index.js'; +export { PointerEventsCheckLevel } from './options.js'; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/keyboard/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/keyboard/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9c9feb7b82aabeadd8acbd9ec8f4127e302a4634 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/keyboard/index.js @@ -0,0 +1,37 @@ +import '../utils/dataTransfer/Clipboard.js'; +import { wait } from '../utils/misc/wait.js'; +import { parseKeyDef } from './parseKeyDef.js'; + +async function keyboard(text) { + const actions = parseKeyDef(this.config.keyboardMap, text); + for(let i = 0; i < actions.length; i++){ + await wait(this.config); + await keyboardAction(this, actions[i]); + } +} +async function keyboardAction(instance, { keyDef, releasePrevious, releaseSelf, repeat }) { + const { system } = instance; + // Release the key automatically if it was pressed before. + if (system.keyboard.isKeyPressed(keyDef)) { + await system.keyboard.keyup(instance, keyDef); + } + if (!releasePrevious) { + for(let i = 1; i <= repeat; i++){ + await system.keyboard.keydown(instance, keyDef); + if (i < repeat) { + await wait(instance.config); + } + } + // Release the key only on the last iteration on `state.repeatKey`. + if (releaseSelf) { + await system.keyboard.keyup(instance, keyDef); + } + } +} +async function releaseAllKeys(instance) { + for (const k of instance.system.keyboard.getPressedKeys()){ + await instance.system.keyboard.keyup(instance, k); + } +} + +export { keyboard, releaseAllKeys }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/keyboard/keyMap.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/keyboard/keyMap.js new file mode 100644 index 0000000000000000000000000000000000000000..78d7c7cfe0c1d6c4051f5a44bd93e314f1851bab --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/keyboard/keyMap.js @@ -0,0 +1,176 @@ +import { DOM_KEY_LOCATION } from '../system/keyboard.js'; + +/** + * Mapping for a default US-104-QWERTY keyboard + */ const defaultKeyMap = [ + // alphanumeric block - writing system + ...'0123456789'.split('').map((c)=>({ + code: `Digit${c}`, + key: c + })), + ...')!@#$%^&*('.split('').map((c, i)=>({ + code: `Digit${i}`, + key: c, + shiftKey: true + })), + ...'abcdefghijklmnopqrstuvwxyz'.split('').map((c)=>({ + code: `Key${c.toUpperCase()}`, + key: c + })), + ...'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('').map((c)=>({ + code: `Key${c}`, + key: c, + shiftKey: true + })), + { + code: 'BracketLeft', + key: '[' + }, + { + code: 'BracketLeft', + key: '{', + shiftKey: true + }, + { + code: 'BracketRight', + key: ']' + }, + { + code: 'BracketRight', + key: '}', + shiftKey: true + }, + // alphanumeric block - functional + { + code: 'Space', + key: ' ' + }, + { + code: 'AltLeft', + key: 'Alt', + location: DOM_KEY_LOCATION.LEFT + }, + { + code: 'AltRight', + key: 'Alt', + location: DOM_KEY_LOCATION.RIGHT + }, + { + code: 'ShiftLeft', + key: 'Shift', + location: DOM_KEY_LOCATION.LEFT + }, + { + code: 'ShiftRight', + key: 'Shift', + location: DOM_KEY_LOCATION.RIGHT + }, + { + code: 'ControlLeft', + key: 'Control', + location: DOM_KEY_LOCATION.LEFT + }, + { + code: 'ControlRight', + key: 'Control', + location: DOM_KEY_LOCATION.RIGHT + }, + { + code: 'MetaLeft', + key: 'Meta', + location: DOM_KEY_LOCATION.LEFT + }, + { + code: 'MetaRight', + key: 'Meta', + location: DOM_KEY_LOCATION.RIGHT + }, + { + code: 'OSLeft', + key: 'OS', + location: DOM_KEY_LOCATION.LEFT + }, + { + code: 'OSRight', + key: 'OS', + location: DOM_KEY_LOCATION.RIGHT + }, + { + code: 'ContextMenu', + key: 'ContextMenu' + }, + { + code: 'Tab', + key: 'Tab' + }, + { + code: 'CapsLock', + key: 'CapsLock' + }, + { + code: 'Backspace', + key: 'Backspace' + }, + { + code: 'Enter', + key: 'Enter' + }, + // function + { + code: 'Escape', + key: 'Escape' + }, + // arrows + { + code: 'ArrowUp', + key: 'ArrowUp' + }, + { + code: 'ArrowDown', + key: 'ArrowDown' + }, + { + code: 'ArrowLeft', + key: 'ArrowLeft' + }, + { + code: 'ArrowRight', + key: 'ArrowRight' + }, + // control pad + { + code: 'Home', + key: 'Home' + }, + { + code: 'End', + key: 'End' + }, + { + code: 'Delete', + key: 'Delete' + }, + { + code: 'PageUp', + key: 'PageUp' + }, + { + code: 'PageDown', + key: 'PageDown' + }, + // Special keys that are not part of a default US-layout but included for specific behavior + { + code: 'Fn', + key: 'Fn' + }, + { + code: 'Symbol', + key: 'Symbol' + }, + { + code: 'AltRight', + key: 'AltGraph' + } +]; + +export { defaultKeyMap }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/keyboard/parseKeyDef.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/keyboard/parseKeyDef.js new file mode 100644 index 0000000000000000000000000000000000000000..850da1b3dcc29f19db2e26dbfc401ea63bedbcc3 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/keyboard/parseKeyDef.js @@ -0,0 +1,43 @@ +import '../utils/dataTransfer/Clipboard.js'; +import { readNextDescriptor } from '../utils/keyDef/readNextDescriptor.js'; + +/** + * Parse key definitions per `keyboardMap` + * + * Keys can be referenced by `{key}` or `{special}` as well as physical locations per `[code]`. + * Everything else will be interpreted as a typed character - e.g. `a`. + * Brackets `{` and `[` can be escaped by doubling - e.g. `foo[[bar` translates to `foo[bar`. + * Keeping the key pressed can be written as `{key>}`. + * When keeping the key pressed you can choose how long (how many keydown and keypress) the key is pressed `{key>3}`. + * You can then release the key per `{key>3/}` or keep it pressed and continue with the next key. + */ function parseKeyDef(keyboardMap, text) { + const defs = []; + do { + const { type, descriptor, consumedLength, releasePrevious, releaseSelf = true, repeat } = readNextDescriptor(text, 'keyboard'); + var _keyboardMap_find; + const keyDef = (_keyboardMap_find = keyboardMap.find((def)=>{ + if (type === '[') { + var _def_code; + return ((_def_code = def.code) === null || _def_code === undefined ? undefined : _def_code.toLowerCase()) === descriptor.toLowerCase(); + } else if (type === '{') { + var _def_key; + return ((_def_key = def.key) === null || _def_key === undefined ? undefined : _def_key.toLowerCase()) === descriptor.toLowerCase(); + } + return def.key === descriptor; + })) !== null && _keyboardMap_find !== undefined ? _keyboardMap_find : { + key: 'Unknown', + code: 'Unknown', + [type === '[' ? 'code' : 'key']: descriptor + }; + defs.push({ + keyDef, + releasePrevious, + releaseSelf, + repeat + }); + text = text.slice(consumedLength); + }while (text) + return defs; +} + +export { parseKeyDef }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/options.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/options.js new file mode 100644 index 0000000000000000000000000000000000000000..a85a784c186ee6870030b08afd1c7a2d4503c280 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/options.js @@ -0,0 +1,12 @@ +var PointerEventsCheckLevel = /*#__PURE__*/ function(PointerEventsCheckLevel) { + /** + * Check pointer events on every user interaction that triggers a bunch of events. + * E.g. once for releasing a mouse button even though this triggers `pointerup`, `mouseup`, `click`, etc... + */ PointerEventsCheckLevel[PointerEventsCheckLevel["EachTrigger"] = 4] = "EachTrigger"; + /** Check each target once per call to pointer (related) API */ PointerEventsCheckLevel[PointerEventsCheckLevel["EachApiCall"] = 2] = "EachApiCall"; + /** Check each event target once */ PointerEventsCheckLevel[PointerEventsCheckLevel["EachTarget"] = 1] = "EachTarget"; + /** No pointer events check */ PointerEventsCheckLevel[PointerEventsCheckLevel["Never"] = 0] = "Never"; + return PointerEventsCheckLevel; +}({}); + +export { PointerEventsCheckLevel }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/package.json b/tools/ui/node_modules/@testing-library/user-event/dist/esm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..aead43de364cd1cc107d5fc3a4ea6fea7d7bd01c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/pointer/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/pointer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5860a0ad42330421a734a4edfb09a3988a1a3a08 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/pointer/index.js @@ -0,0 +1,72 @@ +import '../utils/dataTransfer/Clipboard.js'; +import { setLevelRef, ApiLevel } from '../utils/misc/level.js'; +import { wait } from '../utils/misc/wait.js'; +import { parseKeyDef } from './parseKeyDef.js'; + +async function pointer(input) { + const { pointerMap } = this.config; + const actions = []; + (Array.isArray(input) ? input : [ + input + ]).forEach((actionInput)=>{ + if (typeof actionInput === 'string') { + actions.push(...parseKeyDef(pointerMap, actionInput)); + } else if ('keys' in actionInput) { + actions.push(...parseKeyDef(pointerMap, actionInput.keys).map((i)=>({ + ...actionInput, + ...i + }))); + } else { + actions.push(actionInput); + } + }); + for(let i = 0; i < actions.length; i++){ + await wait(this.config); + await pointerAction(this, actions[i]); + } + this.system.pointer.resetClickCount(); +} +async function pointerAction(instance, action) { + var _previousPosition_caret, _previousPosition_caret1; + const pointerName = 'pointerName' in action && action.pointerName ? action.pointerName : 'keyDef' in action ? instance.system.pointer.getPointerName(action.keyDef) : 'mouse'; + const previousPosition = instance.system.pointer.getPreviousPosition(pointerName); + var _action_target, _action_coords, _action_node, _action_offset; + const position = { + target: (_action_target = action.target) !== null && _action_target !== undefined ? _action_target : getPrevTarget(instance, previousPosition), + coords: (_action_coords = action.coords) !== null && _action_coords !== undefined ? _action_coords : previousPosition === null || previousPosition === undefined ? undefined : previousPosition.coords, + caret: { + node: (_action_node = action.node) !== null && _action_node !== undefined ? _action_node : hasCaretPosition(action) ? undefined : previousPosition === null || previousPosition === undefined ? undefined : (_previousPosition_caret = previousPosition.caret) === null || _previousPosition_caret === undefined ? undefined : _previousPosition_caret.node, + offset: (_action_offset = action.offset) !== null && _action_offset !== undefined ? _action_offset : hasCaretPosition(action) ? undefined : previousPosition === null || previousPosition === undefined ? undefined : (_previousPosition_caret1 = previousPosition.caret) === null || _previousPosition_caret1 === undefined ? undefined : _previousPosition_caret1.offset + } + }; + if ('keyDef' in action) { + if (instance.system.pointer.isKeyPressed(action.keyDef)) { + setLevelRef(instance, ApiLevel.Trigger); + await instance.system.pointer.release(instance, action.keyDef, position); + } + if (!action.releasePrevious) { + setLevelRef(instance, ApiLevel.Trigger); + await instance.system.pointer.press(instance, action.keyDef, position); + if (action.releaseSelf) { + setLevelRef(instance, ApiLevel.Trigger); + await instance.system.pointer.release(instance, action.keyDef, position); + } + } + } else { + setLevelRef(instance, ApiLevel.Trigger); + await instance.system.pointer.move(instance, pointerName, position); + } +} +function hasCaretPosition(action) { + var _action_target, _ref; + return !!((_ref = (_action_target = action.target) !== null && _action_target !== undefined ? _action_target : action.node) !== null && _ref !== undefined ? _ref : action.offset !== undefined); +} +function getPrevTarget(instance, position) { + if (!position) { + throw new Error('This pointer has no previous position. Provide a target property!'); + } + var _position_target; + return (_position_target = position.target) !== null && _position_target !== undefined ? _position_target : instance.config.document.body; +} + +export { pointer }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/pointer/keyMap.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/pointer/keyMap.js new file mode 100644 index 0000000000000000000000000000000000000000..6ab75e2c6bb094f6e0f3afa9da24902963858751 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/pointer/keyMap.js @@ -0,0 +1,31 @@ +const defaultKeyMap = [ + { + name: 'MouseLeft', + pointerType: 'mouse', + button: 'primary' + }, + { + name: 'MouseRight', + pointerType: 'mouse', + button: 'secondary' + }, + { + name: 'MouseMiddle', + pointerType: 'mouse', + button: 'auxiliary' + }, + { + name: 'TouchA', + pointerType: 'touch' + }, + { + name: 'TouchB', + pointerType: 'touch' + }, + { + name: 'TouchC', + pointerType: 'touch' + } +]; + +export { defaultKeyMap }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/pointer/parseKeyDef.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/pointer/parseKeyDef.js new file mode 100644 index 0000000000000000000000000000000000000000..bb95365c1c07392ecc3f101a6b07b2348c18ca46 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/pointer/parseKeyDef.js @@ -0,0 +1,21 @@ +import '../utils/dataTransfer/Clipboard.js'; +import { readNextDescriptor } from '../utils/keyDef/readNextDescriptor.js'; + +function parseKeyDef(pointerMap, keys) { + const defs = []; + do { + const { descriptor, consumedLength, releasePrevious, releaseSelf = true } = readNextDescriptor(keys, 'pointer'); + const keyDef = pointerMap.find((p)=>p.name === descriptor); + if (keyDef) { + defs.push({ + keyDef, + releasePrevious, + releaseSelf + }); + } + keys = keys.slice(consumedLength); + }while (keys) + return defs; +} + +export { parseKeyDef }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/setup/api.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/setup/api.js new file mode 100644 index 0000000000000000000000000000000000000000..1e71de8d3609962d2988c08f7a75f2da2eab2150 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/setup/api.js @@ -0,0 +1,33 @@ +import { click, dblClick, tripleClick } from '../convenience/click.js'; +import { hover, unhover } from '../convenience/hover.js'; +import { tab } from '../convenience/tab.js'; +import { keyboard } from '../keyboard/index.js'; +import { copy } from '../clipboard/copy.js'; +import { cut } from '../clipboard/cut.js'; +import { paste } from '../clipboard/paste.js'; +import { pointer } from '../pointer/index.js'; +import { clear } from '../utility/clear.js'; +import { deselectOptions, selectOptions } from '../utility/selectOptions.js'; +import { type } from '../utility/type.js'; +import { upload } from '../utility/upload.js'; + +const userEventApi = { + click, + dblClick, + tripleClick, + hover, + unhover, + tab, + keyboard, + copy, + cut, + paste, + pointer, + clear, + deselectOptions, + selectOptions, + type, + upload +}; + +export { userEventApi }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/setup/directApi.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/setup/directApi.js new file mode 100644 index 0000000000000000000000000000000000000000..a1eb427538605ce884b1cdf0d188ceffc15e1a04 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/setup/directApi.js @@ -0,0 +1,58 @@ +import { setupDirect } from './setup.js'; + +function clear(element) { + return setupDirect().api.clear(element); +} +function click(element, options = {}) { + return setupDirect(options, element).api.click(element); +} +function copy(options = {}) { + return setupDirect(options).api.copy(); +} +function cut(options = {}) { + return setupDirect(options).api.cut(); +} +function dblClick(element, options = {}) { + return setupDirect(options).api.dblClick(element); +} +function deselectOptions(select, values, options = {}) { + return setupDirect(options).api.deselectOptions(select, values); +} +function hover(element, options = {}) { + return setupDirect(options).api.hover(element); +} +async function keyboard(text, options = {}) { + const { api, system } = setupDirect(options); + return api.keyboard(text).then(()=>system); +} +async function pointer(input, options = {}) { + const { api, system } = setupDirect(options); + return api.pointer(input).then(()=>system); +} +function paste(clipboardData, options) { + return setupDirect(options).api.paste(clipboardData); +} +function selectOptions(select, values, options = {}) { + return setupDirect(options).api.selectOptions(select, values); +} +function tripleClick(element, options = {}) { + return setupDirect(options).api.tripleClick(element); +} +function type(element, text, options = {}) { + return setupDirect(options, element).api.type(element, text, options); +} +function unhover(element, options = {}) { + const { api, system } = setupDirect(options); + system.pointer.setMousePosition({ + target: element + }); + return api.unhover(element); +} +function upload(element, fileOrFiles, options = {}) { + return setupDirect(options).api.upload(element, fileOrFiles); +} +function tab(options = {}) { + return setupDirect().api.tab(options); +} + +export { clear, click, copy, cut, dblClick, deselectOptions, hover, keyboard, paste, pointer, selectOptions, tab, tripleClick, type, unhover, upload }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/setup/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/setup/index.js new file mode 100644 index 0000000000000000000000000000000000000000..884e0a968006686f01e5a3d623bafd15903ad588 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/setup/index.js @@ -0,0 +1,9 @@ +import { setupMain } from './setup.js'; +import * as directApi from './directApi.js'; + +const userEvent = { + ...directApi, + setup: setupMain +}; + +export { userEvent }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/setup/setup.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/setup/setup.js new file mode 100644 index 0000000000000000000000000000000000000000..bb8031fbaaf4712c46fce3549892dfeca92bc71c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/setup/setup.js @@ -0,0 +1,119 @@ +import { patchFocus } from '../document/patchFocus.js'; +import { prepareDocument } from '../document/prepareDocument.js'; +import { dispatchEvent, dispatchUIEvent } from '../event/dispatchEvent.js'; +import { attachClipboardStubToView } from '../utils/dataTransfer/Clipboard.js'; +import { getWindow } from '../utils/misc/getWindow.js'; +import { getDocumentFromNode } from '../utils/misc/getDocumentFromNode.js'; +import { setLevelRef, ApiLevel } from '../utils/misc/level.js'; +import { wait } from '../utils/misc/wait.js'; +import { PointerEventsCheckLevel } from '../options.js'; +import '@testing-library/dom'; +import { defaultKeyMap } from '../keyboard/keyMap.js'; +import { defaultKeyMap as defaultKeyMap$1 } from '../pointer/keyMap.js'; +import { System } from '../system/index.js'; +import { userEventApi } from './api.js'; +import { wrapAsync } from './wrapAsync.js'; + +/** + * Default options applied when API is called per `userEvent.anyApi()` + */ const defaultOptionsDirect = { + applyAccept: true, + autoModify: true, + delay: 0, + document: globalThis.document, + keyboardMap: defaultKeyMap, + pointerMap: defaultKeyMap$1, + pointerEventsCheck: PointerEventsCheckLevel.EachApiCall, + skipAutoClose: false, + skipClick: false, + skipHover: false, + writeToClipboard: false, + advanceTimers: ()=>Promise.resolve() +}; +/** + * Default options applied when API is called per `userEvent().anyApi()` + */ const defaultOptionsSetup = { + ...defaultOptionsDirect, + writeToClipboard: true +}; +function createConfig(options = {}, defaults = defaultOptionsSetup, node) { + const document = getDocument(options, node, defaults); + return { + ...defaults, + ...options, + document + }; +} +/** + * Start a "session" with userEvent. + * All APIs returned by this function share an input device state and a default configuration. + */ function setupMain(options = {}) { + const config = createConfig(options); + prepareDocument(config.document); + patchFocus(getWindow(config.document).HTMLElement); + var _config_document_defaultView; + const view = (_config_document_defaultView = config.document.defaultView) !== null && _config_document_defaultView !== undefined ? _config_document_defaultView : /* istanbul ignore next */ globalThis.window; + attachClipboardStubToView(view); + return createInstance(config).api; +} +/** + * Setup in direct call per `userEvent.anyApi()` + */ function setupDirect({ keyboardState, pointerState, ...options } = {}, node) { + const config = createConfig(options, defaultOptionsDirect, node); + prepareDocument(config.document); + patchFocus(getWindow(config.document).HTMLElement); + var _ref; + const system = (_ref = pointerState !== null && pointerState !== undefined ? pointerState : keyboardState) !== null && _ref !== undefined ? _ref : new System(); + return { + api: createInstance(config, system).api, + system + }; +} +/** + * Create a set of callbacks with different default settings but the same state. + */ function setupSub(options) { + return createInstance({ + ...this.config, + ...options + }, this.system).api; +} +function wrapAndBindImpl(instance, impl) { + function method(...args) { + setLevelRef(instance, ApiLevel.Call); + return wrapAsync(()=>impl.apply(instance, args).then(async (ret)=>{ + await wait(instance.config); + return ret; + })); + } + Object.defineProperty(method, 'name', { + get: ()=>impl.name + }); + return method; +} +function createInstance(config, system = new System()) { + const instance = {}; + Object.assign(instance, { + config, + dispatchEvent: dispatchEvent.bind(instance), + dispatchUIEvent: dispatchUIEvent.bind(instance), + system, + levelRefs: {}, + ...userEventApi + }); + return { + instance, + api: { + ...Object.fromEntries(Object.entries(userEventApi).map(([name, api])=>[ + name, + wrapAndBindImpl(instance, api) + ])), + setup: setupSub.bind(instance) + } + }; +} +function getDocument(options, node, defaults) { + var _options_document, _ref; + return (_ref = (_options_document = options.document) !== null && _options_document !== undefined ? _options_document : node && getDocumentFromNode(node)) !== null && _ref !== undefined ? _ref : defaults.document; +} + +export { createConfig, createInstance, setupDirect, setupMain, setupSub }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/setup/wrapAsync.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/setup/wrapAsync.js new file mode 100644 index 0000000000000000000000000000000000000000..b56e4070a99142c52ff974be12f41bf3672194ef --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/setup/wrapAsync.js @@ -0,0 +1,9 @@ +import { getConfig } from '@testing-library/dom'; + +/** + * Wrap an internal Promise + */ function wrapAsync(implementation) { + return getConfig().asyncWrapper(implementation); +} + +export { wrapAsync }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/index.js new file mode 100644 index 0000000000000000000000000000000000000000..70f9896d0a4417c948f0cc4444972ca5e8e301b0 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/index.js @@ -0,0 +1,42 @@ +import { KeyboardHost } from './keyboard.js'; +import { PointerHost } from './pointer/index.js'; + +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +/** + * @internal Do not create/alter this by yourself as this type might be subject to changes. + */ class System { + getUIEventModifiers() { + return { + altKey: this.keyboard.modifiers.Alt, + ctrlKey: this.keyboard.modifiers.Control, + metaKey: this.keyboard.modifiers.Meta, + shiftKey: this.keyboard.modifiers.Shift, + modifierAltGraph: this.keyboard.modifiers.AltGraph, + modifierCapsLock: this.keyboard.modifiers.CapsLock, + modifierFn: this.keyboard.modifiers.Fn, + modifierFnLock: this.keyboard.modifiers.FnLock, + modifierNumLock: this.keyboard.modifiers.NumLock, + modifierScrollLock: this.keyboard.modifiers.ScrollLock, + modifierSymbol: this.keyboard.modifiers.Symbol, + modifierSymbolLock: this.keyboard.modifiers.SymbolLock + }; + } + constructor(){ + _define_property(this, "keyboard", new KeyboardHost(this)); + _define_property(this, "pointer", new PointerHost(this)); + } +} + +export { System }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/keyboard.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/keyboard.js new file mode 100644 index 0000000000000000000000000000000000000000..43700ca3a873aa6eb1cb4553c0889b685ff90fff --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/keyboard.js @@ -0,0 +1,166 @@ +import '../utils/dataTransfer/Clipboard.js'; +import { getActiveElementOrBody } from '../utils/focus/getActiveElement.js'; + +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +var DOM_KEY_LOCATION = /*#__PURE__*/ function(DOM_KEY_LOCATION) { + DOM_KEY_LOCATION[DOM_KEY_LOCATION["STANDARD"] = 0] = "STANDARD"; + DOM_KEY_LOCATION[DOM_KEY_LOCATION["LEFT"] = 1] = "LEFT"; + DOM_KEY_LOCATION[DOM_KEY_LOCATION["RIGHT"] = 2] = "RIGHT"; + DOM_KEY_LOCATION[DOM_KEY_LOCATION["NUMPAD"] = 3] = "NUMPAD"; + return DOM_KEY_LOCATION; +}({}); +const modifierKeys = [ + 'Alt', + 'AltGraph', + 'Control', + 'Fn', + 'Meta', + 'Shift', + 'Symbol' +]; +function isModifierKey(key) { + return modifierKeys.includes(key); +} +const modifierLocks = [ + 'CapsLock', + 'FnLock', + 'NumLock', + 'ScrollLock', + 'SymbolLock' +]; +function isModifierLock(key) { + return modifierLocks.includes(key); +} +class KeyboardHost { + isKeyPressed(keyDef) { + return this.pressed.has(String(keyDef.code)); + } + getPressedKeys() { + return this.pressed.values().map((p)=>p.keyDef); + } + /** Press a key */ async keydown(instance, keyDef) { + const key = String(keyDef.key); + const code = String(keyDef.code); + const target = getActiveElementOrBody(instance.config.document); + this.setKeydownTarget(target); + this.pressed.add(code, keyDef); + if (isModifierKey(key)) { + this.modifiers[key] = true; + } + const unprevented = instance.dispatchUIEvent(target, 'keydown', { + key, + code + }); + if (isModifierLock(key) && !this.modifiers[key]) { + this.modifiers[key] = true; + this.modifierLockStart[key] = true; + } + if (unprevented) { + this.pressed.setUnprevented(code); + } + if (unprevented && this.hasKeyPress(key)) { + instance.dispatchUIEvent(getActiveElementOrBody(instance.config.document), 'keypress', { + key, + code, + charCode: keyDef.key === 'Enter' ? 13 : String(keyDef.key).charCodeAt(0) + }); + } + } + /** Release a key */ async keyup(instance, keyDef) { + const key = String(keyDef.key); + const code = String(keyDef.code); + const unprevented = this.pressed.isUnprevented(code); + this.pressed.delete(code); + if (isModifierKey(key) && !this.pressed.values().find((p)=>p.keyDef.key === key)) { + this.modifiers[key] = false; + } + instance.dispatchUIEvent(getActiveElementOrBody(instance.config.document), 'keyup', { + key, + code + }, !unprevented); + if (isModifierLock(key) && this.modifiers[key]) { + if (this.modifierLockStart[key]) { + this.modifierLockStart[key] = false; + } else { + this.modifiers[key] = false; + } + } + } + setKeydownTarget(target) { + if (target !== this.lastKeydownTarget) { + this.carryChar = ''; + } + this.lastKeydownTarget = target; + } + hasKeyPress(key) { + return (key.length === 1 || key === 'Enter') && !this.modifiers.Control && !this.modifiers.Alt; + } + constructor(system){ + _define_property(this, "system", undefined); + _define_property(this, "modifiers", { + Alt: false, + AltGraph: false, + CapsLock: false, + Control: false, + Fn: false, + FnLock: false, + Meta: false, + NumLock: false, + ScrollLock: false, + Shift: false, + Symbol: false, + SymbolLock: false + }); + _define_property(this, "pressed", new class { + add(code, keyDef) { + var _this_registry, _code; + var _; + (_ = (_this_registry = this.registry)[_code = code]) !== null && _ !== undefined ? _ : _this_registry[_code] = { + keyDef, + unpreventedDefault: false + }; + } + has(code) { + return !!this.registry[code]; + } + setUnprevented(code) { + const o = this.registry[code]; + if (o) { + o.unpreventedDefault = true; + } + } + isUnprevented(code) { + var _this_registry_code; + return !!((_this_registry_code = this.registry[code]) === null || _this_registry_code === undefined ? undefined : _this_registry_code.unpreventedDefault); + } + delete(code) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this.registry[code]; + } + values() { + return Object.values(this.registry); + } + constructor(){ + _define_property(this, "registry", {}); + } + }()); + _define_property(this, "carryChar", ''); + _define_property(this, "lastKeydownTarget", undefined); + _define_property(this, "modifierLockStart", {}); + this.system = system; + } +} + +export { DOM_KEY_LOCATION, KeyboardHost }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/buttons.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/buttons.js new file mode 100644 index 0000000000000000000000000000000000000000..4570e395a7cd10e76b96962e8778ac3e98a7d0be --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/buttons.js @@ -0,0 +1,78 @@ +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +class Buttons { + getButtons() { + let v = 0; + for (const button of Object.keys(this.pressed)){ + // eslint-disable-next-line no-bitwise + v |= 2 ** Number(button); + } + return v; + } + down(keyDef) { + const button = getMouseButtonId(keyDef.button); + if (button in this.pressed) { + this.pressed[button].push(keyDef); + return undefined; + } + this.pressed[button] = [ + keyDef + ]; + return button; + } + up(keyDef) { + const button = getMouseButtonId(keyDef.button); + if (button in this.pressed) { + this.pressed[button] = this.pressed[button].filter((k)=>k.name !== keyDef.name); + if (this.pressed[button].length === 0) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this.pressed[button]; + return button; + } + } + return undefined; + } + constructor(){ + _define_property(this, "pressed", {}); + } +} +const MouseButton = { + primary: 0, + secondary: 1, + auxiliary: 2, + back: 3, + X1: 3, + forward: 4, + X2: 4 +}; +function getMouseButtonId(button = 0) { + if (button in MouseButton) { + return MouseButton[button]; + } + return Number(button); +} +// On the `MouseEvent.button` property auxiliary and secondary button are flipped compared to `MouseEvent.buttons`. +const MouseButtonFlip = { + 1: 2, + 2: 1 +}; +function getMouseEventButton(button) { + button = getMouseButtonId(button); + if (button in MouseButtonFlip) { + return MouseButtonFlip[button]; + } + return button; +} + +export { Buttons, MouseButton, MouseButtonFlip, getMouseButtonId, getMouseEventButton }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/device.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/device.js new file mode 100644 index 0000000000000000000000000000000000000000..51f4c491ac998040ebf7a589a0ecdda8ae51dc4c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/device.js @@ -0,0 +1,32 @@ +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +class Device { + get countPressed() { + return this.pressedKeys.size; + } + isPressed(keyDef) { + return this.pressedKeys.has(keyDef.name); + } + addPressed(keyDef) { + return this.pressedKeys.add(keyDef.name); + } + removePressed(keyDef) { + return this.pressedKeys.delete(keyDef.name); + } + constructor(){ + _define_property(this, "pressedKeys", new Set()); + } +} + +export { Device }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..cc1605b88ce57a23406a5a70eec82b3735fa7d89 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/index.js @@ -0,0 +1,157 @@ +import { Buttons } from './buttons.js'; +import { Device } from './device.js'; +import { Mouse } from './mouse.js'; +import { Pointer } from './pointer.js'; + +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +class PointerHost { + isKeyPressed(keyDef) { + return this.devices.get(keyDef.pointerType).isPressed(keyDef); + } + async press(instance, keyDef, position) { + this.devices.get(keyDef.pointerType).addPressed(keyDef); + this.buttons.down(keyDef); + const pointerName = this.getPointerName(keyDef); + const pointer = keyDef.pointerType === 'touch' ? this.pointers.new(pointerName, keyDef.pointerType, this.buttons) : this.pointers.get(pointerName); + // TODO: deprecate the following implicit setting of position + pointer.position = position; + if (pointer.pointerType !== 'touch') { + this.mouse.position = position; + } + if (pointer.pointerType === 'touch') { + pointer.init(instance); + } + pointer.down(instance, keyDef.button); + if (pointer.pointerType !== 'touch') { + this.mouse.down(instance, keyDef, pointer.isPrevented); + } + } + async move(instance, pointerName, position) { + const pointer = this.pointers.get(pointerName); + // In (some?) browsers this order of events can be observed. + // This interweaving of events is probably unnecessary. + // While the order of mouse (or pointer) events is defined per spec, + // the order in which they interweave/follow on a user interaction depends on the implementation. + const pointermove = pointer.move(instance, position); + const mousemove = pointer.pointerType === 'touch' ? undefined : this.mouse.move(instance, position, pointer.isPrevented); + pointermove === null || pointermove === undefined ? undefined : pointermove.leave(); + mousemove === null || mousemove === undefined ? undefined : mousemove.leave(); + pointermove === null || pointermove === undefined ? undefined : pointermove.enter(); + mousemove === null || mousemove === undefined ? undefined : mousemove.enter(); + pointermove === null || pointermove === undefined ? undefined : pointermove.move(); + mousemove === null || mousemove === undefined ? undefined : mousemove.move(); + } + async release(instance, keyDef, position) { + const device = this.devices.get(keyDef.pointerType); + device.removePressed(keyDef); + this.buttons.up(keyDef); + const pointer = this.pointers.get(this.getPointerName(keyDef)); + const isPrevented = pointer.isPrevented; + // TODO: deprecate the following implicit setting of position + pointer.position = position; + if (pointer.pointerType !== 'touch') { + this.mouse.position = position; + } + if (device.countPressed === 0) { + pointer.up(instance, keyDef.button); + } + if (pointer.pointerType === 'touch') { + pointer.release(instance); + } + if (pointer.pointerType === 'touch' && !pointer.isMultitouch) { + const mousemove = this.mouse.move(instance, position, isPrevented); + mousemove === null || mousemove === undefined ? undefined : mousemove.leave(); + mousemove === null || mousemove === undefined ? undefined : mousemove.enter(); + mousemove === null || mousemove === undefined ? undefined : mousemove.move(); + this.mouse.down(instance, keyDef, isPrevented); + } + if (!pointer.isMultitouch) { + const mousemove = this.mouse.move(instance, position, isPrevented); + mousemove === null || mousemove === undefined ? undefined : mousemove.leave(); + mousemove === null || mousemove === undefined ? undefined : mousemove.enter(); + mousemove === null || mousemove === undefined ? undefined : mousemove.move(); + this.mouse.up(instance, keyDef, isPrevented); + } + } + getPointerName(keyDef) { + return keyDef.pointerType === 'touch' ? keyDef.name : keyDef.pointerType; + } + getPreviousPosition(pointerName) { + return this.pointers.has(pointerName) ? this.pointers.get(pointerName).position : undefined; + } + resetClickCount() { + this.mouse.resetClickCount(); + } + getMouseTarget(instance) { + var _this_mouse_position_target; + return (_this_mouse_position_target = this.mouse.position.target) !== null && _this_mouse_position_target !== undefined ? _this_mouse_position_target : instance.config.document.body; + } + setMousePosition(position) { + this.mouse.position = position; + this.pointers.get('mouse').position = position; + } + constructor(system){ + _define_property(this, "system", undefined); + _define_property(this, "mouse", undefined); + _define_property(this, "buttons", undefined); + _define_property(this, "devices", new class { + get(k) { + var _this_registry, _k; + var _; + return (_ = (_this_registry = this.registry)[_k = k]) !== null && _ !== undefined ? _ : _this_registry[_k] = new Device(); + } + constructor(){ + _define_property(this, "registry", {}); + } + }()); + _define_property(this, "pointers", new class { + new(pointerName, pointerType, buttons) { + const isPrimary = pointerType !== 'touch' || !Object.values(this.registry).some((p)=>p.pointerType === 'touch' && !p.isCancelled); + if (!isPrimary) { + Object.values(this.registry).forEach((p)=>{ + if (p.pointerType === pointerType && !p.isCancelled) { + p.isMultitouch = true; + } + }); + } + this.registry[pointerName] = new Pointer({ + pointerId: this.nextId++, + pointerType, + isPrimary + }, buttons); + return this.registry[pointerName]; + } + get(pointerName) { + if (!this.has(pointerName)) { + throw new Error(`Trying to access pointer "${pointerName}" which does not exist.`); + } + return this.registry[pointerName]; + } + has(pointerName) { + return pointerName in this.registry; + } + constructor(){ + _define_property(this, "registry", {}); + _define_property(this, "nextId", 1); + } + }()); + this.system = system; + this.buttons = new Buttons(); + this.mouse = new Mouse(); + this.pointers.new('mouse', 'mouse', this.buttons); + } +} + +export { PointerHost }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/mouse.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/mouse.js new file mode 100644 index 0000000000000000000000000000000000000000..b8a71065ef456e96a19aa0011f94447a4eac7893 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/mouse.js @@ -0,0 +1,205 @@ +import '../../event/behavior/click.js'; +import '../../event/behavior/cut.js'; +import '../../event/behavior/keydown.js'; +import '../../event/behavior/keypress.js'; +import '../../event/behavior/keyup.js'; +import '../../event/behavior/paste.js'; +import '@testing-library/dom'; +import '../../utils/dataTransfer/Clipboard.js'; +import { isDisabled } from '../../utils/misc/isDisabled.js'; +import { getTreeDiff } from '../../utils/misc/getTreeDiff.js'; +import { focusElement } from '../../event/focus.js'; +import { setSelectionPerMouseDown } from '../../event/selection/setSelectionPerMouse.js'; +import { modifySelectionPerMouseMove } from '../../event/selection/modifySelectionPerMouse.js'; +import { getMouseEventButton, Buttons } from './buttons.js'; +import { isDifferentPointerPosition } from './shared.js'; + +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +/** + * This object is the single "virtual" mouse that might be controlled by multiple different pointer devices. + */ class Mouse { + move(instance, position, /** Whether `preventDefault()` has been called on the `pointerdown` event */ isPrevented) { + const prevPosition = this.position; + const prevTarget = this.getTarget(instance); + this.position = position; + if (!isDifferentPointerPosition(prevPosition, position)) { + return; + } + const nextTarget = this.getTarget(instance); + const init = this.getEventInit('mousemove'); + const [leave, enter] = getTreeDiff(prevTarget, nextTarget); + return { + leave: ()=>{ + if (prevTarget !== nextTarget) { + instance.dispatchUIEvent(prevTarget, 'mouseout', init); + leave.forEach((el)=>instance.dispatchUIEvent(el, 'mouseleave', init)); + } + }, + enter: ()=>{ + if (prevTarget !== nextTarget) { + instance.dispatchUIEvent(nextTarget, 'mouseover', init); + enter.forEach((el)=>instance.dispatchUIEvent(el, 'mouseenter', init)); + } + }, + move: ()=>{ + if (isPrevented) { + return; + } + instance.dispatchUIEvent(nextTarget, 'mousemove', init); + this.modifySelecting(instance); + } + }; + } + down(instance, keyDef, /** Whether `preventDefault()` has been called on the `pointerdown` event */ isPrevented) { + const button = this.buttons.down(keyDef); + if (button === undefined) { + return; + } + const target = this.getTarget(instance); + this.buttonDownTarget[button] = target; + const init = this.getEventInit('mousedown', keyDef.button); + const disabled = isDisabled(target); + if (!isPrevented && (disabled || instance.dispatchUIEvent(target, 'mousedown', init))) { + this.startSelecting(instance, init.detail); + focusElement(target); + } + if (!disabled && getMouseEventButton(keyDef.button) === 2) { + instance.dispatchUIEvent(target, 'contextmenu', this.getEventInit('contextmenu', keyDef.button)); + } + } + up(instance, keyDef, /** Whether `preventDefault()` has been called on the `pointerdown` event */ isPrevented) { + const button = this.buttons.up(keyDef); + if (button === undefined) { + return; + } + const target = this.getTarget(instance); + if (!isDisabled(target)) { + if (!isPrevented) { + const mouseUpInit = this.getEventInit('mouseup', keyDef.button); + instance.dispatchUIEvent(target, 'mouseup', mouseUpInit); + this.endSelecting(); + } + const clickTarget = getTreeDiff(this.buttonDownTarget[button], target)[2][0]; + if (clickTarget) { + const init = this.getEventInit('click', keyDef.button); + if (init.detail) { + instance.dispatchUIEvent(clickTarget, init.button === 0 ? 'click' : 'auxclick', init); + if (init.button === 0 && init.detail === 2) { + instance.dispatchUIEvent(clickTarget, 'dblclick', { + ...this.getEventInit('dblclick', keyDef.button), + detail: init.detail + }); + } + } + } + } + } + resetClickCount() { + this.clickCount.reset(); + } + getEventInit(type, button) { + const init = { + ...this.position.coords + }; + init.button = getMouseEventButton(button); + init.buttons = this.buttons.getButtons(); + if (type === 'mousedown') { + init.detail = this.clickCount.getOnDown(init.button); + } else if (type === 'mouseup') { + init.detail = this.clickCount.getOnUp(init.button); + } else if (type === 'click' || type === 'auxclick') { + init.detail = this.clickCount.incOnClick(init.button); + } + return init; + } + getTarget(instance) { + var _this_position_target; + return (_this_position_target = this.position.target) !== null && _this_position_target !== undefined ? _this_position_target : instance.config.document.body; + } + startSelecting(instance, clickCount) { + var _this_position_caret, _this_position_caret1; + // TODO: support extending range (shift) + this.selecting = setSelectionPerMouseDown({ + document: instance.config.document, + target: this.getTarget(instance), + node: (_this_position_caret = this.position.caret) === null || _this_position_caret === undefined ? undefined : _this_position_caret.node, + offset: (_this_position_caret1 = this.position.caret) === null || _this_position_caret1 === undefined ? undefined : _this_position_caret1.offset, + clickCount + }); + } + modifySelecting(instance) { + var _this_position_caret, _this_position_caret1; + if (!this.selecting) { + return; + } + modifySelectionPerMouseMove(this.selecting, { + document: instance.config.document, + target: this.getTarget(instance), + node: (_this_position_caret = this.position.caret) === null || _this_position_caret === undefined ? undefined : _this_position_caret.node, + offset: (_this_position_caret1 = this.position.caret) === null || _this_position_caret1 === undefined ? undefined : _this_position_caret1.offset + }); + } + endSelecting() { + this.selecting = undefined; + } + constructor(){ + _define_property(this, "position", {}); + _define_property(this, "buttons", new Buttons()); + _define_property(this, "selecting", undefined); + _define_property(this, "buttonDownTarget", {}); + // According to spec the `detail` on click events should be the number + // of *consecutive* clicks with a specific button. + // On `mousedown` and `mouseup` it should be this number increased by one. + // But the browsers don't implement it this way. + // If another button is pressed, + // in Webkit: the `mouseup` on the previously pressed button has `detail: 0` and no `click`/`auxclick`. + // in Gecko: the `mouseup` and click events have the same detail as the `mousedown`. + // If there is a delay while a button is pressed, + // the `mouseup` and `click` are normal, but a following `mousedown` starts a new click count. + // We'll follow the minimal implementation of Webkit. + _define_property(this, "clickCount", new class { + incOnClick(button) { + const current = this.down[button] === undefined ? undefined : Number(this.down[button]) + 1; + this.count = this.count[button] === undefined ? {} : { + [button]: Number(this.count[button]) + 1 + }; + return current; + } + getOnDown(button) { + var _this_count_button; + this.down = { + [button]: (_this_count_button = this.count[button]) !== null && _this_count_button !== undefined ? _this_count_button : 0 + }; + var _this_count_button1; + this.count = { + [button]: (_this_count_button1 = this.count[button]) !== null && _this_count_button1 !== undefined ? _this_count_button1 : 0 + }; + return Number(this.count[button]) + 1; + } + getOnUp(button) { + return this.down[button] === undefined ? undefined : Number(this.down[button]) + 1; + } + reset() { + this.count = {}; + } + constructor(){ + _define_property(this, "down", {}); + _define_property(this, "count", {}); + } + }()); + } +} + +export { Mouse }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/pointer.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/pointer.js new file mode 100644 index 0000000000000000000000000000000000000000..93bce3bbca5fb189aec653a8bf5e9608e783d6c0 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/pointer.js @@ -0,0 +1,129 @@ +import '../../utils/dataTransfer/Clipboard.js'; +import { getTreeDiff } from '../../utils/misc/getTreeDiff.js'; +import { assertPointerEvents, hasPointerEvents } from '../../utils/pointer/cssPointerEvents.js'; +import { isDifferentPointerPosition } from './shared.js'; +import { getMouseEventButton } from './buttons.js'; + +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +class Pointer { + init(instance) { + const target = this.getTarget(instance); + const [, enter] = getTreeDiff(null, target); + const init = this.getEventInit(); + assertPointerEvents(instance, target); + instance.dispatchUIEvent(target, 'pointerover', init); + enter.forEach((el)=>instance.dispatchUIEvent(el, 'pointerenter', init)); + return this; + } + move(instance, position) { + const prevPosition = this.position; + const prevTarget = this.getTarget(instance); + this.position = position; + if (!isDifferentPointerPosition(prevPosition, position)) { + return; + } + const nextTarget = this.getTarget(instance); + const init = this.getEventInit(-1); + const [leave, enter] = getTreeDiff(prevTarget, nextTarget); + return { + leave: ()=>{ + if (hasPointerEvents(instance, prevTarget)) { + if (prevTarget !== nextTarget) { + instance.dispatchUIEvent(prevTarget, 'pointerout', init); + leave.forEach((el)=>instance.dispatchUIEvent(el, 'pointerleave', init)); + } + } + }, + enter: ()=>{ + assertPointerEvents(instance, nextTarget); + if (prevTarget !== nextTarget) { + instance.dispatchUIEvent(nextTarget, 'pointerover', init); + enter.forEach((el)=>instance.dispatchUIEvent(el, 'pointerenter', init)); + } + }, + move: ()=>{ + instance.dispatchUIEvent(nextTarget, 'pointermove', init); + } + }; + } + down(instance, button = 0) { + if (this.isDown) { + return; + } + const target = this.getTarget(instance); + assertPointerEvents(instance, target); + this.isDown = true; + this.isPrevented = !instance.dispatchUIEvent(target, 'pointerdown', this.getEventInit(button)); + } + up(instance, button = 0) { + if (!this.isDown) { + return; + } + const target = this.getTarget(instance); + assertPointerEvents(instance, target); + this.isPrevented = false; + this.isDown = false; + instance.dispatchUIEvent(target, 'pointerup', this.getEventInit(button)); + } + release(instance) { + const target = this.getTarget(instance); + const [leave] = getTreeDiff(target, null); + const init = this.getEventInit(); + // Currently there is no PointerEventsCheckLevel that would + // make this check not use the *asserted* cached value from `up`. + /* istanbul ignore else */ if (hasPointerEvents(instance, target)) { + instance.dispatchUIEvent(target, 'pointerout', init); + leave.forEach((el)=>instance.dispatchUIEvent(el, 'pointerleave', init)); + } + this.isCancelled = true; + } + getTarget(instance) { + var _this_position_target; + return (_this_position_target = this.position.target) !== null && _this_position_target !== undefined ? _this_position_target : instance.config.document.body; + } + getEventInit(/** + * The `button` that caused the event. + * + * This should be `-1` if the event is not caused by a button or touch/pen contact, + * e.g. a moving pointer. + */ button) { + return { + ...this.position.coords, + pointerId: this.pointerId, + pointerType: this.pointerType, + isPrimary: this.isPrimary, + button: getMouseEventButton(button), + buttons: this.buttons.getButtons() + }; + } + constructor({ pointerId, pointerType, isPrimary }, buttons){ + _define_property(this, "pointerId", undefined); + _define_property(this, "pointerType", undefined); + _define_property(this, "isPrimary", undefined); + _define_property(this, "buttons", undefined); + _define_property(this, "isMultitouch", false); + _define_property(this, "isCancelled", false); + _define_property(this, "isDown", false); + _define_property(this, "isPrevented", false); + _define_property(this, "position", {}); + this.pointerId = pointerId; + this.pointerType = pointerType; + this.isPrimary = isPrimary; + this.isMultitouch = !isPrimary; + this.buttons = buttons; + } +} + +export { Pointer }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/shared.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/shared.js new file mode 100644 index 0000000000000000000000000000000000000000..d9d99576b138c8c8706bde3bfc2e39fd02447233 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/system/pointer/shared.js @@ -0,0 +1,6 @@ +function isDifferentPointerPosition(positionA, positionB) { + var _positionA_coords, _positionB_coords, _positionA_coords1, _positionB_coords1, _positionA_coords2, _positionB_coords2, _positionA_coords3, _positionB_coords3, _positionA_coords4, _positionB_coords4, _positionA_coords5, _positionB_coords5, _positionA_coords6, _positionB_coords6, _positionA_coords7, _positionB_coords7, _positionA_coords8, _positionB_coords8, _positionA_coords9, _positionB_coords9, _positionA_caret, _positionB_caret, _positionA_caret1, _positionB_caret1; + return positionA.target !== positionB.target || ((_positionA_coords = positionA.coords) === null || _positionA_coords === undefined ? undefined : _positionA_coords.x) !== ((_positionB_coords = positionB.coords) === null || _positionB_coords === undefined ? undefined : _positionB_coords.x) || ((_positionA_coords1 = positionA.coords) === null || _positionA_coords1 === undefined ? undefined : _positionA_coords1.y) !== ((_positionB_coords1 = positionB.coords) === null || _positionB_coords1 === undefined ? undefined : _positionB_coords1.y) || ((_positionA_coords2 = positionA.coords) === null || _positionA_coords2 === undefined ? undefined : _positionA_coords2.clientX) !== ((_positionB_coords2 = positionB.coords) === null || _positionB_coords2 === undefined ? undefined : _positionB_coords2.clientX) || ((_positionA_coords3 = positionA.coords) === null || _positionA_coords3 === undefined ? undefined : _positionA_coords3.clientY) !== ((_positionB_coords3 = positionB.coords) === null || _positionB_coords3 === undefined ? undefined : _positionB_coords3.clientY) || ((_positionA_coords4 = positionA.coords) === null || _positionA_coords4 === undefined ? undefined : _positionA_coords4.offsetX) !== ((_positionB_coords4 = positionB.coords) === null || _positionB_coords4 === undefined ? undefined : _positionB_coords4.offsetX) || ((_positionA_coords5 = positionA.coords) === null || _positionA_coords5 === undefined ? undefined : _positionA_coords5.offsetY) !== ((_positionB_coords5 = positionB.coords) === null || _positionB_coords5 === undefined ? undefined : _positionB_coords5.offsetY) || ((_positionA_coords6 = positionA.coords) === null || _positionA_coords6 === undefined ? undefined : _positionA_coords6.pageX) !== ((_positionB_coords6 = positionB.coords) === null || _positionB_coords6 === undefined ? undefined : _positionB_coords6.pageX) || ((_positionA_coords7 = positionA.coords) === null || _positionA_coords7 === undefined ? undefined : _positionA_coords7.pageY) !== ((_positionB_coords7 = positionB.coords) === null || _positionB_coords7 === undefined ? undefined : _positionB_coords7.pageY) || ((_positionA_coords8 = positionA.coords) === null || _positionA_coords8 === undefined ? undefined : _positionA_coords8.screenX) !== ((_positionB_coords8 = positionB.coords) === null || _positionB_coords8 === undefined ? undefined : _positionB_coords8.screenX) || ((_positionA_coords9 = positionA.coords) === null || _positionA_coords9 === undefined ? undefined : _positionA_coords9.screenY) !== ((_positionB_coords9 = positionB.coords) === null || _positionB_coords9 === undefined ? undefined : _positionB_coords9.screenY) || ((_positionA_caret = positionA.caret) === null || _positionA_caret === undefined ? undefined : _positionA_caret.node) !== ((_positionB_caret = positionB.caret) === null || _positionB_caret === undefined ? undefined : _positionB_caret.node) || ((_positionA_caret1 = positionA.caret) === null || _positionA_caret1 === undefined ? undefined : _positionA_caret1.offset) !== ((_positionB_caret1 = positionB.caret) === null || _positionB_caret1 === undefined ? undefined : _positionB_caret1.offset); +} + +export { isDifferentPointerPosition }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utility/clear.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utility/clear.js new file mode 100644 index 0000000000000000000000000000000000000000..a4a895308caddf5bd85dce34ec0ad8d452a81d56 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utility/clear.js @@ -0,0 +1,30 @@ +import '../event/behavior/click.js'; +import '../event/behavior/cut.js'; +import '../event/behavior/keydown.js'; +import '../event/behavior/keypress.js'; +import '../event/behavior/keyup.js'; +import '../event/behavior/paste.js'; +import '@testing-library/dom'; +import '../utils/dataTransfer/Clipboard.js'; +import { isEditable } from '../utils/edit/isEditable.js'; +import { isDisabled } from '../utils/misc/isDisabled.js'; +import { focusElement } from '../event/focus.js'; +import { input } from '../event/input.js'; +import { selectAll, isAllSelected } from '../event/selection/selectAll.js'; + +async function clear(element) { + if (!isEditable(element) || isDisabled(element)) { + throw new Error('clear()` is only supported on editable elements.'); + } + focusElement(element); + if (element.ownerDocument.activeElement !== element) { + throw new Error('The element to be cleared could not be focused.'); + } + selectAll(element); + if (!isAllSelected(element)) { + throw new Error('The element content to be cleared could not be selected.'); + } + input(this, element, '', 'deleteContentBackward'); +} + +export { clear }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utility/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utility/index.js new file mode 100644 index 0000000000000000000000000000000000000000..79177c5fa581cf306d1b1db108ce4914e731c9c8 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utility/index.js @@ -0,0 +1,4 @@ +export { clear } from './clear.js'; +export { deselectOptions, selectOptions } from './selectOptions.js'; +export { type } from './type.js'; +export { upload } from './upload.js'; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utility/selectOptions.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utility/selectOptions.js new file mode 100644 index 0000000000000000000000000000000000000000..5d36724fde707aeb06a47beed8667ab38b235b1e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utility/selectOptions.js @@ -0,0 +1,111 @@ +import { getConfig } from '@testing-library/dom'; +import { isElementType } from '../utils/misc/isElementType.js'; +import '../utils/dataTransfer/Clipboard.js'; +import { isDisabled } from '../utils/misc/isDisabled.js'; +import { wait } from '../utils/misc/wait.js'; +import { hasPointerEvents } from '../utils/pointer/cssPointerEvents.js'; +import '../event/behavior/click.js'; +import '../event/behavior/cut.js'; +import '../event/behavior/keydown.js'; +import '../event/behavior/keypress.js'; +import '../event/behavior/keyup.js'; +import '../event/behavior/paste.js'; +import { focusElement } from '../event/focus.js'; + +async function selectOptions(select, values) { + return selectOptionsBase.call(this, true, select, values); +} +async function deselectOptions(select, values) { + return selectOptionsBase.call(this, false, select, values); +} +async function selectOptionsBase(newValue, select, values) { + if (!newValue && !select.multiple) { + throw getConfig().getElementError(`Unable to deselect an option in a non-multiple select. Use selectOptions to change the selection instead.`, select); + } + const valArray = Array.isArray(values) ? values : [ + values + ]; + const allOptions = Array.from(select.querySelectorAll('option, [role="option"]')); + const selectedOptions = valArray.map((val)=>{ + if (typeof val !== 'string' && allOptions.includes(val)) { + return val; + } else { + const matchingOption = allOptions.find((o)=>o.value === val || o.innerHTML === val); + if (matchingOption) { + return matchingOption; + } else { + throw getConfig().getElementError(`Value "${String(val)}" not found in options`, select); + } + } + }).filter((option)=>!isDisabled(option)); + if (isDisabled(select) || !selectedOptions.length) return; + const selectOption = (option)=>{ + option.selected = newValue; + this.dispatchUIEvent(select, 'input', { + bubbles: true, + cancelable: false, + composed: true + }); + this.dispatchUIEvent(select, 'change'); + }; + if (isElementType(select, 'select')) { + if (select.multiple) { + for (const option of selectedOptions){ + const withPointerEvents = this.config.pointerEventsCheck === 0 ? true : hasPointerEvents(this, option); + // events fired for multiple select are weird. Can't use hover... + if (withPointerEvents) { + this.dispatchUIEvent(option, 'pointerover'); + this.dispatchUIEvent(select, 'pointerenter'); + this.dispatchUIEvent(option, 'mouseover'); + this.dispatchUIEvent(select, 'mouseenter'); + this.dispatchUIEvent(option, 'pointermove'); + this.dispatchUIEvent(option, 'mousemove'); + this.dispatchUIEvent(option, 'pointerdown'); + this.dispatchUIEvent(option, 'mousedown'); + } + focusElement(select); + if (withPointerEvents) { + this.dispatchUIEvent(option, 'pointerup'); + this.dispatchUIEvent(option, 'mouseup'); + } + selectOption(option); + if (withPointerEvents) { + this.dispatchUIEvent(option, 'click'); + } + await wait(this.config); + } + } else if (selectedOptions.length === 1) { + const withPointerEvents = this.config.pointerEventsCheck === 0 ? true : hasPointerEvents(this, select); + // the click to open the select options + if (withPointerEvents) { + await this.click(select); + } else { + focusElement(select); + } + selectOption(selectedOptions[0]); + if (withPointerEvents) { + // the browser triggers another click event on the select for the click on the option + // this second click has no 'down' phase + this.dispatchUIEvent(select, 'pointerover'); + this.dispatchUIEvent(select, 'pointerenter'); + this.dispatchUIEvent(select, 'mouseover'); + this.dispatchUIEvent(select, 'mouseenter'); + this.dispatchUIEvent(select, 'pointerup'); + this.dispatchUIEvent(select, 'mouseup'); + this.dispatchUIEvent(select, 'click'); + } + await wait(this.config); + } else { + throw getConfig().getElementError(`Cannot select multiple options on a non-multiple select`, select); + } + } else if (select.getAttribute('role') === 'listbox') { + for (const option of selectedOptions){ + await this.click(option); + await this.unhover(option); + } + } else { + throw getConfig().getElementError(`Cannot select options on elements that are neither select nor listbox elements`, select); + } +} + +export { deselectOptions, selectOptions }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utility/type.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utility/type.js new file mode 100644 index 0000000000000000000000000000000000000000..c6f751a69986068678082b79658fc772770f404c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utility/type.js @@ -0,0 +1,21 @@ +import { releaseAllKeys } from '../keyboard/index.js'; +import '../utils/dataTransfer/Clipboard.js'; +import { setSelectionRange } from '../event/selection/setSelectionRange.js'; + +async function type(element, text, { skipClick = this.config.skipClick, skipAutoClose = this.config.skipAutoClose, initialSelectionStart, initialSelectionEnd } = {}) { + // TODO: properly type guard + // we use this workaround for now to prevent changing behavior + if (element.disabled) return; + if (!skipClick) { + await this.click(element); + } + if (initialSelectionStart !== undefined) { + setSelectionRange(element, initialSelectionStart, initialSelectionEnd !== null && initialSelectionEnd !== undefined ? initialSelectionEnd : initialSelectionStart); + } + await this.keyboard(text); + if (!skipAutoClose) { + await releaseAllKeys(this); + } +} + +export { type }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utility/upload.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utility/upload.js new file mode 100644 index 0000000000000000000000000000000000000000..9918d4893500303e3c633466706d11311215bc3f --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utility/upload.js @@ -0,0 +1,60 @@ +import { isElementType } from '../utils/misc/isElementType.js'; +import { createFileList } from '../utils/dataTransfer/FileList.js'; +import '../utils/dataTransfer/Clipboard.js'; +import { setFiles } from '../utils/edit/setFiles.js'; +import { isDisabled } from '../utils/misc/isDisabled.js'; +import { getWindow } from '../utils/misc/getWindow.js'; + +async function upload(element, fileOrFiles) { + const input = isElementType(element, 'label') ? element.control : element; + if (!input || !isElementType(input, 'input', { + type: 'file' + })) { + throw new TypeError(`The ${input === element ? 'given' : 'associated'} ${input === null || input === undefined ? undefined : input.tagName} element does not accept file uploads`); + } + if (isDisabled(element)) return; + const files = (Array.isArray(fileOrFiles) ? fileOrFiles : [ + fileOrFiles + ]).filter((file)=>!this.config.applyAccept || isAcceptableFile(file, input.accept)).slice(0, input.multiple ? undefined : 1); + const fileDialog = ()=>{ + var _input_files; + // do not fire an input event if the file selection does not change + if (files.length === ((_input_files = input.files) === null || _input_files === undefined ? undefined : _input_files.length) && files.every((f, i)=>{ + var _input_files; + return f === ((_input_files = input.files) === null || _input_files === undefined ? undefined : _input_files.item(i)); + })) { + return; + } + setFiles(input, createFileList(getWindow(element), files)); + this.dispatchUIEvent(input, 'input'); + this.dispatchUIEvent(input, 'change'); + }; + input.addEventListener('fileDialog', fileDialog); + await this.click(element); + input.removeEventListener('fileDialog', fileDialog); +} +// When matching files, browsers ignore case and consider jpeg/jpg interchangeable. +function normalize(nameOrType) { + return nameOrType.toLowerCase().replace(/(\.|\/)jpg\b/g, '$1jpeg'); +} +function isAcceptableFile(file, accept) { + if (!accept) { + return true; + } + const wildcards = [ + 'audio/*', + 'image/*', + 'video/*' + ]; + return normalize(accept).trim().split(/\s*,\s*/).some((acceptToken)=>{ + // tokens starting with a dot represent a file extension + if (acceptToken.startsWith('.')) { + return normalize(file.name).endsWith(acceptToken); + } else if (wildcards.includes(acceptToken)) { + return normalize(file.type).startsWith(acceptToken.replace('*', '')); + } + return normalize(file.type) === acceptToken; + }); +} + +export { upload }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/click/isClickableInput.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/click/isClickableInput.js new file mode 100644 index 0000000000000000000000000000000000000000..75056f447ccc6fb5f7f12636d475e8f9812d5005 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/click/isClickableInput.js @@ -0,0 +1,18 @@ +import { isElementType } from '../misc/isElementType.js'; + +var clickableInputTypes = /*#__PURE__*/ function(clickableInputTypes) { + clickableInputTypes["button"] = "button"; + clickableInputTypes["color"] = "color"; + clickableInputTypes["file"] = "file"; + clickableInputTypes["image"] = "image"; + clickableInputTypes["reset"] = "reset"; + clickableInputTypes["submit"] = "submit"; + clickableInputTypes["checkbox"] = "checkbox"; + clickableInputTypes["radio"] = "radio"; + return clickableInputTypes; +}(clickableInputTypes || {}); +function isClickableInput(element) { + return isElementType(element, 'button') || isElementType(element, 'input') && element.type in clickableInputTypes; +} + +export { isClickableInput }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/dataTransfer/Blob.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/dataTransfer/Blob.js new file mode 100644 index 0000000000000000000000000000000000000000..31dacd1dbd336d599994e90767570a2f754ec1b8 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/dataTransfer/Blob.js @@ -0,0 +1,14 @@ +// jsdom does not implement Blob.text() +function readBlobText(blob, FileReader) { + return new Promise((res, rej)=>{ + const fr = new FileReader(); + fr.onerror = rej; + fr.onabort = rej; + fr.onload = ()=>{ + res(String(fr.result)); + }; + fr.readAsText(blob); + }); +} + +export { readBlobText }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/dataTransfer/Clipboard.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/dataTransfer/Clipboard.js new file mode 100644 index 0000000000000000000000000000000000000000..2ed2676b52adaee045d2594b051c08a4b133e7df --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/dataTransfer/Clipboard.js @@ -0,0 +1,162 @@ +import { getWindow } from '../misc/getWindow.js'; +import { readBlobText } from './Blob.js'; +import { createDataTransfer, getBlobFromDataTransferItem } from './DataTransfer.js'; + +// Clipboard is not available in jsdom +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +// MDN lists string|Blob|Promise as possible types in ClipboardItemData +// lib.dom.d.ts lists only Promise +// https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem/ClipboardItem#syntax +function createClipboardItem(window, ...blobs) { + const dataMap = Object.fromEntries(blobs.map((b)=>[ + typeof b === 'string' ? 'text/plain' : b.type, + Promise.resolve(b) + ])); + // use real ClipboardItem if available + /* istanbul ignore if */ if (typeof window.ClipboardItem !== 'undefined') { + return new window.ClipboardItem(dataMap); + } + return new class ClipboardItem { + get types() { + return Array.from(Object.keys(this.data)); + } + async getType(type) { + const value = await this.data[type]; + if (!value) { + throw new Error(`${type} is not one of the available MIME types on this item.`); + } + return value instanceof window.Blob ? value : new window.Blob([ + value + ], { + type + }); + } + constructor(d){ + _define_property(this, "data", undefined); + this.data = d; + } + }(dataMap); +} +const ClipboardStubControl = Symbol('Manage ClipboardSub'); +function createClipboardStub(window, control) { + return Object.assign(new class Clipboard extends window.EventTarget { + async read() { + return Array.from(this.items); + } + async readText() { + let text = ''; + for (const item of this.items){ + const type = item.types.includes('text/plain') ? 'text/plain' : item.types.find((t)=>t.startsWith('text/')); + if (type) { + text += await item.getType(type).then((b)=>readBlobText(b, window.FileReader)); + } + } + return text; + } + async write(data) { + this.items = data; + } + async writeText(text) { + this.items = [ + createClipboardItem(window, text) + ]; + } + constructor(...args){ + super(...args), _define_property(this, "items", []); + } + }(), { + [ClipboardStubControl]: control + }); +} +function isClipboardStub(clipboard) { + return !!(clipboard === null || clipboard === undefined ? undefined : clipboard[ClipboardStubControl]); +} +function attachClipboardStubToView(window) { + if (isClipboardStub(window.navigator.clipboard)) { + return window.navigator.clipboard[ClipboardStubControl]; + } + const realClipboard = Object.getOwnPropertyDescriptor(window.navigator, 'clipboard'); + let stub; + const control = { + resetClipboardStub: ()=>{ + stub = createClipboardStub(window, control); + }, + detachClipboardStub: ()=>{ + /* istanbul ignore if */ if (realClipboard) { + Object.defineProperty(window.navigator, 'clipboard', realClipboard); + } else { + Object.defineProperty(window.navigator, 'clipboard', { + value: undefined, + configurable: true + }); + } + } + }; + stub = createClipboardStub(window, control); + Object.defineProperty(window.navigator, 'clipboard', { + get: ()=>stub, + configurable: true + }); + return stub[ClipboardStubControl]; +} +function resetClipboardStubOnView(window) { + if (isClipboardStub(window.navigator.clipboard)) { + window.navigator.clipboard[ClipboardStubControl].resetClipboardStub(); + } +} +function detachClipboardStubFromView(window) { + if (isClipboardStub(window.navigator.clipboard)) { + window.navigator.clipboard[ClipboardStubControl].detachClipboardStub(); + } +} +async function readDataTransferFromClipboard(document) { + const window = document.defaultView; + const clipboard = window === null || window === undefined ? undefined : window.navigator.clipboard; + const items = clipboard && await clipboard.read(); + if (!items) { + throw new Error('The Clipboard API is unavailable.'); + } + const dt = createDataTransfer(window); + for (const item of items){ + for (const type of item.types){ + dt.setData(type, await item.getType(type).then((b)=>readBlobText(b, window.FileReader))); + } + } + return dt; +} +async function writeDataTransferToClipboard(document, clipboardData) { + const window = getWindow(document); + const clipboard = window.navigator.clipboard; + const items = []; + for(let i = 0; i < clipboardData.items.length; i++){ + const dtItem = clipboardData.items[i]; + const blob = await getBlobFromDataTransferItem(window, dtItem); + items.push(createClipboardItem(window, blob)); + } + const written = clipboard && await clipboard.write(items).then(()=>true, // Can happen with other implementations that e.g. require permissions + /* istanbul ignore next */ ()=>false); + if (!written) { + throw new Error('The Clipboard API is unavailable.'); + } +} +const g = globalThis; +/* istanbul ignore else */ if (typeof g.afterEach === 'function') { + g.afterEach(()=>resetClipboardStubOnView(globalThis.window)); +} +/* istanbul ignore else */ if (typeof g.afterAll === 'function') { + g.afterAll(()=>detachClipboardStubFromView(globalThis.window)); +} + +export { attachClipboardStubToView, createClipboardItem, detachClipboardStubFromView, readDataTransferFromClipboard, resetClipboardStubOnView, writeDataTransferToClipboard }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/dataTransfer/DataTransfer.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/dataTransfer/DataTransfer.js new file mode 100644 index 0000000000000000000000000000000000000000..98189be509364c603fb237f91685d58eecbccc9a --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/dataTransfer/DataTransfer.js @@ -0,0 +1,133 @@ +import { createFileList } from './FileList.js'; + +function _define_property(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +// DataTransfer is not implemented in jsdom. +// DataTransfer with FileList is being created by the browser on certain events. +class DataTransferItemStub { + getAsFile() { + return this.file; + } + getAsString(callback) { + if (typeof this.data === 'string') { + callback(this.data); + } + } + /* istanbul ignore next */ webkitGetAsEntry() { + throw new Error('not implemented'); + } + constructor(dataOrFile, type){ + _define_property(this, "kind", undefined); + _define_property(this, "type", undefined); + _define_property(this, "file", null); + _define_property(this, "data", undefined); + if (typeof dataOrFile === 'string') { + this.kind = 'string'; + this.type = String(type); + this.data = dataOrFile; + } else { + this.kind = 'file'; + this.type = dataOrFile.type; + this.file = dataOrFile; + } + } +} +class DataTransferItemListStub extends Array { + add(...args) { + const item = new DataTransferItemStub(args[0], args[1]); + this.push(item); + return item; + } + clear() { + this.splice(0, this.length); + } + remove(index) { + this.splice(index, 1); + } +} +function getTypeMatcher(type, exact) { + const [group, sub] = type.split('/'); + const isGroup = !sub || sub === '*'; + return (item)=>{ + return exact ? item.type === (isGroup ? group : type) : isGroup ? item.type.startsWith(`${group}/`) : item.type === group; + }; +} +function createDataTransferStub(window) { + return new class DataTransferStub { + getData(format) { + var _this_items_find; + const match = (_this_items_find = this.items.find(getTypeMatcher(format, true))) !== null && _this_items_find !== undefined ? _this_items_find : this.items.find(getTypeMatcher(format, false)); + let text = ''; + match === null || match === undefined ? undefined : match.getAsString((t)=>{ + text = t; + }); + return text; + } + setData(format, data) { + const matchIndex = this.items.findIndex(getTypeMatcher(format, true)); + const item = new DataTransferItemStub(data, format); + if (matchIndex >= 0) { + this.items.splice(matchIndex, 1, item); + } else { + this.items.push(item); + } + } + clearData(format) { + if (format) { + const matchIndex = this.items.findIndex(getTypeMatcher(format, true)); + if (matchIndex >= 0) { + this.items.remove(matchIndex); + } + } else { + this.items.clear(); + } + } + get types() { + const t = []; + if (this.files.length) { + t.push('Files'); + } + this.items.forEach((i)=>t.push(i.type)); + Object.freeze(t); + return t; + } + /* istanbul ignore next */ setDragImage() {} + constructor(){ + _define_property(this, "dropEffect", 'none'); + _define_property(this, "effectAllowed", 'uninitialized'); + _define_property(this, "items", new DataTransferItemListStub()); + _define_property(this, "files", createFileList(window, [])); + } + }(); +} +function createDataTransfer(window, files = []) { + // Use real DataTransfer if available + const dt = typeof window.DataTransfer === 'undefined' ? createDataTransferStub(window) : /* istanbul ignore next */ new window.DataTransfer(); + Object.defineProperty(dt, 'files', { + get: ()=>createFileList(window, files) + }); + return dt; +} +async function getBlobFromDataTransferItem(window, item) { + if (item.kind === 'file') { + return item.getAsFile(); + } + return new window.Blob([ + await new Promise((r)=>item.getAsString(r)) + ], { + type: item.type + }); +} + +export { createDataTransfer, getBlobFromDataTransferItem }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/dataTransfer/FileList.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/dataTransfer/FileList.js new file mode 100644 index 0000000000000000000000000000000000000000..916c36ae6939325d9208150608a90ca4b45cd9cc --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/dataTransfer/FileList.js @@ -0,0 +1,22 @@ +// FileList can not be created per constructor. +function createFileList(window, files) { + const list = { + ...files, + length: files.length, + item: (index)=>list[index], + [Symbol.iterator]: function* nextFile() { + for(let i = 0; i < list.length; i++){ + yield list[i]; + } + } + }; + list.constructor = window.FileList; + // guard for environments without FileList + /* istanbul ignore else */ if (window.FileList) { + Object.setPrototypeOf(list, window.FileList.prototype); + } + Object.freeze(list); + return list; +} + +export { createFileList }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/edit/isContentEditable.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/edit/isContentEditable.js new file mode 100644 index 0000000000000000000000000000000000000000..efabac8e40511f5c4a32e85b3b4b07cf6980e292 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/edit/isContentEditable.js @@ -0,0 +1,15 @@ +//jsdom is not supporting isContentEditable +function isContentEditable(element) { + return element.hasAttribute('contenteditable') && (element.getAttribute('contenteditable') == 'true' || element.getAttribute('contenteditable') == ''); +} +/** + * If a node is a contenteditable or inside one, return that element. + */ function getContentEditable(node) { + const element = getElement(node); + return element && (element.closest('[contenteditable=""]') || element.closest('[contenteditable="true"]')); +} +function getElement(node) { + return node.nodeType === 1 ? node : node.parentElement; +} + +export { getContentEditable, isContentEditable }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/edit/isEditable.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/edit/isEditable.js new file mode 100644 index 0000000000000000000000000000000000000000..c3fa1b3aba396524eb71a454d7dde5b92f0c727e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/edit/isEditable.js @@ -0,0 +1,26 @@ +import { isElementType } from '../misc/isElementType.js'; +import { isContentEditable } from './isContentEditable.js'; + +function isEditable(element) { + return isEditableInputOrTextArea(element) && !element.readOnly || isContentEditable(element); +} +var editableInputTypes = /*#__PURE__*/ function(editableInputTypes) { + editableInputTypes["text"] = "text"; + editableInputTypes["date"] = "date"; + editableInputTypes["datetime-local"] = "datetime-local"; + editableInputTypes["email"] = "email"; + editableInputTypes["month"] = "month"; + editableInputTypes["number"] = "number"; + editableInputTypes["password"] = "password"; + editableInputTypes["search"] = "search"; + editableInputTypes["tel"] = "tel"; + editableInputTypes["time"] = "time"; + editableInputTypes["url"] = "url"; + editableInputTypes["week"] = "week"; + return editableInputTypes; +}(editableInputTypes || {}); +function isEditableInputOrTextArea(element) { + return isElementType(element, 'textarea') || isElementType(element, 'input') && element.type in editableInputTypes; +} + +export { isEditable, isEditableInputOrTextArea }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/edit/maxLength.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/edit/maxLength.js new file mode 100644 index 0000000000000000000000000000000000000000..266c971682fe95e8b3416b79e9cf3da7b03a169f --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/edit/maxLength.js @@ -0,0 +1,23 @@ +import { isElementType } from '../misc/isElementType.js'; + +var maxLengthSupportedTypes = /*#__PURE__*/ function(maxLengthSupportedTypes) { + maxLengthSupportedTypes["email"] = "email"; + maxLengthSupportedTypes["password"] = "password"; + maxLengthSupportedTypes["search"] = "search"; + maxLengthSupportedTypes["telephone"] = "telephone"; + maxLengthSupportedTypes["text"] = "text"; + maxLengthSupportedTypes["url"] = "url"; + return maxLengthSupportedTypes; +}(maxLengthSupportedTypes || {}); +// can't use .maxLength property because of a jsdom bug: +// https://github.com/jsdom/jsdom/issues/2927 +function getMaxLength(element) { + var _element_getAttribute; + const attr = (_element_getAttribute = element.getAttribute('maxlength')) !== null && _element_getAttribute !== undefined ? _element_getAttribute : ''; + return /^\d+$/.test(attr) && Number(attr) >= 0 ? Number(attr) : undefined; +} +function supportsMaxLength(element) { + return isElementType(element, 'textarea') || isElementType(element, 'input') && element.type in maxLengthSupportedTypes; +} + +export { getMaxLength, supportsMaxLength }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/edit/setFiles.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/edit/setFiles.js new file mode 100644 index 0000000000000000000000000000000000000000..394f3152c503999a28e5245bda569a4b34c5f96b --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/edit/setFiles.js @@ -0,0 +1,57 @@ +// It is not possible to create a real FileList programmatically. +// Therefore assigning `files` property with a programmatically created FileList results in an error. +// Just assigning the property (as per fireEvent) breaks the interweaving with the `value` property. +const fakeFiles = Symbol('files and value properties are mocked'); +function restoreProperty(obj, prop, descriptor) { + if (descriptor) { + Object.defineProperty(obj, prop, descriptor); + } else { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete obj[prop]; + } +} +function setFiles(el, files) { + var _el_fakeFiles; + (_el_fakeFiles = el[fakeFiles]) === null || _el_fakeFiles === undefined ? undefined : _el_fakeFiles.restore(); + const typeDescr = Object.getOwnPropertyDescriptor(el, 'type'); + const valueDescr = Object.getOwnPropertyDescriptor(el, 'value'); + const filesDescr = Object.getOwnPropertyDescriptor(el, 'files'); + function restore() { + restoreProperty(el, 'type', typeDescr); + restoreProperty(el, 'value', valueDescr); + restoreProperty(el, 'files', filesDescr); + } + el[fakeFiles] = { + restore + }; + Object.defineProperties(el, { + files: { + configurable: true, + get: ()=>files + }, + value: { + configurable: true, + get: ()=>files.length ? `C:\\fakepath\\${files[0].name}` : '', + set (v) { + if (v === '') { + restore(); + } else { + var _valueDescr_set; + valueDescr === null || valueDescr === undefined ? undefined : (_valueDescr_set = valueDescr.set) === null || _valueDescr_set === undefined ? undefined : _valueDescr_set.call(el, v); + } + } + }, + type: { + configurable: true, + get: ()=>'file', + set (v) { + if (v !== 'file') { + restore(); + el.type = v; + } + } + } + }); +} + +export { setFiles }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/edit/timeValue.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/edit/timeValue.js new file mode 100644 index 0000000000000000000000000000000000000000..dc54b5d68474c410b52580049f4cdf4eb8f67b4e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/edit/timeValue.js @@ -0,0 +1,37 @@ +const parseInt = globalThis.parseInt; +function buildTimeValue(value) { + const onlyDigitsValue = value.replace(/\D/g, ''); + if (onlyDigitsValue.length < 2) { + return value; + } + const firstDigit = parseInt(onlyDigitsValue[0], 10); + const secondDigit = parseInt(onlyDigitsValue[1], 10); + if (firstDigit >= 3 || firstDigit === 2 && secondDigit >= 4) { + let index; + if (firstDigit >= 3) { + index = 1; + } else { + index = 2; + } + return build(onlyDigitsValue, index); + } + if (value.length === 2) { + return value; + } + return build(onlyDigitsValue, 2); +} +function build(onlyDigitsValue, index) { + const hours = onlyDigitsValue.slice(0, index); + const validHours = Math.min(parseInt(hours, 10), 23); + const minuteCharacters = onlyDigitsValue.slice(index); + const parsedMinutes = parseInt(minuteCharacters, 10); + const validMinutes = Math.min(parsedMinutes, 59); + return `${validHours.toString().padStart(2, '0')}:${validMinutes.toString().padStart(2, '0')}`; +} +function isValidDateOrTimeValue(element, value) { + const clone = element.cloneNode(); + clone.value = value; + return clone.value === value; +} + +export { buildTimeValue, isValidDateOrTimeValue }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/cursor.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/cursor.js new file mode 100644 index 0000000000000000000000000000000000000000..5a4e2cd4ca3361077cb02efe0b9460e532d3f87e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/cursor.js @@ -0,0 +1,124 @@ +import { isContentEditable } from '../edit/isContentEditable.js'; +import { isElementType } from '../misc/isElementType.js'; + +function getNextCursorPosition(node, offset, direction, inputType) { + // The behavior at text node zero offset is inconsistent. + // When walking backwards: + // Firefox always moves to zero offset and jumps over last offset. + // Chrome jumps over zero offset per default but over last offset when Shift is pressed. + // The cursor always moves to zero offset if the focus area (contenteditable or body) ends there. + // When walking forward both ignore zero offset. + // When walking over input elements the cursor moves before or after that element. + // When walking over line breaks the cursor moves inside any following text node. + if (isTextNode(node) && offset + direction >= 0 && offset + direction <= node.nodeValue.length) { + return { + node, + offset: offset + direction + }; + } + const nextNode = getNextCharacterContentNode(node, offset, direction); + if (nextNode) { + if (isTextNode(nextNode)) { + return { + node: nextNode, + offset: direction > 0 ? Math.min(1, nextNode.nodeValue.length) : Math.max(nextNode.nodeValue.length - 1, 0) + }; + } else if (isElementType(nextNode, 'br')) { + const nextPlusOne = getNextCharacterContentNode(nextNode, undefined, direction); + if (!nextPlusOne) { + // The behavior when there is no possible cursor position beyond the line break is inconsistent. + // In Chrome outside of contenteditable moving before a leading line break is possible. + // A leading line break can still be removed per deleteContentBackward. + // A trailing line break on the other hand is not removed by deleteContentForward. + if (direction < 0 && inputType === 'deleteContentBackward') { + return { + node: nextNode.parentNode, + offset: getOffset(nextNode) + }; + } + return undefined; + } else if (isTextNode(nextPlusOne)) { + return { + node: nextPlusOne, + offset: direction > 0 ? 0 : nextPlusOne.nodeValue.length + }; + } else if (direction < 0 && isElementType(nextPlusOne, 'br')) { + return { + node: nextNode.parentNode, + offset: getOffset(nextNode) + }; + } else { + return { + node: nextPlusOne.parentNode, + offset: getOffset(nextPlusOne) + (direction > 0 ? 0 : 1) + }; + } + } else { + return { + node: nextNode.parentNode, + offset: getOffset(nextNode) + (direction > 0 ? 1 : 0) + }; + } + } +} +function getNextCharacterContentNode(node, offset, direction) { + const nextOffset = Number(offset) + (direction < 0 ? -1 : 0); + if (offset !== undefined && isElement(node) && nextOffset >= 0 && nextOffset < node.children.length) { + node = node.children[nextOffset]; + } + return walkNodes(node, direction === 1 ? 'next' : 'previous', isTreatedAsCharacterContent); +} +function isTreatedAsCharacterContent(node) { + if (isTextNode(node)) { + return true; + } + if (isElement(node)) { + if (isElementType(node, [ + 'input', + 'textarea' + ])) { + return node.type !== 'hidden'; + } else if (isElementType(node, 'br')) { + return true; + } + } + return false; +} +function getOffset(node) { + let i = 0; + while(node.previousSibling){ + i++; + node = node.previousSibling; + } + return i; +} +function isElement(node) { + return node.nodeType === 1; +} +function isTextNode(node) { + return node.nodeType === 3; +} +function walkNodes(node, direction, callback) { + for(;;){ + var _node_ownerDocument; + const sibling = node[`${direction}Sibling`]; + if (sibling) { + node = getDescendant(sibling, direction === 'next' ? 'first' : 'last'); + if (callback(node)) { + return node; + } + } else if (node.parentNode && (!isElement(node.parentNode) || !isContentEditable(node.parentNode) && node.parentNode !== ((_node_ownerDocument = node.ownerDocument) === null || _node_ownerDocument === undefined ? undefined : _node_ownerDocument.body))) { + node = node.parentNode; + } else { + break; + } + } +} +function getDescendant(node, direction) { + while(node.hasChildNodes()){ + node = node[`${direction}Child`]; + } + return node; +} + +export { getNextCursorPosition }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/getActiveElement.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/getActiveElement.js new file mode 100644 index 0000000000000000000000000000000000000000..44899e10bd04f95f09dc27cc6ff7284d881ab338 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/getActiveElement.js @@ -0,0 +1,20 @@ +import { isDisabled } from '../misc/isDisabled.js'; + +function getActiveElement(document) { + const activeElement = document.activeElement; + if (activeElement === null || activeElement === undefined ? undefined : activeElement.shadowRoot) { + return getActiveElement(activeElement.shadowRoot); + } else { + // Browser does not yield disabled elements as document.activeElement - jsdom does + if (isDisabled(activeElement)) { + return document.ownerDocument ? /* istanbul ignore next */ document.ownerDocument.body : document.body; + } + return activeElement; + } +} +function getActiveElementOrBody(document) { + var _getActiveElement; + return (_getActiveElement = getActiveElement(document)) !== null && _getActiveElement !== undefined ? _getActiveElement : /* istanbul ignore next */ document.body; +} + +export { getActiveElement, getActiveElementOrBody }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/getTabDestination.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/getTabDestination.js new file mode 100644 index 0000000000000000000000000000000000000000..929275b6fa0015d41b50e84be6d63e9e959b51c8 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/getTabDestination.js @@ -0,0 +1,78 @@ +import { isDisabled } from '../misc/isDisabled.js'; +import { isElementType } from '../misc/isElementType.js'; +import { isVisible } from '../misc/isVisible.js'; +import { FOCUSABLE_SELECTOR } from './selector.js'; + +function getTabDestination(activeElement, shift) { + const document = activeElement.ownerDocument; + const focusableElements = document.querySelectorAll(FOCUSABLE_SELECTOR); + const enabledElements = Array.from(focusableElements).filter((el)=>el === activeElement || !(Number(el.getAttribute('tabindex')) < 0 || isDisabled(el))); + // tabindex has no effect if the active element has negative tabindex + if (Number(activeElement.getAttribute('tabindex')) >= 0) { + enabledElements.sort((a, b)=>{ + const i = Number(a.getAttribute('tabindex')); + const j = Number(b.getAttribute('tabindex')); + if (i === j) { + return 0; + } else if (i === 0) { + return 1; + } else if (j === 0) { + return -1; + } + return i - j; + }); + } + const checkedRadio = {}; + let prunedElements = [ + document.body + ]; + const activeRadioGroup = isElementType(activeElement, 'input', { + type: 'radio' + }) ? activeElement.name : undefined; + enabledElements.forEach((currentElement)=>{ + const el = currentElement; + // For radio groups keep only the active radio + // If there is no active radio, keep only the checked radio + // If there is no checked radio, treat like everything else + if (isElementType(el, 'input', { + type: 'radio' + }) && el.name) { + // If the active element is part of the group, add only that + if (el === activeElement) { + prunedElements.push(el); + return; + } else if (el.name === activeRadioGroup) { + return; + } + // If we stumble upon a checked radio, remove the others + if (el.checked) { + prunedElements = prunedElements.filter((e)=>!isElementType(e, 'input', { + type: 'radio', + name: el.name + })); + prunedElements.push(el); + checkedRadio[el.name] = el; + return; + } + // If we already found the checked one, skip + if (typeof checkedRadio[el.name] !== 'undefined') { + return; + } + } + prunedElements.push(el); + }); + for(let index = prunedElements.findIndex((el)=>el === activeElement);;){ + index += shift ? -1 : 1; + // loop at overflow + if (index === prunedElements.length) { + index = 0; + } else if (index === -1) { + index = prunedElements.length - 1; + } + if (prunedElements[index] === activeElement || prunedElements[index] === document.body || isVisible(prunedElements[index])) { + return prunedElements[index]; + } + } +} + +export { getTabDestination }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/isFocusable.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/isFocusable.js new file mode 100644 index 0000000000000000000000000000000000000000..789069eb2a261f6baa6ab4982edd3604a1fbc347 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/isFocusable.js @@ -0,0 +1,7 @@ +import { FOCUSABLE_SELECTOR } from './selector.js'; + +function isFocusable(element) { + return element.matches(FOCUSABLE_SELECTOR); +} + +export { isFocusable }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/selection.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/selection.js new file mode 100644 index 0000000000000000000000000000000000000000..3fc8532ce909c5ef0a9bbb3aa99804b3467d374c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/selection.js @@ -0,0 +1,17 @@ +import { isClickableInput } from '../click/isClickableInput.js'; +import { isEditableInputOrTextArea } from '../edit/isEditable.js'; + +/** + * Determine if the element has its own selection implementation + * and does not interact with the Document Selection API. + */ function hasOwnSelection(node) { + return isElement(node) && isEditableInputOrTextArea(node); +} +function hasNoSelection(node) { + return isElement(node) && isClickableInput(node); +} +function isElement(node) { + return node.nodeType === 1; +} + +export { hasNoSelection, hasOwnSelection }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/selector.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/selector.js new file mode 100644 index 0000000000000000000000000000000000000000..d200f63e043a0efe60de8f92922243703afec7c9 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/focus/selector.js @@ -0,0 +1,12 @@ +const FOCUSABLE_SELECTOR = [ + 'input:not([type=hidden]):not([disabled])', + 'button:not([disabled])', + 'select:not([disabled])', + 'textarea:not([disabled])', + '[contenteditable=""]', + '[contenteditable="true"]', + 'a[href]', + '[tabindex]:not([disabled])' +].join(', '); + +export { FOCUSABLE_SELECTOR }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/index.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8260aa501cfa41ea1c7197b05e11b825dd3e0ed5 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/index.js @@ -0,0 +1,29 @@ +export { isClickableInput } from './click/isClickableInput.js'; +export { readBlobText } from './dataTransfer/Blob.js'; +export { createDataTransfer, getBlobFromDataTransferItem } from './dataTransfer/DataTransfer.js'; +export { createFileList } from './dataTransfer/FileList.js'; +export { attachClipboardStubToView, createClipboardItem, detachClipboardStubFromView, readDataTransferFromClipboard, resetClipboardStubOnView, writeDataTransferToClipboard } from './dataTransfer/Clipboard.js'; +export { buildTimeValue, isValidDateOrTimeValue } from './edit/timeValue.js'; +export { getContentEditable, isContentEditable } from './edit/isContentEditable.js'; +export { isEditable, isEditableInputOrTextArea } from './edit/isEditable.js'; +export { getMaxLength, supportsMaxLength } from './edit/maxLength.js'; +export { setFiles } from './edit/setFiles.js'; +export { getNextCursorPosition } from './focus/cursor.js'; +export { getActiveElement, getActiveElementOrBody } from './focus/getActiveElement.js'; +export { getTabDestination } from './focus/getTabDestination.js'; +export { isFocusable } from './focus/isFocusable.js'; +export { hasNoSelection, hasOwnSelection } from './focus/selection.js'; +export { FOCUSABLE_SELECTOR } from './focus/selector.js'; +export { readNextDescriptor } from './keyDef/readNextDescriptor.js'; +export { cloneEvent } from './misc/cloneEvent.js'; +export { findClosest } from './misc/findClosest.js'; +export { getDocumentFromNode } from './misc/getDocumentFromNode.js'; +export { getTreeDiff } from './misc/getTreeDiff.js'; +export { getWindow } from './misc/getWindow.js'; +export { isDescendantOrSelf } from './misc/isDescendantOrSelf.js'; +export { isElementType } from './misc/isElementType.js'; +export { isVisible } from './misc/isVisible.js'; +export { isDisabled } from './misc/isDisabled.js'; +export { ApiLevel, getLevelRef, setLevelRef } from './misc/level.js'; +export { wait } from './misc/wait.js'; +export { assertPointerEvents, hasPointerEvents } from './pointer/cssPointerEvents.js'; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/keyDef/readNextDescriptor.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/keyDef/readNextDescriptor.js new file mode 100644 index 0000000000000000000000000000000000000000..dc6b4eb4743b06b8633a0459e6dcbb5ef411e209 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/keyDef/readNextDescriptor.js @@ -0,0 +1,90 @@ +var bracketDict = /*#__PURE__*/ function(bracketDict) { + bracketDict["{"] = "}"; + bracketDict["["] = "]"; + return bracketDict; +}(bracketDict || {}); +/** + * Read the next key definition from user input + * + * Describe key per `{descriptor}` or `[descriptor]`. + * Everything else will be interpreted as a single character as descriptor - e.g. `a`. + * Brackets `{` and `[` can be escaped by doubling - e.g. `foo[[bar` translates to `foo[bar`. + * A previously pressed key can be released per `{/descriptor}`. + * Keeping the key pressed can be written as `{descriptor>}`. + * When keeping the key pressed you can choose how long the key is pressed `{descriptor>3}`. + * You can then release the key per `{descriptor>3/}` or keep it pressed and continue with the next key. + */ function readNextDescriptor(text, context) { + let pos = 0; + const startBracket = text[pos] in bracketDict ? text[pos] : ''; + pos += startBracket.length; + const isEscapedChar = new RegExp(`^\\${startBracket}{2}`).test(text); + const type = isEscapedChar ? '' : startBracket; + return { + type, + ...type === '' ? readPrintableChar(text, pos, context) : readTag(text, pos, type, context) + }; +} +function readPrintableChar(text, pos, context) { + const descriptor = text[pos]; + assertDescriptor(descriptor, text, pos, context); + pos += descriptor.length; + return { + consumedLength: pos, + descriptor, + releasePrevious: false, + releaseSelf: true, + repeat: 1 + }; +} +function readTag(text, pos, startBracket, context) { + var _text_slice_match, _text_slice_match1; + const releasePreviousModifier = text[pos] === '/' ? '/' : ''; + pos += releasePreviousModifier.length; + const escapedDescriptor = startBracket === '{' && text[pos] === '\\'; + pos += Number(escapedDescriptor); + const descriptor = escapedDescriptor ? text[pos] : (_text_slice_match = text.slice(pos).match(startBracket === '{' ? /^\w+|^[^}>/]/ : /^\w+/)) === null || _text_slice_match === undefined ? undefined : _text_slice_match[0]; + assertDescriptor(descriptor, text, pos, context); + pos += descriptor.length; + var _text_slice_match_; + const repeatModifier = (_text_slice_match_ = (_text_slice_match1 = text.slice(pos).match(/^>\d+/)) === null || _text_slice_match1 === undefined ? undefined : _text_slice_match1[0]) !== null && _text_slice_match_ !== undefined ? _text_slice_match_ : ''; + pos += repeatModifier.length; + const releaseSelfModifier = text[pos] === '/' || !repeatModifier && text[pos] === '>' ? text[pos] : ''; + pos += releaseSelfModifier.length; + const expectedEndBracket = bracketDict[startBracket]; + const endBracket = text[pos] === expectedEndBracket ? expectedEndBracket : ''; + if (!endBracket) { + throw new Error(getErrorMessage([ + !repeatModifier && 'repeat modifier', + !releaseSelfModifier && 'release modifier', + `"${expectedEndBracket}"` + ].filter(Boolean).join(' or '), text[pos], text, context)); + } + pos += endBracket.length; + return { + consumedLength: pos, + descriptor, + releasePrevious: !!releasePreviousModifier, + repeat: repeatModifier ? Math.max(Number(repeatModifier.substr(1)), 1) : 1, + releaseSelf: hasReleaseSelf(releaseSelfModifier, repeatModifier) + }; +} +function assertDescriptor(descriptor, text, pos, context) { + if (!descriptor) { + throw new Error(getErrorMessage('key descriptor', text[pos], text, context)); + } +} +function hasReleaseSelf(releaseSelfModifier, repeatModifier) { + if (releaseSelfModifier) { + return releaseSelfModifier === '/'; + } + if (repeatModifier) { + return false; + } +} +function getErrorMessage(expected, found, text, context) { + return `Expected ${expected} but found "${found !== null && found !== undefined ? found : ''}" in "${text}" + See ${context === 'pointer' ? `https://testing-library.com/docs/user-event/pointer#pressing-a-button-or-touching-the-screen` : `https://testing-library.com/docs/user-event/keyboard`} + for more information about how userEvent parses your input.`; +} + +export { readNextDescriptor }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/cloneEvent.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/cloneEvent.js new file mode 100644 index 0000000000000000000000000000000000000000..fe6beedd627c5e619219095e46b88ab3c6d1a592 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/cloneEvent.js @@ -0,0 +1,5 @@ +function cloneEvent(event) { + return new event.constructor(event.type, event); +} + +export { cloneEvent }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/findClosest.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/findClosest.js new file mode 100644 index 0000000000000000000000000000000000000000..2761c03392899c0d0a6c87923394c6d9ad42060e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/findClosest.js @@ -0,0 +1,12 @@ +function findClosest(element, callback) { + let el = element; + do { + if (callback(el)) { + return el; + } + el = el.parentElement; + }while (el && el !== element.ownerDocument.body) + return undefined; +} + +export { findClosest }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/getDocumentFromNode.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/getDocumentFromNode.js new file mode 100644 index 0000000000000000000000000000000000000000..68100fbea1f88ff8f78a5bbb6d4d93300018296c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/getDocumentFromNode.js @@ -0,0 +1,8 @@ +function getDocumentFromNode(el) { + return isDocument(el) ? el : el.ownerDocument; +} +function isDocument(node) { + return node.nodeType === 9; +} + +export { getDocumentFromNode }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/getTreeDiff.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/getTreeDiff.js new file mode 100644 index 0000000000000000000000000000000000000000..31e363834a6057a0a58be4e58afcc73359e3e5e6 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/getTreeDiff.js @@ -0,0 +1,23 @@ +function getTreeDiff(a, b) { + const treeA = []; + for(let el = a; el; el = el.parentElement){ + treeA.push(el); + } + const treeB = []; + for(let el = b; el; el = el.parentElement){ + treeB.push(el); + } + let i = 0; + for(;; i++){ + if (i >= treeA.length || i >= treeB.length || treeA[treeA.length - 1 - i] !== treeB[treeB.length - 1 - i]) { + break; + } + } + return [ + treeA.slice(0, treeA.length - i), + treeB.slice(0, treeB.length - i), + treeB.slice(treeB.length - i) + ]; +} + +export { getTreeDiff }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/getWindow.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/getWindow.js new file mode 100644 index 0000000000000000000000000000000000000000..e63a5f4107252189971a45b0b34cc051c1b0abc2 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/getWindow.js @@ -0,0 +1,17 @@ +function getWindow(node) { + var _node_ownerDocument; + if (isDocument(node) && node.defaultView) { + return node.defaultView; + } else if ((_node_ownerDocument = node.ownerDocument) === null || _node_ownerDocument === undefined ? undefined : _node_ownerDocument.defaultView) { + return node.ownerDocument.defaultView; + } + throw new Error(`Could not determine window of node. Node was ${describe(node)}`); +} +function isDocument(node) { + return node.nodeType === 9; +} +function describe(val) { + return typeof val === 'function' ? `function ${val.name}` : val === null ? 'null' : String(val); +} + +export { getWindow }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/isDescendantOrSelf.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/isDescendantOrSelf.js new file mode 100644 index 0000000000000000000000000000000000000000..35de6ce8b021c541548ed0ed856f1b5f26374f02 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/isDescendantOrSelf.js @@ -0,0 +1,12 @@ +function isDescendantOrSelf(potentialDescendant, potentialAncestor) { + let el = potentialDescendant; + do { + if (el === potentialAncestor) { + return true; + } + el = el.parentElement; + }while (el) + return false; +} + +export { isDescendantOrSelf }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/isDisabled.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/isDisabled.js new file mode 100644 index 0000000000000000000000000000000000000000..0de339444159ba7034ef977f0f43500a984497de --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/isDisabled.js @@ -0,0 +1,31 @@ +import { isElementType } from './isElementType.js'; + +// This should probably just rely on the :disabled pseudo-class, but JSDOM doesn't implement it properly. +function isDisabled(element) { + for(let el = element; el; el = el.parentElement){ + if (isElementType(el, [ + 'button', + 'input', + 'select', + 'textarea', + 'optgroup', + 'option' + ])) { + if (el.hasAttribute('disabled')) { + return true; + } + } else if (isElementType(el, 'fieldset')) { + var _el_querySelector; + if (el.hasAttribute('disabled') && !((_el_querySelector = el.querySelector(':scope > legend')) === null || _el_querySelector === undefined ? undefined : _el_querySelector.contains(element))) { + return true; + } + } else if (el.tagName.includes('-')) { + if (el.constructor.formAssociated && el.hasAttribute('disabled')) { + return true; + } + } + } + return false; +} + +export { isDisabled }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/isElementType.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/isElementType.js new file mode 100644 index 0000000000000000000000000000000000000000..5d9cac04ef5bb27d30c27638ed7e23a8cfd18928 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/isElementType.js @@ -0,0 +1,18 @@ +function isElementType(element, tag, props) { + if (element.namespaceURI && element.namespaceURI !== 'http://www.w3.org/1999/xhtml') { + return false; + } + tag = Array.isArray(tag) ? tag : [ + tag + ]; + // tagName is uppercase in HTMLDocument and lowercase in XMLDocument + if (!tag.includes(element.tagName.toLowerCase())) { + return false; + } + if (props) { + return Object.entries(props).every(([k, v])=>element[k] === v); + } + return true; +} + +export { isElementType }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/isVisible.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/isVisible.js new file mode 100644 index 0000000000000000000000000000000000000000..df2b545bdbb701f5779b1474e549e6a872931c76 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/isVisible.js @@ -0,0 +1,17 @@ +import { getWindow } from './getWindow.js'; + +function isVisible(element) { + const window = getWindow(element); + for(let el = element; el === null || el === undefined ? undefined : el.ownerDocument; el = el.parentElement){ + const { display, visibility } = window.getComputedStyle(el); + if (display === 'none') { + return false; + } + if (visibility === 'hidden') { + return false; + } + } + return true; +} + +export { isVisible }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/level.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/level.js new file mode 100644 index 0000000000000000000000000000000000000000..2b7a057fd44a6e22355ea0ecdb1cd18f62f4fc81 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/level.js @@ -0,0 +1,13 @@ +var ApiLevel = /*#__PURE__*/ function(ApiLevel) { + ApiLevel[ApiLevel["Trigger"] = 2] = "Trigger"; + ApiLevel[ApiLevel["Call"] = 1] = "Call"; + return ApiLevel; +}({}); +function setLevelRef(instance, level) { + instance.levelRefs[level] = {}; +} +function getLevelRef(instance, level) { + return instance.levelRefs[level]; +} + +export { ApiLevel, getLevelRef, setLevelRef }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/wait.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/wait.js new file mode 100644 index 0000000000000000000000000000000000000000..743a1337fe97bcd84ed964d0d83a1afd0f319887 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/misc/wait.js @@ -0,0 +1,12 @@ +function wait(config) { + const delay = config.delay; + if (typeof delay !== 'number') { + return; + } + return Promise.all([ + new Promise((resolve)=>globalThis.setTimeout(()=>resolve(), delay)), + config.advanceTimers(delay) + ]); +} + +export { wait }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/pointer/cssPointerEvents.js b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/pointer/cssPointerEvents.js new file mode 100644 index 0000000000000000000000000000000000000000..1b35fced4b1ff3b9ed65cb99147507f21d7f80e8 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/esm/utils/pointer/cssPointerEvents.js @@ -0,0 +1,100 @@ +import { PointerEventsCheckLevel } from '../../options.js'; +import { getWindow } from '../misc/getWindow.js'; +import { isElementType } from '../misc/isElementType.js'; +import { ApiLevel, getLevelRef } from '../misc/level.js'; + +function hasPointerEvents(instance, element) { + var _checkPointerEvents; + return ((_checkPointerEvents = checkPointerEvents(instance, element)) === null || _checkPointerEvents === undefined ? undefined : _checkPointerEvents.pointerEvents) !== 'none'; +} +function closestPointerEventsDeclaration(element) { + const window = getWindow(element); + for(let el = element, tree = []; el === null || el === undefined ? undefined : el.ownerDocument; el = el.parentElement){ + tree.push(el); + const pointerEvents = window.getComputedStyle(el).pointerEvents; + if (pointerEvents && ![ + 'inherit', + 'unset' + ].includes(pointerEvents)) { + return { + pointerEvents, + tree + }; + } + } + return undefined; +} +const PointerEventsCheck = Symbol('Last check for pointer-events'); +function checkPointerEvents(instance, element) { + const lastCheck = element[PointerEventsCheck]; + const needsCheck = instance.config.pointerEventsCheck !== PointerEventsCheckLevel.Never && (!lastCheck || hasBitFlag(instance.config.pointerEventsCheck, PointerEventsCheckLevel.EachApiCall) && lastCheck[ApiLevel.Call] !== getLevelRef(instance, ApiLevel.Call) || hasBitFlag(instance.config.pointerEventsCheck, PointerEventsCheckLevel.EachTrigger) && lastCheck[ApiLevel.Trigger] !== getLevelRef(instance, ApiLevel.Trigger)); + if (!needsCheck) { + return lastCheck === null || lastCheck === undefined ? undefined : lastCheck.result; + } + const declaration = closestPointerEventsDeclaration(element); + element[PointerEventsCheck] = { + [ApiLevel.Call]: getLevelRef(instance, ApiLevel.Call), + [ApiLevel.Trigger]: getLevelRef(instance, ApiLevel.Trigger), + result: declaration + }; + return declaration; +} +function assertPointerEvents(instance, element) { + const declaration = checkPointerEvents(instance, element); + if ((declaration === null || declaration === undefined ? undefined : declaration.pointerEvents) === 'none') { + throw new Error([ + `Unable to perform pointer interaction as the element ${declaration.tree.length > 1 ? 'inherits' : 'has'} \`pointer-events: none\`:`, + '', + printTree(declaration.tree) + ].join('\n')); + } +} +function printTree(tree) { + return tree.reverse().map((el, i)=>[ + ''.padEnd(i), + el.tagName, + el.id && `#${el.id}`, + el.hasAttribute('data-testid') && `(testId=${el.getAttribute('data-testid')})`, + getLabelDescr(el), + tree.length > 1 && i === 0 && ' <-- This element declared `pointer-events: none`', + tree.length > 1 && i === tree.length - 1 && ' <-- Asserted pointer events here' + ].filter(Boolean).join('')).join('\n'); +} +function getLabelDescr(element) { + var _element_labels; + let label; + if (element.hasAttribute('aria-label')) { + label = element.getAttribute('aria-label'); + } else if (element.hasAttribute('aria-labelledby')) { + var _element_ownerDocument_getElementById_textContent, _element_ownerDocument_getElementById; + label = (_element_ownerDocument_getElementById = element.ownerDocument.getElementById(element.getAttribute('aria-labelledby'))) === null || _element_ownerDocument_getElementById === undefined ? undefined : (_element_ownerDocument_getElementById_textContent = _element_ownerDocument_getElementById.textContent) === null || _element_ownerDocument_getElementById_textContent === undefined ? undefined : _element_ownerDocument_getElementById_textContent.trim(); + } else if (isElementType(element, [ + 'button', + 'input', + 'meter', + 'output', + 'progress', + 'select', + 'textarea' + ]) && ((_element_labels = element.labels) === null || _element_labels === undefined ? undefined : _element_labels.length)) { + label = Array.from(element.labels).map((el)=>{ + var _el_textContent; + return (_el_textContent = el.textContent) === null || _el_textContent === undefined ? undefined : _el_textContent.trim(); + }).join('|'); + } else if (isElementType(element, 'button')) { + var _element_textContent; + label = (_element_textContent = element.textContent) === null || _element_textContent === undefined ? undefined : _element_textContent.trim(); + } + label = label === null || label === undefined ? undefined : label.replace(/\n/g, ' '); + if (Number(label === null || label === undefined ? undefined : label.length) > 30) { + label = `${label === null || label === undefined ? undefined : label.substring(0, 29)}…`; + } + return label ? `(label=${label})` : ''; +} +// With the eslint rule and prettier the bitwise operation isn't nice to read +function hasBitFlag(conf, flag) { + // eslint-disable-next-line no-bitwise + return (conf & flag) > 0; +} + +export { assertPointerEvents, hasPointerEvents }; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/clipboard/copy.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/clipboard/copy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e37d0eddb58331448d89647643956a97a1807da4 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/clipboard/copy.d.ts @@ -0,0 +1,2 @@ +import { type Instance } from '../setup'; +export declare function copy(this: Instance): Promise; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/clipboard/cut.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/clipboard/cut.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e826c205f28b798b7cdb210b956994eca71262b9 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/clipboard/cut.d.ts @@ -0,0 +1,2 @@ +import { type Instance } from '../setup'; +export declare function cut(this: Instance): Promise; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/clipboard/index.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/clipboard/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c23fdc563def120ec6889b6c0a5c181de9b75202 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/clipboard/index.d.ts @@ -0,0 +1,3 @@ +export * from './copy'; +export * from './cut'; +export * from './paste'; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/clipboard/paste.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/clipboard/paste.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9118135c00636f49c9752e1e7f6250221c2b937f --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/clipboard/paste.d.ts @@ -0,0 +1,2 @@ +import { type Instance } from '../setup'; +export declare function paste(this: Instance, clipboardData?: DataTransfer | string): Promise; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/convenience/click.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/convenience/click.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f6fe5af119d90b0a3e7bd3a5439a0c5bcf904e5c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/convenience/click.d.ts @@ -0,0 +1,4 @@ +import { type Instance } from '../setup'; +export declare function click(this: Instance, element: Element): Promise; +export declare function dblClick(this: Instance, element: Element): Promise; +export declare function tripleClick(this: Instance, element: Element): Promise; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/convenience/hover.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/convenience/hover.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..84775dbcaaee54d281b2301fc872e07ba2cb1409 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/convenience/hover.d.ts @@ -0,0 +1,3 @@ +import { type Instance } from '../setup'; +export declare function hover(this: Instance, element: Element): Promise; +export declare function unhover(this: Instance, element: Element): Promise; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/convenience/index.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/convenience/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..68f52e7045369f219957ca4b039f0df1e0cb2d2a --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/convenience/index.d.ts @@ -0,0 +1,3 @@ +export * from './click'; +export * from './hover'; +export * from './tab'; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/convenience/tab.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/convenience/tab.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0b06c31bcd5beef83ac0dcdfe55a520ac64509cf --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/convenience/tab.d.ts @@ -0,0 +1,4 @@ +import { type Instance } from '../setup'; +export declare function tab(this: Instance, { shift, }?: { + shift?: boolean; +}): Promise; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/document/UI.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/document/UI.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..98fdc25dd8689e6bacaa9438cc1a7a562d47257c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/document/UI.d.ts @@ -0,0 +1,42 @@ +declare const UIValue: unique symbol; +declare const UISelection: unique symbol; +declare const InitialValue: unique symbol; +declare global { + interface Element { + [UIValue]?: string; + [InitialValue]?: string; + [UISelection]?: UISelection; + } +} +interface UISelection { + anchorOffset: number; + focusOffset: number; +} +export type UIValueString = String & { + [UIValue]: true; +}; +export type UISelectionStart = Number & { + [UISelection]: true; +}; +export declare function isUIValue(value: string | UIValueString): value is UIValueString; +export declare function isUISelectionStart(start: number | UISelectionStart | null): start is UISelectionStart; +export declare function setUIValue(element: HTMLInputElement | HTMLTextAreaElement, value: string): void; +export declare function getUIValue(element: HTMLInputElement | HTMLTextAreaElement): string; +/** Flag the IDL value as clean. This does not change the value.*/ +export declare function setUIValueClean(element: HTMLInputElement | HTMLTextAreaElement): void; +export declare function clearInitialValue(element: HTMLInputElement | HTMLTextAreaElement): void; +export declare function getInitialValue(element: HTMLInputElement | HTMLTextAreaElement): string | undefined; +export declare function setUISelectionRaw(element: HTMLInputElement | HTMLTextAreaElement, selection: UISelection): void; +export declare function setUISelection(element: HTMLInputElement | HTMLTextAreaElement, { focusOffset: focusOffsetParam, anchorOffset: anchorOffsetParam, }: { + anchorOffset?: number; + focusOffset: number; +}, mode?: 'replace' | 'modify'): void; +export type UISelectionRange = UISelection & { + startOffset: number; + endOffset: number; +}; +export declare function getUISelection(element: HTMLInputElement | HTMLTextAreaElement): UISelectionRange; +export declare function hasUISelection(element: HTMLInputElement | HTMLTextAreaElement): boolean; +/** Flag the IDL selection as clean. This does not change the selection. */ +export declare function setUISelectionClean(element: HTMLInputElement | HTMLTextAreaElement): void; +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/document/copySelection.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/document/copySelection.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e32d1bd15cb559b03e51cd235609b26d470496df --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/document/copySelection.d.ts @@ -0,0 +1 @@ +export declare function copySelection(target: Element): DataTransfer; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/document/getValueOrTextContent.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/document/getValueOrTextContent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..614403cc29f2a269ef0ba035c9dfadd1946993cf --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/document/getValueOrTextContent.d.ts @@ -0,0 +1 @@ +export declare function getValueOrTextContent(element: T): T extends HTMLInputElement | HTMLTextAreaElement ? string : string | null; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/document/index.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/document/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c251e2f838cdc425402b816c24049c36cb72c475 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/document/index.d.ts @@ -0,0 +1,5 @@ +export { getUISelection, getUIValue, setUISelection, setUIValue, clearInitialValue, } from './UI'; +export type { UISelectionRange } from './UI'; +export { getValueOrTextContent } from './getValueOrTextContent'; +export { copySelection } from './copySelection'; +export { commitValueAfterInput } from './trackValue'; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/document/interceptor.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/document/interceptor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c776510fb13072c19fbfd7f8894f6cfb5569786 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/document/interceptor.d.ts @@ -0,0 +1,19 @@ +type anyFunc = (...a: any[]) => any; +type Params = Prop extends anyFunc ? Parameters : [Prop]; +type ImplReturn = Prop extends anyFunc ? Parameters : Prop; +export declare function prepareInterceptor(element: ElementType, propName: PropName, interceptorImpl: (this: ElementType, ...args: Params) => { + /** + * React tracks the changes on element properties. + * This workaround tries to alter the DOM element without React noticing, + * so that it later picks up the change. + * + * @see https://github.com/facebook/react/blob/148f8e497c7d37a3c7ab99f01dec2692427272b1/packages/react-dom/src/client/inputValueTracking.js#L51-L104 + */ + applyNative?: boolean; + realArgs?: ImplReturn; + then?: () => void; +}): void; +export declare function prepareValueInterceptor(element: HTMLInputElement | HTMLTextAreaElement): void; +export declare function prepareSelectionInterceptor(element: HTMLInputElement | HTMLTextAreaElement): void; +export declare function prepareRangeTextInterceptor(element: HTMLInputElement | HTMLTextAreaElement): void; +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/document/patchFocus.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/document/patchFocus.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..46e33743a9b23df2b8d8b5c7d70e158a84c6a256 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/document/patchFocus.d.ts @@ -0,0 +1,9 @@ +declare const patched: unique symbol; +declare global { + interface HTMLElement { + readonly [patched]?: Pick; + } +} +export declare function patchFocus(HTMLElement: typeof globalThis['HTMLElement']): void; +export declare function restoreFocus(HTMLElement: typeof globalThis['HTMLElement']): void; +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/document/prepareDocument.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/document/prepareDocument.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..04d9a770d2aa3c72f20aadd210a5dfb585bcf43e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/document/prepareDocument.d.ts @@ -0,0 +1,8 @@ +declare const isPrepared: unique symbol; +declare global { + interface Node { + [isPrepared]?: typeof isPrepared; + } +} +export declare function prepareDocument(document: Document): void; +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/document/trackValue.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/document/trackValue.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..08d24cdc04b2976532296e93d32941ad709d9abe --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/document/trackValue.d.ts @@ -0,0 +1,17 @@ +declare const TrackChanges: unique symbol; +declare global { + interface Window { + REACT_VERSION?: number; + } + interface Element { + [TrackChanges]?: { + previousValue?: string; + tracked?: string[]; + nextValue?: string; + }; + } +} +export declare function startTrackValue(element: HTMLInputElement | HTMLTextAreaElement): void; +export declare function trackOrSetValue(element: HTMLInputElement | HTMLTextAreaElement, v: string): void; +export declare function commitValueAfterInput(element: HTMLInputElement | HTMLTextAreaElement, cursorOffset: number): void; +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/click.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/click.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/click.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/cut.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/cut.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/cut.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/index.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..28efbb6cc62a89bcfb39c4a38e7265e9f8785043 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/index.d.ts @@ -0,0 +1,8 @@ +import './click'; +import './cut'; +import './keydown'; +import './keypress'; +import './keyup'; +import './paste'; +export { behavior } from './registry'; +export type { BehaviorPlugin } from './registry'; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/keydown.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/keydown.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/keydown.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/keypress.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/keypress.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/keypress.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/keyup.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/keyup.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/keyup.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/paste.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/paste.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/paste.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/registry.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/registry.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7a58c2e4c43005b7e518b00cef9a32155c3e56ae --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/behavior/registry.d.ts @@ -0,0 +1,9 @@ +import { type Instance } from '../../setup'; +import { EventType } from '../types'; +export interface BehaviorPlugin { + (event: DocumentEventMap[Type], target: Element, instance: Instance): // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + void | (() => void); +} +export declare const behavior: { + [Type in EventType]?: BehaviorPlugin; +}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/createEvent.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/createEvent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e38efb7c676e69dba0c4a2bcaf4b795af3e08a3 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/createEvent.d.ts @@ -0,0 +1,2 @@ +import { type EventType, type EventTypeInit, type FixedDocumentEventMap } from './types'; +export declare function createEvent(type: K, target: Element, init?: EventTypeInit): FixedDocumentEventMap[K]; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/dispatchEvent.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/dispatchEvent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..de8df88a7ac414bcab01768df435900fd321d40b --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/dispatchEvent.d.ts @@ -0,0 +1,5 @@ +import { type Instance } from '../setup'; +import { EventType, EventTypeInit } from './types'; +export declare function dispatchUIEvent(this: Instance, target: Element, type: K, init?: EventTypeInit, preventDefault?: boolean): boolean; +export declare function dispatchEvent(this: Instance, target: Element, event: Event, preventDefault?: boolean): boolean; +export declare function dispatchDOMEvent(target: Element, type: K, init?: EventTypeInit): void; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/eventMap.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/eventMap.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7a915b08fa0c02cdcfe560b54417ab295502d992 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/eventMap.d.ts @@ -0,0 +1,265 @@ +import { EventType } from './types'; +export declare const eventMap: { + readonly auxclick: { + readonly EventType: "PointerEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly beforeinput: { + readonly EventType: "InputEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly blur: { + readonly EventType: "FocusEvent"; + readonly defaultInit: { + readonly bubbles: false; + readonly cancelable: false; + readonly composed: true; + }; + }; + readonly click: { + readonly EventType: "PointerEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly contextmenu: { + readonly EventType: "PointerEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly copy: { + readonly EventType: "ClipboardEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly change: { + readonly EventType: "Event"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: false; + }; + }; + readonly cut: { + readonly EventType: "ClipboardEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly dblclick: { + readonly EventType: "MouseEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly focus: { + readonly EventType: "FocusEvent"; + readonly defaultInit: { + readonly bubbles: false; + readonly cancelable: false; + readonly composed: true; + }; + }; + readonly focusin: { + readonly EventType: "FocusEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: false; + readonly composed: true; + }; + }; + readonly focusout: { + readonly EventType: "FocusEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: false; + readonly composed: true; + }; + }; + readonly keydown: { + readonly EventType: "KeyboardEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly keypress: { + readonly EventType: "KeyboardEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly keyup: { + readonly EventType: "KeyboardEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly paste: { + readonly EventType: "ClipboardEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly input: { + readonly EventType: "InputEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: false; + readonly composed: true; + }; + }; + readonly mousedown: { + readonly EventType: "MouseEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly mouseenter: { + readonly EventType: "MouseEvent"; + readonly defaultInit: { + readonly bubbles: false; + readonly cancelable: false; + readonly composed: true; + }; + }; + readonly mouseleave: { + readonly EventType: "MouseEvent"; + readonly defaultInit: { + readonly bubbles: false; + readonly cancelable: false; + readonly composed: true; + }; + }; + readonly mousemove: { + readonly EventType: "MouseEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly mouseout: { + readonly EventType: "MouseEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly mouseover: { + readonly EventType: "MouseEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly mouseup: { + readonly EventType: "MouseEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly pointerover: { + readonly EventType: "PointerEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly pointerenter: { + readonly EventType: "PointerEvent"; + readonly defaultInit: { + readonly bubbles: false; + readonly cancelable: false; + }; + }; + readonly pointerdown: { + readonly EventType: "PointerEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly pointermove: { + readonly EventType: "PointerEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly pointerup: { + readonly EventType: "PointerEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly pointercancel: { + readonly EventType: "PointerEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: false; + readonly composed: true; + }; + }; + readonly pointerout: { + readonly EventType: "PointerEvent"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + readonly composed: true; + }; + }; + readonly pointerleave: { + readonly EventType: "PointerEvent"; + readonly defaultInit: { + readonly bubbles: false; + readonly cancelable: false; + }; + }; + readonly submit: { + readonly EventType: "Event"; + readonly defaultInit: { + readonly bubbles: true; + readonly cancelable: true; + }; + }; +}; +export declare function isMouseEvent(type: EventType): boolean; +export declare function isKeyboardEvent(type: EventType): boolean; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/focus.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/focus.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6757e6b5c1379f5b4636bb6a5a4f06a6b8ed0628 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/focus.d.ts @@ -0,0 +1,5 @@ +/** + * Focus closest focusable element. + */ +export declare function focusElement(element: Element): void; +export declare function blurElement(element: Element): void; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/index.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..95034b9d6ccc9669ffe5e3c83207c4ceee23655d --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/index.d.ts @@ -0,0 +1,7 @@ +import { EventType, PointerCoords } from './types'; +export type { EventType, PointerCoords }; +export { dispatchEvent, dispatchUIEvent, dispatchDOMEvent } from './dispatchEvent'; +export { blurElement, focusElement } from './focus'; +export { input } from './input'; +export type { SelectionRange } from './selection'; +export { isAllSelected, modifySelectionPerMouseMove, setSelectionPerMouseDown, selectAll, } from './selection'; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/input.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/input.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..949759bf379149998e7f946fa262b554ce9cdb09 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/input.d.ts @@ -0,0 +1,2 @@ +import { type Instance } from '../setup'; +export declare function input(instance: Instance, element: Element, data: string, inputType?: string): void; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/radio.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/radio.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a15e125f0b2af9fc785262058c554ae400a1c0af --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/radio.d.ts @@ -0,0 +1,4 @@ +import { type Instance } from '../setup'; +export declare function walkRadio(instance: Instance, el: HTMLInputElement & { + type: 'radio'; +}, direction: -1 | 1): void; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/getInputRange.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/getInputRange.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bccf6bc7befe41df84a08d2e3538232afa3ef247 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/getInputRange.d.ts @@ -0,0 +1,5 @@ +import { UISelectionRange } from '../../document'; +/** + * Get the range that would be overwritten by input. + */ +export declare function getInputRange(focusNode: Node): UISelectionRange | Range | undefined; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/getTargetTypeAndSelection.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/getTargetTypeAndSelection.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..274966d4121df1e3c2b868013a20e7108388d156 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/getTargetTypeAndSelection.d.ts @@ -0,0 +1,10 @@ +/** + * Determine which selection logic and selection ranges to consider. + */ +export declare function getTargetTypeAndSelection(node: Node): { + readonly type: "input"; + readonly selection: import("../../document").UISelectionRange; +} | { + readonly type: "contenteditable" | "default"; + readonly selection: Selection | null | undefined; +}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/index.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a01fcce03026860761d41086193f4a85ac554c7e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/index.d.ts @@ -0,0 +1,15 @@ +import { type EditableInputOrTextarea } from '../../utils'; +export { getInputRange } from './getInputRange'; +export { modifySelection } from './modifySelection'; +export { moveSelection } from './moveSelection'; +export { setSelectionPerMouseDown } from './setSelectionPerMouse'; +export { modifySelectionPerMouseMove } from './modifySelectionPerMouse'; +export { isAllSelected, selectAll } from './selectAll'; +export { setSelectionRange } from './setSelectionRange'; +export { setSelection } from './setSelection'; +export { updateSelectionOnFocus } from './updateSelectionOnFocus'; +export type SelectionRange = { + node: EditableInputOrTextarea; + start: number; + end: number; +}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/modifySelection.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/modifySelection.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b5d59279b1a81373498d9f9eb3c348d90df44078 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/modifySelection.d.ts @@ -0,0 +1,8 @@ +/** + * Extend/shrink the selection like with Shift+Arrows or Shift+Mouse + */ +export declare function modifySelection({ focusNode, focusOffset, }: { + focusNode: Node; + /** DOM Offset */ + focusOffset: number; +}): void; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/modifySelectionPerMouse.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/modifySelectionPerMouse.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..364d821507375f0c32eb45b6db5826c16e7d723e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/modifySelectionPerMouse.d.ts @@ -0,0 +1,7 @@ +import { type SelectionRange } from '.'; +export declare function modifySelectionPerMouseMove(selectionRange: Range | SelectionRange, { document, target, node, offset, }: { + document: Document; + target: Element; + node?: Node; + offset?: number; +}): void; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/moveSelection.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/moveSelection.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9b78a1c987dc643f1d9d9d6d52bfb8dafb649aef --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/moveSelection.d.ts @@ -0,0 +1,4 @@ +/** + * Move the selection + */ +export declare function moveSelection(node: Element, direction: -1 | 1): void; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/resolveCaretPosition.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/resolveCaretPosition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..11f63d6df8c837a408b28b4282b595fecee36ee2 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/resolveCaretPosition.d.ts @@ -0,0 +1,8 @@ +export declare function resolveCaretPosition({ target, node, offset, }: { + target: Element; + node?: Node; + offset?: number; +}): { + node: Node; + offset: number; +}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/selectAll.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/selectAll.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7464ac6a47f7f831453b3732882278e17f0bb592 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/selectAll.d.ts @@ -0,0 +1,5 @@ +/** + * Expand a selection like the browser does when pressing Ctrl+A. + */ +export declare function selectAll(target: Element): void; +export declare function isAllSelected(target: Element): boolean; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/setSelection.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/setSelection.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1f590272092b9fbc8a4499998726164f53af7372 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/setSelection.d.ts @@ -0,0 +1,10 @@ +/** + * Set the selection + */ +export declare function setSelection({ focusNode, focusOffset, anchorNode, anchorOffset, }: { + anchorNode?: Node; + /** DOM offset */ + anchorOffset?: number; + focusNode: Node; + focusOffset: number; +}): void; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/setSelectionPerMouse.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/setSelectionPerMouse.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b9c9804e70f9f36aa7dde7f00e16e1e6074414f --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/setSelectionPerMouse.d.ts @@ -0,0 +1,8 @@ +import { type SelectionRange } from '.'; +export declare function setSelectionPerMouseDown({ document, target, clickCount, node, offset, }: { + document: Document; + target: Element; + clickCount: number; + node?: Node; + offset?: number; +}): Range | SelectionRange | undefined; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/setSelectionRange.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/setSelectionRange.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ac6b1a3656b0d48a8a6ac7d1510eca5dd5d5135 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/setSelectionRange.d.ts @@ -0,0 +1,6 @@ +/** + * Backward-compatible selection. + * + * Handles input elements and contenteditable if it only contains a single text node. + */ +export declare function setSelectionRange(element: Element, anchorOffset: number, focusOffset: number): void; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/updateSelectionOnFocus.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/updateSelectionOnFocus.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8df69e9cc3a41a7a9d48b6867dfa1e7de958d9dc --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/selection/updateSelectionOnFocus.d.ts @@ -0,0 +1,5 @@ +/** + * Reset the Document Selection when moving focus into an element + * with own selection implementation. + */ +export declare function updateSelectionOnFocus(element: Element): void; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/types.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..20f0f69d2d85e3daa009a9f5ad5d2c5696e6fa14 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/types.d.ts @@ -0,0 +1,20 @@ +import { eventMap } from './eventMap'; +export type EventType = keyof typeof eventMap; +export type EventTypeInit = SpecificEventInit; +export interface FixedDocumentEventMap extends DocumentEventMap { + input: InputEvent; +} +type SpecificEventInit = E extends InputEvent ? InputEventInit : E extends ClipboardEvent ? ClipboardEventInit : E extends KeyboardEvent ? KeyboardEventInit : E extends PointerEvent ? PointerEventInit : E extends MouseEvent ? MouseEventInit : E extends FocusEvent ? FocusEventInit : E extends UIEvent ? UIEventInit : EventInit; +export interface PointerCoords { + x?: number; + y?: number; + clientX?: number; + clientY?: number; + offsetX?: number; + offsetY?: number; + pageX?: number; + pageY?: number; + screenX?: number; + screenY?: number; +} +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/event/wrapEvent.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/wrapEvent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0662a0e337d47c1fb4a159e09633e5c354343aa0 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/event/wrapEvent.d.ts @@ -0,0 +1 @@ +export declare function wrapEvent(cb: () => R, _element: Element): R; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/index.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dfe8ff68fcf6a0d86c9755cadf794f369611f20f --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/index.d.ts @@ -0,0 +1,6 @@ +export { userEvent as default } from './setup'; +export { userEvent } from './setup'; +export type { UserEvent } from './setup/setup'; +export type { keyboardKey } from './system/keyboard'; +export type { pointerKey } from './system/pointer'; +export { PointerEventsCheckLevel, type Options } from './options'; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/keyboard/index.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/keyboard/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4d4edd003a6d5bde3e89b917ffcda6bf1e8bd55a --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/keyboard/index.d.ts @@ -0,0 +1,3 @@ +import { type Instance } from '../setup'; +export declare function keyboard(this: Instance, text: string): Promise; +export declare function releaseAllKeys(instance: Instance): Promise; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/keyboard/keyMap.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/keyboard/keyMap.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..aa1a26f5ce2f5aaefc4af6b654130f153ee7ed64 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/keyboard/keyMap.d.ts @@ -0,0 +1,5 @@ +import { keyboardKey } from '../system/keyboard'; +/** + * Mapping for a default US-104-QWERTY keyboard + */ +export declare const defaultKeyMap: keyboardKey[]; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/keyboard/parseKeyDef.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/keyboard/parseKeyDef.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b7794ad5c7552f2aa86719c0baa27774c5bd6b9b --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/keyboard/parseKeyDef.d.ts @@ -0,0 +1,17 @@ +import { keyboardKey } from '../system/keyboard'; +/** + * Parse key definitions per `keyboardMap` + * + * Keys can be referenced by `{key}` or `{special}` as well as physical locations per `[code]`. + * Everything else will be interpreted as a typed character - e.g. `a`. + * Brackets `{` and `[` can be escaped by doubling - e.g. `foo[[bar` translates to `foo[bar`. + * Keeping the key pressed can be written as `{key>}`. + * When keeping the key pressed you can choose how long (how many keydown and keypress) the key is pressed `{key>3}`. + * You can then release the key per `{key>3/}` or keep it pressed and continue with the next key. + */ +export declare function parseKeyDef(keyboardMap: keyboardKey[], text: string): { + keyDef: keyboardKey; + releasePrevious: boolean; + releaseSelf: boolean; + repeat: number; +}[]; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/options.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c421693a26c9c4031bbcec5b16660773d4332201 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/options.d.ts @@ -0,0 +1,115 @@ +import { type keyboardKey } from './system/keyboard'; +import { type pointerKey } from './system/pointer'; +export declare enum PointerEventsCheckLevel { + /** + * Check pointer events on every user interaction that triggers a bunch of events. + * E.g. once for releasing a mouse button even though this triggers `pointerup`, `mouseup`, `click`, etc... + */ + EachTrigger = 4, + /** Check each target once per call to pointer (related) API */ + EachApiCall = 2, + /** Check each event target once */ + EachTarget = 1, + /** No pointer events check */ + Never = 0 +} +export interface Options { + /** + * When using `userEvent.upload`, automatically discard files + * that don't match an `accept` property if it exists. + * + * @default true + */ + applyAccept?: boolean; + /** + * We intend to automatically apply modifier keys for printable characters in the future. + * I.e. `A` implying `{Shift>}a{/Shift}` if caps lock is not active. + * + * This options allows you to opt out of this change in foresight. + * The feature therefore will not constitute a breaking change. + * + * @default true + */ + autoModify?: boolean; + /** + * Between some subsequent inputs like typing a series of characters + * the code execution is delayed per `setTimeout` for (at least) `delay` milliseconds. + * This moves the next changes at least to next macro task + * and allows other (asynchronous) code to run between events. + * + * `null` prevents `setTimeout` from being called. + * + * @default 0 + */ + delay?: number | null; + /** + * The document. + * + * This defaults to the owner document of an element if an API is called directly with an element and without setup. + * Otherwise it falls back to the global document. + * + * @default element.ownerDocument??globalThis.document + */ + document?: Document; + /** + * An array of keyboard keys the keyboard device consists of. + * + * This allows to plug in different layouts / localizations. + * + * Defaults to a "standard" US-104-QWERTY keyboard. + */ + keyboardMap?: keyboardKey[]; + /** + * An array of available pointer keys. + * + * This allows to plug in different pointer devices. + */ + pointerMap?: pointerKey[]; + /** + * The pointer API includes a check if an element has or inherits `pointer-events: none`. + * This check is known to be expensive and very expensive when checking deeply nested nodes. + * This option determines how often the pointer related APIs perform the check. + * + * This is a binary flag option. You can combine multiple Levels. + * + * @default PointerEventsCheckLevel.EachCall + */ + pointerEventsCheck?: PointerEventsCheckLevel | number; + /** + * `userEvent.type` automatically releases any keys still pressed at the end of the call. + * This option allows to opt out of this feature. + * + * @default false + */ + skipAutoClose?: boolean; + /** + * `userEvent.type` implies a click at the end of the element content/value. + * This option allows to opt out of this feature. + * + * @default false + */ + skipClick?: boolean; + /** + * `userEvent.click` implies moving the cursor to the target element first. + * This options allows to opt out of this feature. + * + * @default false + */ + skipHover?: boolean; + /** + * Write selected data to Clipboard API when a `cut` or `copy` is triggered. + * + * The Clipboard API is usually not available to test code. + * Our `setup` replaces the `navigator.clipboard` property with a stub. + * + * Defaults to `false` when calling the APIs directly. + * Defaults to `true` when calling the APIs per `setup`. + */ + writeToClipboard?: boolean; + /** + * A function to be called internally to advance your fake timers (if applicable) + * + * @example jest.advanceTimersByTime + */ + advanceTimers?: ((delay: number) => Promise) | ((delay: number) => void); +} diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/pointer/index.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/pointer/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a12beaa4f824c979cb617b4c8d222fef58203a1d --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/pointer/index.d.ts @@ -0,0 +1,28 @@ +import { type PointerCoords } from '../event'; +import { type Instance } from '../setup'; +import { type pointerKey } from '../system/pointer'; +type PointerActionInput = string | ({ + keys: string; +} & PointerActionPosition) | PointerAction; +export type PointerInput = PointerActionInput | Array; +type PointerAction = PointerPressAction | PointerMoveAction; +type PointerActionPosition = { + target?: Element; + coords?: PointerCoords; + node?: Node; + /** + * If `node` is set, this is the DOM offset. + * Otherwise this is the `textContent`/`value` offset on the `target`. + */ + offset?: number; +}; +interface PointerPressAction extends PointerActionPosition { + keyDef: pointerKey; + releasePrevious: boolean; + releaseSelf: boolean; +} +interface PointerMoveAction extends PointerActionPosition { + pointerName?: string; +} +export declare function pointer(this: Instance, input: PointerInput): Promise; +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/pointer/keyMap.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/pointer/keyMap.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..32c8fd971e5d8f67c6cb9bf22aa725b0aa5f1809 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/pointer/keyMap.d.ts @@ -0,0 +1,2 @@ +import { pointerKey } from '../system/pointer'; +export declare const defaultKeyMap: pointerKey[]; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/pointer/parseKeyDef.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/pointer/parseKeyDef.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..920ef599696009fd05f0055d2436fc9932499152 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/pointer/parseKeyDef.d.ts @@ -0,0 +1,6 @@ +import { pointerKey } from '../system/pointer'; +export declare function parseKeyDef(pointerMap: pointerKey[], keys: string): { + keyDef: pointerKey; + releasePrevious: boolean; + releaseSelf: boolean; +}[]; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/setup/api.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/setup/api.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..697f4b3873a21bfdf97f1bff7fb1bb495c847f3e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/setup/api.d.ts @@ -0,0 +1,23 @@ +import { click, dblClick, tripleClick, hover, unhover, tab } from '../convenience'; +import { keyboard } from '../keyboard'; +import { copy, cut, paste } from '../clipboard'; +import { pointer } from '../pointer'; +import { clear, deselectOptions, selectOptions, type, upload } from '../utility'; +export declare const userEventApi: { + click: typeof click; + dblClick: typeof dblClick; + tripleClick: typeof tripleClick; + hover: typeof hover; + unhover: typeof unhover; + tab: typeof tab; + keyboard: typeof keyboard; + copy: typeof copy; + cut: typeof cut; + paste: typeof paste; + pointer: typeof pointer; + clear: typeof clear; + deselectOptions: typeof deselectOptions; + selectOptions: typeof selectOptions; + type: typeof type; + upload: typeof upload; +}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/setup/directApi.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/setup/directApi.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..16046c334c2e6205bde6f13dd95da36a3619c389 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/setup/directApi.d.ts @@ -0,0 +1,24 @@ +import { type Options } from '../options'; +import { type PointerInput } from '../pointer'; +import { type System } from '../system'; +import { type UserEventApi } from './setup'; +export type DirectOptions = Options & { + keyboardState?: System; + pointerState?: System; +}; +export declare function clear(element: Element): Promise; +export declare function click(element: Element, options?: DirectOptions): Promise; +export declare function copy(options?: DirectOptions): Promise; +export declare function cut(options?: DirectOptions): Promise; +export declare function dblClick(element: Element, options?: DirectOptions): Promise; +export declare function deselectOptions(select: Element, values: HTMLElement | HTMLElement[] | string[] | string, options?: DirectOptions): Promise; +export declare function hover(element: Element, options?: DirectOptions): Promise; +export declare function keyboard(text: string, options?: DirectOptions): Promise; +export declare function pointer(input: PointerInput, options?: DirectOptions): Promise; +export declare function paste(clipboardData?: DataTransfer | string, options?: DirectOptions): Promise; +export declare function selectOptions(select: Element, values: HTMLElement | HTMLElement[] | string[] | string, options?: DirectOptions): Promise; +export declare function tripleClick(element: Element, options?: DirectOptions): Promise; +export declare function type(element: Element, text: string, options?: DirectOptions & Parameters[2]): Promise; +export declare function unhover(element: Element, options?: DirectOptions): Promise; +export declare function upload(element: HTMLElement, fileOrFiles: File | File[], options?: DirectOptions): Promise; +export declare function tab(options?: DirectOptions & Parameters[0]): Promise; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/setup/index.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/setup/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2bc2f11a2e117a22bc6f44414adc6e426bfcc91c --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/setup/index.d.ts @@ -0,0 +1,22 @@ +import { setupMain } from './setup'; +import * as directApi from './directApi'; +export type { Instance } from './setup'; +export declare const userEvent: { + readonly setup: typeof setupMain; + readonly clear: typeof directApi.clear; + readonly click: typeof directApi.click; + readonly copy: typeof directApi.copy; + readonly cut: typeof directApi.cut; + readonly dblClick: typeof directApi.dblClick; + readonly deselectOptions: typeof directApi.deselectOptions; + readonly hover: typeof directApi.hover; + readonly keyboard: typeof directApi.keyboard; + readonly pointer: typeof directApi.pointer; + readonly paste: typeof directApi.paste; + readonly selectOptions: typeof directApi.selectOptions; + readonly tripleClick: typeof directApi.tripleClick; + readonly type: typeof directApi.type; + readonly unhover: typeof directApi.unhover; + readonly upload: typeof directApi.upload; + readonly tab: typeof directApi.tab; +}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/setup/setup.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/setup/setup.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a27cee2d607fc1cdf091b8848543c90cff5aa30e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/setup/setup.d.ts @@ -0,0 +1,44 @@ +import { dispatchEvent, dispatchUIEvent } from '../event'; +import { Options } from '../options'; +import { System } from '../system'; +import { userEventApi } from './api'; +import { DirectOptions } from './directApi'; +export type UserEventApi = typeof userEventApi; +export type UserEvent = { + readonly setup: (...args: Parameters) => UserEvent; +} & { + readonly [k in keyof UserEventApi]: (...args: Parameters) => ReturnType; +}; +export type Instance = UserEventApi & { + config: Config; + dispatchEvent: OmitThisParameter; + dispatchUIEvent: OmitThisParameter; + system: System; + levelRefs: Record; +}; +export type Config = Required; +export declare function createConfig(options?: Options, defaults?: Required, node?: Node): Config; +/** + * Start a "session" with userEvent. + * All APIs returned by this function share an input device state and a default configuration. + */ +export declare function setupMain(options?: Options): UserEvent; +/** + * Setup in direct call per `userEvent.anyApi()` + */ +export declare function setupDirect({ keyboardState, pointerState, ...options }?: DirectOptions & { + keyboardState?: System; + pointerState?: System; +}, // backward-compatibility +node?: Node): { + api: UserEvent; + system: System; +}; +/** + * Create a set of callbacks with different default settings but the same state. + */ +export declare function setupSub(this: Instance, options: Options): UserEvent; +export declare function createInstance(config: Config, system?: System): { + instance: Instance; + api: UserEvent; +}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/setup/wrapAsync.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/setup/wrapAsync.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c37824763298e1d0bd948b87e4e3d0f8f076d2d9 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/setup/wrapAsync.d.ts @@ -0,0 +1,4 @@ +/** + * Wrap an internal Promise + */ +export declare function wrapAsync Promise) | (() => R)>(implementation: P): Promise; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/system/index.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/system/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4796dabb69ea5cf9369e3048e06d47583b52b924 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/system/index.d.ts @@ -0,0 +1,10 @@ +import { KeyboardHost } from './keyboard'; +import { PointerHost } from './pointer'; +/** + * @internal Do not create/alter this by yourself as this type might be subject to changes. + */ +export declare class System { + readonly keyboard: KeyboardHost; + readonly pointer: PointerHost; + getUIEventModifiers(): EventModifierInit; +} diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/system/keyboard.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/system/keyboard.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e9e459e1298b28235f10ab9c9acbe54afb367f6 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/system/keyboard.d.ts @@ -0,0 +1,50 @@ +import { type Instance } from '../setup'; +import { type System } from '.'; +export declare enum DOM_KEY_LOCATION { + STANDARD = 0, + LEFT = 1, + RIGHT = 2, + NUMPAD = 3 +} +export interface keyboardKey { + /** Physical location on a keyboard */ + code?: string; + /** Character or functional key descriptor */ + key?: string; + /** Location on the keyboard for keys with multiple representation */ + location?: DOM_KEY_LOCATION; + /** Does the character in `key` require/imply AltRight to be pressed? */ + altGr?: boolean; + /** Does the character in `key` require/imply a shiftKey to be pressed? */ + shift?: boolean; +} +export declare class KeyboardHost { + readonly system: System; + constructor(system: System); + readonly modifiers: { + Alt: boolean; + AltGraph: boolean; + CapsLock: boolean; + Control: boolean; + Fn: boolean; + FnLock: boolean; + Meta: boolean; + NumLock: boolean; + ScrollLock: boolean; + Shift: boolean; + Symbol: boolean; + SymbolLock: boolean; + }; + private readonly pressed; + carryChar: string; + private lastKeydownTarget; + private readonly modifierLockStart; + isKeyPressed(keyDef: keyboardKey): boolean; + getPressedKeys(): keyboardKey[]; + /** Press a key */ + keydown(instance: Instance, keyDef: keyboardKey): Promise; + /** Release a key */ + keyup(instance: Instance, keyDef: keyboardKey): Promise; + private setKeydownTarget; + private hasKeyPress; +} diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/buttons.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/buttons.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e00ae7b89a62a851d5be995b095910b77032eb55 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/buttons.d.ts @@ -0,0 +1,23 @@ +import { type pointerKey } from './shared'; +export declare class Buttons { + private readonly pressed; + getButtons(): number; + down(keyDef: pointerKey): number | undefined; + up(keyDef: pointerKey): number | undefined; +} +export declare const MouseButton: { + readonly primary: 0; + readonly secondary: 1; + readonly auxiliary: 2; + readonly back: 3; + readonly X1: 3; + readonly forward: 4; + readonly X2: 4; +}; +export type MouseButton = keyof typeof MouseButton | number; +export declare function getMouseButtonId(button?: MouseButton): number; +export declare const MouseButtonFlip: { + readonly 1: 2; + readonly 2: 1; +}; +export declare function getMouseEventButton(button?: MouseButton): number; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/device.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/device.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d8c48f475b2299bec2b50ffe15c61b491a04bde4 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/device.d.ts @@ -0,0 +1,8 @@ +import { type pointerKey } from '.'; +export declare class Device { + private pressedKeys; + get countPressed(): number; + isPressed(keyDef: pointerKey): boolean; + addPressed(keyDef: pointerKey): Set; + removePressed(keyDef: pointerKey): boolean; +} diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/index.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..85d84e0004193f85d060e6c2e7200cfa76d1ee71 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/index.d.ts @@ -0,0 +1,21 @@ +import { System } from '..'; +import { Instance } from '../../setup'; +import { pointerKey, PointerPosition } from './shared'; +export type { pointerKey, PointerPosition } from './shared'; +export declare class PointerHost { + readonly system: System; + constructor(system: System); + private readonly mouse; + private readonly buttons; + private readonly devices; + private readonly pointers; + isKeyPressed(keyDef: pointerKey): boolean; + press(instance: Instance, keyDef: pointerKey, position: PointerPosition): Promise; + move(instance: Instance, pointerName: string, position: PointerPosition): Promise; + release(instance: Instance, keyDef: pointerKey, position: PointerPosition): Promise; + getPointerName(keyDef: pointerKey): string; + getPreviousPosition(pointerName: string): PointerPosition | undefined; + resetClickCount(): void; + getMouseTarget(instance: Instance): Element; + setMousePosition(position: PointerPosition): void; +} diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/mouse.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/mouse.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0f500471beebba2a1ce61467cee2d79cd1b2b7be --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/mouse.d.ts @@ -0,0 +1,31 @@ +import { type Instance } from '../../setup'; +import { pointerKey, PointerPosition } from './shared'; +/** + * This object is the single "virtual" mouse that might be controlled by multiple different pointer devices. + */ +export declare class Mouse { + position: PointerPosition; + private readonly buttons; + private selecting?; + private buttonDownTarget; + private readonly clickCount; + move(instance: Instance, position: PointerPosition, + /** Whether `preventDefault()` has been called on the `pointerdown` event */ + isPrevented: boolean): { + leave: () => void; + enter: () => void; + move: () => void; + } | undefined; + down(instance: Instance, keyDef: pointerKey, + /** Whether `preventDefault()` has been called on the `pointerdown` event */ + isPrevented: boolean): void; + up(instance: Instance, keyDef: pointerKey, + /** Whether `preventDefault()` has been called on the `pointerdown` event */ + isPrevented: boolean): void; + resetClickCount(): void; + private getEventInit; + private getTarget; + private startSelecting; + private modifySelecting; + private endSelecting; +} diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/pointer.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/pointer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e97720938e86793336b0c23cb1a1bc73cac1a782 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/pointer.d.ts @@ -0,0 +1,32 @@ +import { type Instance } from '../../setup'; +import { PointerPosition } from './shared'; +import { Buttons, MouseButton } from './buttons'; +type PointerInit = { + pointerId: number; + pointerType: string; + isPrimary: boolean; +}; +export declare class Pointer { + constructor({ pointerId, pointerType, isPrimary }: PointerInit, buttons: Buttons); + readonly pointerId: number; + readonly pointerType: string; + readonly isPrimary: boolean; + readonly buttons: Buttons; + isMultitouch: boolean; + isCancelled: boolean; + isDown: boolean; + isPrevented: boolean; + position: PointerPosition; + init(instance: Instance): this; + move(instance: Instance, position: PointerPosition): { + leave: () => void; + enter: () => void; + move: () => void; + } | undefined; + down(instance: Instance, button?: MouseButton): void; + up(instance: Instance, button?: MouseButton): void; + release(instance: Instance): void; + private getTarget; + private getEventInit; +} +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/shared.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/shared.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a8fc4cf56a00368b1a2eacc89a57151e585158bb --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/system/pointer/shared.d.ts @@ -0,0 +1,20 @@ +import { PointerCoords } from '../../event'; +import { MouseButton } from './buttons'; +export interface pointerKey { + /** Name of the pointer key */ + name: string; + /** Type of the pointer device */ + pointerType: 'mouse' | 'pen' | 'touch'; + /** Type of button */ + button?: MouseButton; +} +export interface PointerPosition { + target?: Element; + coords?: PointerCoords; + caret?: CaretPosition; +} +export interface CaretPosition { + node?: Node; + offset?: number; +} +export declare function isDifferentPointerPosition(positionA: PointerPosition, positionB: PointerPosition): boolean; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utility/clear.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utility/clear.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f8c931ce9f9d08e603d0240d51215caa98d04f14 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utility/clear.d.ts @@ -0,0 +1,2 @@ +import { type Instance } from '../setup'; +export declare function clear(this: Instance, element: Element): Promise; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utility/index.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utility/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c28214820a9774ecc350ed2981a56593fe05ddfb --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utility/index.d.ts @@ -0,0 +1,4 @@ +export * from './clear'; +export * from './selectOptions'; +export * from './type'; +export * from './upload'; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utility/selectOptions.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utility/selectOptions.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..91733107ede4d3b0ea670b07ff37f9e2286a791f --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utility/selectOptions.d.ts @@ -0,0 +1,3 @@ +import { type Instance } from '../setup'; +export declare function selectOptions(this: Instance, select: Element, values: HTMLElement | HTMLElement[] | string[] | string): Promise; +export declare function deselectOptions(this: Instance, select: Element, values: HTMLElement | HTMLElement[] | string[] | string): Promise; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utility/type.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utility/type.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dea9b9105dd5c94cdd76c5263e8995d202f4a8d8 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utility/type.d.ts @@ -0,0 +1,9 @@ +import { type Instance } from '../setup'; +import { type Options } from '../options'; +export interface typeOptions { + skipClick?: Options['skipClick']; + skipAutoClose?: Options['skipAutoClose']; + initialSelectionStart?: number; + initialSelectionEnd?: number; +} +export declare function type(this: Instance, element: Element, text: string, { skipClick, skipAutoClose, initialSelectionStart, initialSelectionEnd, }?: typeOptions): Promise; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utility/upload.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utility/upload.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7698cb7cd7724038a5cef5d08677ac81f0ff3d39 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utility/upload.d.ts @@ -0,0 +1,5 @@ +import { type Instance } from '../setup'; +export interface uploadInit { + changeInit?: EventInit; +} +export declare function upload(this: Instance, element: HTMLElement, fileOrFiles: File | File[]): Promise; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/click/isClickableInput.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/click/isClickableInput.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..48b42fc50b19b35ca76f81edd7b77aabc05c3f9f --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/click/isClickableInput.d.ts @@ -0,0 +1,15 @@ +declare enum clickableInputTypes { + 'button' = "button", + 'color' = "color", + 'file' = "file", + 'image' = "image", + 'reset' = "reset", + 'submit' = "submit", + 'checkbox' = "checkbox", + 'radio' = "radio" +} +export type ClickableInputOrButton = HTMLButtonElement | (HTMLInputElement & { + type: clickableInputTypes; +}); +export declare function isClickableInput(element: Element): element is ClickableInputOrButton; +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/dataTransfer/Blob.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/dataTransfer/Blob.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cfc3a2a98c2892760e272ee3713740f6f38b3c3a --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/dataTransfer/Blob.d.ts @@ -0,0 +1,3 @@ +export declare function readBlobText(blob: Blob, FileReader: { + new (): FileReader; +}): Promise; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/dataTransfer/Clipboard.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/dataTransfer/Clipboard.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..112ba124653dcf732c3442b737493e012ac11f8b --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/dataTransfer/Clipboard.d.ts @@ -0,0 +1,11 @@ +export declare function createClipboardItem(window: Window & typeof globalThis, ...blobs: Array): ClipboardItem; +type ClipboardStubControlInstance = { + resetClipboardStub: () => void; + detachClipboardStub: () => void; +}; +export declare function attachClipboardStubToView(window: Window & typeof globalThis): ClipboardStubControlInstance; +export declare function resetClipboardStubOnView(window: Window & typeof globalThis): void; +export declare function detachClipboardStubFromView(window: Window & typeof globalThis): void; +export declare function readDataTransferFromClipboard(document: Document): Promise; +export declare function writeDataTransferToClipboard(document: Document, clipboardData: DataTransfer): Promise; +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/dataTransfer/DataTransfer.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/dataTransfer/DataTransfer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d1a38eff7240e0acd4697a4f40d385d750ce704 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/dataTransfer/DataTransfer.d.ts @@ -0,0 +1,2 @@ +export declare function createDataTransfer(window: Window & typeof globalThis, files?: File[]): DataTransfer; +export declare function getBlobFromDataTransferItem(window: Window & typeof globalThis, item: DataTransferItem): Promise; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/dataTransfer/FileList.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/dataTransfer/FileList.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a698ee5cbd9e21c35c84e1f424b0a72bbe660a37 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/dataTransfer/FileList.d.ts @@ -0,0 +1 @@ +export declare function createFileList(window: Window & typeof globalThis, files: File[]): FileList; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/edit/isContentEditable.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/edit/isContentEditable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d25c7df401db152f0f563e4c6a1535b1357f7ce --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/edit/isContentEditable.d.ts @@ -0,0 +1,7 @@ +export declare function isContentEditable(element: Element): element is HTMLElement & { + contenteditable: 'true'; +}; +/** + * If a node is a contenteditable or inside one, return that element. + */ +export declare function getContentEditable(node: Node): Element | null; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/edit/isEditable.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/edit/isEditable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..001f25d8185640b3b70ab3abf6aa59bd85c93d05 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/edit/isEditable.d.ts @@ -0,0 +1,24 @@ +import { isContentEditable } from './isContentEditable'; +type GuardedType = T extends (x: any) => x is infer R ? R : never; +export declare function isEditable(element: Element): element is GuardedType | (EditableInputOrTextarea & { + readOnly: false; +}); +declare enum editableInputTypes { + 'text' = "text", + 'date' = "date", + 'datetime-local' = "datetime-local", + 'email' = "email", + 'month' = "month", + 'number' = "number", + 'password' = "password", + 'search' = "search", + 'tel' = "tel", + 'time' = "time", + 'url' = "url", + 'week' = "week" +} +export type EditableInputOrTextarea = HTMLTextAreaElement | (HTMLInputElement & { + type: editableInputTypes; +}); +export declare function isEditableInputOrTextArea(element: Element): element is EditableInputOrTextarea; +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/edit/maxLength.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/edit/maxLength.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..85cfb1262a66bc8bd3443700c1dd7735d8683f6e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/edit/maxLength.d.ts @@ -0,0 +1,14 @@ +declare enum maxLengthSupportedTypes { + 'email' = "email", + 'password' = "password", + 'search' = "search", + 'telephone' = "telephone", + 'text' = "text", + 'url' = "url" +} +type ElementWithMaxLengthSupport = HTMLTextAreaElement | (HTMLInputElement & { + type: maxLengthSupportedTypes; +}); +export declare function getMaxLength(element: ElementWithMaxLengthSupport): number | undefined; +export declare function supportsMaxLength(element: Element): element is ElementWithMaxLengthSupport; +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/edit/setFiles.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/edit/setFiles.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..25bd115b0b296c44126630aa71a803021fa73bc3 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/edit/setFiles.d.ts @@ -0,0 +1,12 @@ +declare const fakeFiles: unique symbol; +declare global { + interface HTMLInputElement { + [fakeFiles]?: { + restore: () => void; + }; + } +} +export declare function setFiles(el: HTMLInputElement & { + type: 'file'; +}, files: FileList): void; +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/edit/timeValue.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/edit/timeValue.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..97e50f1a88618c08983faae2f87e7da62d68402d --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/edit/timeValue.d.ts @@ -0,0 +1,4 @@ +export declare function buildTimeValue(value: string): string; +export declare function isValidDateOrTimeValue(element: HTMLInputElement & { + type: 'date' | 'time'; +}, value: string): boolean; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/cursor.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/cursor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f3e40b12b20a9de66d110d413e173c55587dd778 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/cursor.d.ts @@ -0,0 +1,9 @@ +declare global { + interface Text { + nodeValue: string; + } +} +export declare function getNextCursorPosition(node: Node, offset: number, direction: -1 | 1, inputType?: string): { + node: Node; + offset: number; +} | undefined; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/getActiveElement.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/getActiveElement.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..53167f5fbbc0d26bda0642c31afc4e6f2427bbb1 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/getActiveElement.d.ts @@ -0,0 +1,2 @@ +export declare function getActiveElement(document: Document | ShadowRoot): Element | null; +export declare function getActiveElementOrBody(document: Document): Element; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/getTabDestination.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/getTabDestination.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6bcc8d3d815347d5356e106c18d8ee83566b379a --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/getTabDestination.d.ts @@ -0,0 +1 @@ +export declare function getTabDestination(activeElement: Element, shift: boolean): HTMLElement; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/isFocusable.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/isFocusable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..65bb3b4cb6828d5df9359af925b091eec57c2ff4 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/isFocusable.d.ts @@ -0,0 +1 @@ +export declare function isFocusable(element: Element): element is HTMLElement; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/selection.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/selection.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9e44eebd8418bdf53452d987238fbd1275c8737 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/selection.d.ts @@ -0,0 +1,8 @@ +import { ClickableInputOrButton } from '../click/isClickableInput'; +import { EditableInputOrTextarea } from '../edit/isEditable'; +/** + * Determine if the element has its own selection implementation + * and does not interact with the Document Selection API. + */ +export declare function hasOwnSelection(node: Node): node is EditableInputOrTextarea; +export declare function hasNoSelection(node: Node): node is ClickableInputOrButton; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/selector.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/selector.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dfb32b23463ef737f65a3241d521aa0c48279cb1 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/focus/selector.d.ts @@ -0,0 +1 @@ +export declare const FOCUSABLE_SELECTOR: string; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/index.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..da75d90559c0426d0774781310d904c71bd2e30e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/index.d.ts @@ -0,0 +1,29 @@ +export * from './click/isClickableInput'; +export * from './dataTransfer/Blob'; +export * from './dataTransfer/DataTransfer'; +export * from './dataTransfer/FileList'; +export * from './dataTransfer/Clipboard'; +export * from './edit/timeValue'; +export * from './edit/isContentEditable'; +export * from './edit/isEditable'; +export * from './edit/maxLength'; +export * from './edit/setFiles'; +export * from './focus/cursor'; +export * from './focus/getActiveElement'; +export * from './focus/getTabDestination'; +export * from './focus/isFocusable'; +export * from './focus/selection'; +export * from './focus/selector'; +export * from './keyDef/readNextDescriptor'; +export * from './misc/cloneEvent'; +export * from './misc/findClosest'; +export * from './misc/getDocumentFromNode'; +export * from './misc/getTreeDiff'; +export * from './misc/getWindow'; +export * from './misc/isDescendantOrSelf'; +export * from './misc/isElementType'; +export * from './misc/isVisible'; +export * from './misc/isDisabled'; +export * from './misc/level'; +export * from './misc/wait'; +export * from './pointer/cssPointerEvents'; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/keyDef/readNextDescriptor.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/keyDef/readNextDescriptor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f06df4dc2dae02d712e557aeb222309b6fbcaf73 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/keyDef/readNextDescriptor.d.ts @@ -0,0 +1,21 @@ +type Context = 'pointer' | 'keyboard'; +/** + * Read the next key definition from user input + * + * Describe key per `{descriptor}` or `[descriptor]`. + * Everything else will be interpreted as a single character as descriptor - e.g. `a`. + * Brackets `{` and `[` can be escaped by doubling - e.g. `foo[[bar` translates to `foo[bar`. + * A previously pressed key can be released per `{/descriptor}`. + * Keeping the key pressed can be written as `{descriptor>}`. + * When keeping the key pressed you can choose how long the key is pressed `{descriptor>3}`. + * You can then release the key per `{descriptor>3/}` or keep it pressed and continue with the next key. + */ +export declare function readNextDescriptor(text: string, context: Context): { + consumedLength: number; + descriptor: string; + releasePrevious: boolean; + repeat: number; + releaseSelf: boolean | undefined; + type: string; +}; +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/cloneEvent.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/cloneEvent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0135e904419955ea6974309e68ec9a0c6015a8a6 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/cloneEvent.d.ts @@ -0,0 +1 @@ +export declare function cloneEvent(event: E): E; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/findClosest.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/findClosest.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b125697709c180029a1170bbaee9d6e23bf35c0e --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/findClosest.d.ts @@ -0,0 +1 @@ +export declare function findClosest(element: Element, callback: (e: Element) => e is T): T | undefined; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/getDocumentFromNode.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/getDocumentFromNode.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..68a6b51a857d5dab53a007ec0091b6bfadad33e4 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/getDocumentFromNode.d.ts @@ -0,0 +1 @@ +export declare function getDocumentFromNode(el: Node): Document | null; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/getTreeDiff.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/getTreeDiff.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b689968e274b526684f98545cc2e07a96eb633bc --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/getTreeDiff.d.ts @@ -0,0 +1 @@ +export declare function getTreeDiff(a: Element | null, b: Element | null): readonly [Element[], Element[], Element[]]; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/getWindow.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/getWindow.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a7148d7901a7c547000f8d6364b2149b3d1dc0a --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/getWindow.d.ts @@ -0,0 +1 @@ +export declare function getWindow(node: Node): Window & typeof globalThis; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/isDescendantOrSelf.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/isDescendantOrSelf.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f4b6debe059f6c9a0d10909c137c17a1646fa28 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/isDescendantOrSelf.d.ts @@ -0,0 +1 @@ +export declare function isDescendantOrSelf(potentialDescendant: Element, potentialAncestor: Element): boolean; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/isDisabled.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/isDisabled.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6fda87763cc5a80a35614cde01bc8825af431d92 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/isDisabled.d.ts @@ -0,0 +1 @@ +export declare function isDisabled(element: Element | null): boolean; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/isElementType.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/isElementType.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..aa7a44302fed608531c1616f4ba0f4d241b25998 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/isElementType.d.ts @@ -0,0 +1,5 @@ +type tag = keyof HTMLElementTagNameMap; +export declare function isElementType(element: Element, tag: T | T[], props?: P): element is P extends undefined ? HTMLElementTagNameMap[T] : HTMLElementTagNameMap[T] & P; +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/isVisible.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/isVisible.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d79bf3359656e539cdc46b63f2523b1521e99edf --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/isVisible.d.ts @@ -0,0 +1 @@ +export declare function isVisible(element: Element): boolean; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/level.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/level.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..75890e7ae23b5869b0bfcdc6406d8e08006f300d --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/level.d.ts @@ -0,0 +1,8 @@ +import { type Instance } from '../../setup'; +export declare enum ApiLevel { + Trigger = 2, + Call = 1 +} +export type LevelRefs = Record; +export declare function setLevelRef(instance: Instance, level: ApiLevel): void; +export declare function getLevelRef(instance: Instance, level: ApiLevel): object | undefined; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/wait.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/wait.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c99929208c10e148581177ec1f10d14b53a432b4 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/misc/wait.d.ts @@ -0,0 +1,2 @@ +import { type Instance } from '../../setup'; +export declare function wait(config: Instance['config']): Promise<[void, void]> | undefined; diff --git a/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/pointer/cssPointerEvents.d.ts b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/pointer/cssPointerEvents.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eea8a8f65ad74b532beef73afc2c0023d2011592 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/dist/types/utils/pointer/cssPointerEvents.d.ts @@ -0,0 +1,19 @@ +import { type Instance } from '../../setup'; +import { ApiLevel } from '../misc/level'; +export declare function hasPointerEvents(instance: Instance, element: Element): boolean; +declare function closestPointerEventsDeclaration(element: Element): { + pointerEvents: string; + tree: Element[]; +} | undefined; +declare const PointerEventsCheck: unique symbol; +declare global { + interface Element { + [PointerEventsCheck]?: { + [k in ApiLevel]?: object; + } & { + result: ReturnType; + }; + } +} +export declare function assertPointerEvents(instance: Instance, element: Element): void; +export {}; diff --git a/tools/ui/node_modules/@testing-library/user-event/package.json b/tools/ui/node_modules/@testing-library/user-event/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7cb3d6a76fb8ab2ce70cdbc1aced19eb9efcfcb4 --- /dev/null +++ b/tools/ui/node_modules/@testing-library/user-event/package.json @@ -0,0 +1,112 @@ +{ + "name": "@testing-library/user-event", + "version": "14.6.1", + "description": "Fire events the same way the user does", + "keywords": [ + "react-testing-library", + "dom-testing-library", + "react", + "testing" + ], + "author": "Giorgio Polvara ", + "license": "MIT", + "engines": { + "node": ">=12", + "npm": ">=6" + }, + "repository": { + "type": "git", + "url": "https://github.com/testing-library/user-event" + }, + "bugs": { + "url": "https://github.com/testing-library/user-event/issues" + }, + "homepage": "https://github.com/testing-library/user-event#readme", + "files": [ + "dist" + ], + "scripts": { + "build": "scripts ts-build2 --cjs --target es2019", + "lint": "kcd-scripts lint", + "setup": "npm install && npm run validate -s", + "setup:env": "node --experimental-import-meta-resolve scripts/setup.js", + "test": "kcd-scripts test", + "test:jest": "kcd-scripts test", + "test:toolbox": "NODE_OPTIONS='--experimental-vm-modules --experimental-modules --experimental-import-meta-resolve' node scripts/test.js", + "test:debug": "kcd-scripts --inspect-brk test --runInBand", + "test:update": "npm test -- --updateSnapshot --coverage", + "validate": "kcd-scripts typecheck" + }, + "devDependencies": { + "@esbuild-plugins/node-modules-polyfill": "^0.2.2", + "@ph.fritsche/scripts-config": "^2.4.0", + "@ph.fritsche/toolbox": "^1.0.0-alpha.11", + "@testing-library/dom": "^10.4.0", + "@testing-library/jest-dom": "^5.16.3", + "@testing-library/react": "^16.1.0", + "@types/jest-in-case": "^1.0.3", + "@types/react": "^18.0.25", + "@types/sinonjs__fake-timers": "^8.1.2", + "css.escape": "^1.5.1", + "esbuild": "^0.19.10", + "esbuild-plugin-globals": "^0.2.0", + "eslint-import-resolver-typescript": "^3.5.2", + "eslint-plugin-local-rules": "^1.3.2", + "expect": "^28.1.3", + "is-ci": "^3.0.1", + "istanbul-lib-coverage": "^3.2.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.1", + "istanbul-reports": "^3.1.5", + "jest-in-case": "^1.0.2", + "jest-mock": "^28.1.3", + "jest-serializer-ansi": "^1.0.3", + "jsdom": "^20.0.3", + "kcd-scripts": "^12.1.0", + "react": "^18.0.0", + "react-dom": "^18.0.0", + "shared-scripts": "^1.5.1", + "ts-node": "^10.9.1", + "typescript": "^4.9.3" + }, + "peerDependencies": { + "@testing-library/dom": ">=7.21.4" + }, + "dependencies": {}, + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.js", + "types": "./dist/types/index.d.ts", + "exports": { + ".": { + "types": "./dist/types/index.d.ts", + "require": "./dist/cjs/index.js", + "default": "./dist/esm/index.js" + }, + "./dist/cjs/*.js": { + "types": "./dist/types/*.d.ts", + "import": "./dist/esm/*.js", + "default": "./dist/cjs/*.js" + }, + "./dist/esm/*.js": { + "types": "./dist/types/*.d.ts", + "default": "./dist/esm/*.js", + "require": "./dist/cjs/*.js" + } + }, + "typesVersions": { + "*": { + "dist/types/*": [ + "./dist/types/*" + ], + "dist/cjs/*.js": [ + "./dist/types/*.d.ts" + ], + "dist/esm/*.js": [ + "./dist/types/*.d.ts" + ], + "*": [ + "./dist/types/*.d.ts" + ] + } + } +} diff --git a/tools/ui/node_modules/@tmcp/adapter-valibot/CHANGELOG.md b/tools/ui/node_modules/@tmcp/adapter-valibot/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..13a8e81d4261b87bdcb6671b714d070adb96e54b --- /dev/null +++ b/tools/ui/node_modules/@tmcp/adapter-valibot/CHANGELOG.md @@ -0,0 +1,51 @@ +# @tmcp/adapter-valibot + +## 0.1.6 + +### Patch Changes + +- 77be8a1: chore: add license + +## 0.1.5 + +### Patch Changes + +- ccb2693: fix: add atrocious hack to satisfy enum type string required by official sdk +- Updated dependencies [61d7c9e] + - tmcp@1.17.0 + +## 0.1.4 + +### Patch Changes + +- d4dcd27: chore: update readme +- Updated dependencies [d4dcd27] +- Updated dependencies [d4dcd27] + - tmcp@1.10.2 + +## 0.1.3 + +### Patch Changes + +- feb8f62: chore: use `dts-buddy` to generate better types +- Updated dependencies [feb8f62] + - tmcp@1.8.1 + +## 0.1.2 + +### Patch Changes + +- 9e06169: fix: add tmcp as a dev dependency + +## 1.0.0 + +### Patch Changes + +- Updated dependencies [9073ae4] + - tmcp@1.1.0 + +## 0.1.1 + +### Patch Changes + +- d5fc7fb: fix: update readme diff --git a/tools/ui/node_modules/@tmcp/adapter-valibot/LICENSE b/tools/ui/node_modules/@tmcp/adapter-valibot/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1e85c344f0ce6621b49293c01b4fab313bdce1c0 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/adapter-valibot/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Paolo Ricciuti + +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. diff --git a/tools/ui/node_modules/@tmcp/adapter-valibot/README.md b/tools/ui/node_modules/@tmcp/adapter-valibot/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e4dee050e578d2ee85781515a23b5beca52116e6 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/adapter-valibot/README.md @@ -0,0 +1,158 @@ +# @tmcp/adapter-valibot + +Valibot adapter for TMCP JSON Schema conversion. + +## Installation + +```bash +pnpm add @tmcp/adapter-valibot valibot tmcp +``` + +## Usage + +```javascript +import { ValibotJsonSchemaAdapter } from '@tmcp/adapter-valibot'; +import * as v from 'valibot'; + +const adapter = new ValibotJsonSchemaAdapter(); + +// Define a Valibot schema +const userSchema = v.object({ + name: v.string(), + age: v.number(), + email: v.pipe(v.string(), v.email()), +}); + +// Convert to JSON Schema +const jsonSchema = await adapter.toJsonSchema(userSchema); +console.log(jsonSchema); +``` + +## Usage with TMCP Server + +```javascript +import { McpServer } from 'tmcp'; +import { ValibotJsonSchemaAdapter } from '@tmcp/adapter-valibot'; +import * as v from 'valibot'; + +const adapter = new ValibotJsonSchemaAdapter(); +const server = new McpServer( + { + name: 'my-server', + version: '1.0.0', + description: 'Server with Valibot schemas', + }, + { + adapter, + capabilities: { + tools: { listChanged: true }, + }, + }, +); + +// Define a tool with Valibot schema +server.tool( + { + name: 'create_user', + description: 'Create a new user', + schema: v.object({ + name: v.string(), + age: v.pipe(v.number(), v.minValue(0)), + email: v.pipe(v.string(), v.email()), + }), + }, + async ({ name, age, email }) => { + return { + content: [ + { + type: 'text', + text: `Created user: ${name}, age ${age}, email ${email}`, + }, + ], + }; + }, +); +``` + +## Advanced Usage + +### Custom Validation and Metadata + +```javascript +import { ValibotJsonSchemaAdapter } from '@tmcp/adapter-valibot'; +import * as v from 'valibot'; + +const adapter = new ValibotJsonSchemaAdapter(); + +// Schema with custom descriptions and metadata +const userSchema = v.object({ + name: v.pipe(v.string(), v.minLength(1), v.maxLength(100)), + age: v.pipe(v.number(), v.minValue(0), v.maxValue(150)), + email: v.pipe(v.string(), v.email()), + preferences: v.optional( + v.object({ + theme: v.picklist(['light', 'dark']), + notifications: v.boolean(), + }), + ), +}); + +const jsonSchema = await adapter.toJsonSchema(userSchema); +``` + +### Complex Schemas + +```javascript +import * as v from 'valibot'; + +// Union types +const contactSchema = v.union([ + v.object({ + type: v.literal('email'), + value: v.pipe(v.string(), v.email()), + }), + v.object({ + type: v.literal('phone'), + value: v.pipe(v.string(), v.regex(/^\+?\d+$/)), + }), +]); + +// Arrays and nested objects +const companySchema = v.object({ + name: v.string(), + employees: v.array(userSchema), + contacts: v.array(contactSchema), + founded: v.pipe( + v.date(), + v.transform((date) => date.toISOString()), + ), +}); +``` + +## API + +### `ValibotJsonSchemaAdapter` + +A class that extends the base `JsonSchemaAdapter` from TMCP and provides Valibot-specific schema conversion. + +#### Methods + +- `toJsonSchema(schema)` - Converts a Valibot schema to JSON Schema format + +## Dependencies + +- `valibot` - Peer dependency for schema validation (^1.1.0) +- `tmcp` - Peer dependency for the base adapter +- `@valibot/to-json-schema` - For schema conversion + +## Features + +- **Full Valibot support** - Supports all Valibot schema types and validations +- **Type safety** - Full TypeScript support with proper type inference +- **Rich validation** - Preserves validation rules and transformations +- **Easy integration** - Drop-in replacement for other TMCP adapters +- **Performance** - Efficient schema conversion using Valibot's built-in utilities + +## Acknowledgments + +Huge thanks to Sean O'Bannon that provided us with the `@tmcp` scope on npm. diff --git a/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/LICENSE.md b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..3a695a6a34eb5ad09a784ee966bc276ef19fbdcd --- /dev/null +++ b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/LICENSE.md @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Fabian Hiller + +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. diff --git a/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/README.md b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/README.md new file mode 100644 index 0000000000000000000000000000000000000000..be51115ae2c6ca0d8dae800ea6332650b46913fa --- /dev/null +++ b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/README.md @@ -0,0 +1,470 @@ +# Valibot to JSON Schema + +Utility to convert [Valibot](https://valibot.dev) schemas to JSON Schema. Supports JSON Schema draft-07, draft-2020-12, and OpenAPI 3.0 Schema Object formats. + +```js +import { toJsonSchema } from '@valibot/to-json-schema'; +import * as v from 'valibot'; + +toJsonSchema(v.string()); // { $schema: "http://json-schema.org/draft-07/schema#", type: "string" } +``` + +This package is particularly popular for: + +- **API Documentation**: Generate OpenAPI specifications from your Valibot schemas +- **Code Generation**: Create client SDKs and types from your validation schemas +- **LLM Integration**: Generate structured outputs for Large Language Models +- **Schema Sharing**: Share validation logic between different programming languages + +> Some Valibot features can't be mapped to JSON schema. For example, transformation actions have no equivalent in JSON schema. Also, some Valibot schemas or validations are too JS-specific and do not have an equivalent JSON schema attribute. + +## Supported features + +**Note**: Converted schemas may behave slightly differently in JSON schema validators (especially for string format) because their implementation is different from Valibot's. + +| Schema | Status | Note | +| ---------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------- | +| `any` | ✅ | | +| `array` | ✅ | | +| `boolean` | ✅ | | +| `enum` | ✅ | | +| `exactOptional` | ✅ | | +| `intersect` | ✅ | | +| `lazy` | ⚠️ | The `.getter` function is always executed with `undefined` as input | +| `literal` | ⚠️ | Only JSON compatible values are supported | +| `looseObject` | ✅ | | +| `looseTuple` | ✅ | | +| `never` | ✅ | | +| `null` | ✅ | | +| `nullable` | ✅ | | +| `nullish` | ✅ | | +| `number` | ✅ | | +| `objectWithRest` | ✅ | | +| `object` | ✅ | | +| `optional` | ✅ | | +| `picklist` | ⚠️ | Only JSON compatible values are supported | +| `record` | ⚠️ | Only `string` schemas for the key of the record are supported. Adds `propertyNames` for key validation (not available in OpenAPI 3.0) | +| `strictObject` | ✅ | | +| `strictTuple` | ✅ | | +| `string` | ✅ | | +| `tupleWithRest` | ✅ | | +| `tuple` | ✅ | | +| `union` | ✅ | | +| `undefinedable` | ✅ | | +| `unknown` | ✅ | | +| `variant` | ⚠️ | The discriminator key will be ignored | + +| Actions | Status | Note | +| --------------- | ------ | ----------------------------------------------------------- | +| `base64` | ✅ | | +| `bic` | ✅ | | +| `cuid2` | ✅ | | +| `decimal` | ✅ | | +| `description` | ✅ | | +| `digits` | ✅ | | +| `domain` | ✅ | | +| `email` | ✅ | | +| `emoji` | ✅ | | +| `empty` | ✅ | | +| `endsWith` | ✅ | | +| `entries` | ✅ | | +| `examples` | ✅ | | +| `gtValue` | ⚠️ | Only in combination with `number` and `integer` schema | +| `hash` | ✅ | | +| `hexadecimal` | ✅ | | +| `hexColor` | ✅ | | +| `includes` | ✅ | | +| `integer` | ✅ | | +| `ipv4` | ✅ | | +| `ipv6` | ✅ | | +| `isoDate` | ✅ | | +| `isoDateTime` | ✅ | | +| `isoTime` | ✅ | | +| `isoTimeSecond` | ✅ | | +| `isoTimestamp` | ✅ | | +| `isoWeek` | ✅ | | +| `isrc` | ✅ | | +| `jwsCompact` | ✅ | | +| `length` | ⚠️ | Only in combination with `string` and `array` schema | +| `ltValue` | ⚠️ | Only in combination with `number` and `integer` schema | +| `mac` | ✅ | | +| `mac48` | ✅ | | +| `mac64` | ✅ | | +| `maxEntries` | ✅ | | +| `maxLength` | ⚠️ | Only in combination with `string` and `array` schema | +| `maxValue` | ⚠️ | Only in combination with `number` schema | +| `metadata` | ⚠️ | Only for valid `title`, `description` and `examples` values | +| `minEntries` | ✅ | | +| `minLength` | ⚠️ | Only in combination with `string` and `array` schema | +| `minValue` | ⚠️ | Only in combination with `number` schema | +| `multipleOf` | ✅ | | +| `nanoid` | ✅ | | +| `nonEmpty` | ✅ | | +| `notValue` | ⚠️ | Only JSON compatible values are supported | +| `notValues` | ⚠️ | Only JSON compatible values are supported | +| `octal` | ✅ | | +| `regex` | ⚠️ | RegExp flags are not supported in JSON Schema | +| `rfcEmail` | ✅ | | +| `safeInteger` | ✅ | | +| `slug` | ✅ | | +| `startsWith` | ✅ | | +| `title` | ✅ | | +| `ulid` | ✅ | | +| `url` | ✅ | | +| `uuid` | ✅ | | +| `value` | ⚠️ | Only JSON compatible values are supported | +| `values` | ⚠️ | Only JSON compatible values are supported | + +## Configurations + +| Option | Type | Note | +| -------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| target | `'draft-07' \| 'draft-2020-12' \| 'openapi-3.0'` | The target JSON Schema format. Defaults to `'draft-07'`. | +| typeMode | `'ignore' \| 'input' \| 'output'` | Whether to convert the input or output type of the Valibot schema to JSON Schema. | +| errorMode | `'throw' \| 'warn' \| 'ignore'` | The policy for handling incompatible schemas and actions. | +| definitions | `Record` | The schema definitions for constructing recursive schemas. If not specified, the definitions are generated automatically. | +| overrideSchema | `(context: OverrideSchemaContext) => JsonSchema \| null \| undefined` | Overrides the JSON Schema conversion for a specific Valibot schema. | +| ignoreActions | `string[]` | The actions that should be ignored during the conversion. | +| overrideAction | `(context: OverrideActionContext) => JsonSchema \| null \| undefined` | Overrides the JSON Schema reference for a specific Valibot action. | +| overrideRef | `(context: OverrideRefContext) => string \| null \| undefined` | Overrides the JSON Schema reference for a specific reference ID. | + +### Target format + +The `target` configuration allows you to specify which JSON Schema format to generate. Different targets have different capabilities and syntax: + +```js +import { toJsonSchema } from '@valibot/to-json-schema'; +import * as v from 'valibot'; + +const schema = v.nullable(v.string()); + +// JSON Schema draft-07 (default) +toJsonSchema(schema); +// { $schema: "http://json-schema.org/draft-07/schema#", anyOf: [{ type: "string" }, { type: "null" }] } + +// JSON Schema draft-2020-12 +toJsonSchema(schema, { target: 'draft-2020-12' }); +// { $schema: "https://json-schema.org/draft/2020-12/schema", anyOf: [{ type: "string" }, { type: "null" }] } + +// OpenAPI 3.0 Schema Object +toJsonSchema(schema, { target: 'openapi-3.0' }); +// { type: "string", nullable: true } +``` + +**Note**: Some features like `propertyNames` for record schemas are not available in OpenAPI 3.0. + +### Type mode + +The `typeMode` configuration controls whether to convert the input or output type of the Valibot schema to JSON Schema. + +- When set to `'input'`, conversion stops before the first potential type transformation action or second schema in any pipeline. +- When set to `'output'`, conversion of any pipelines starts from the last schema in the pipeline. Therefore, the output type must be specified explicitly with a schema after the last type transformation action. +- When set to `'ignore'` (default), the entire pipeline is converted. + +This is particularly useful when defining API endpoints where external developers need different schema information for requests vs responses: + +```js +import { toJsonSchema } from '@valibot/to-json-schema'; +import * as v from 'valibot'; + +const ValibotSchema = v.pipe( + v.string(), + v.decimal(), + v.transform(Number), + v.number(), + v.maxValue(100) +); + +toJsonSchema(ValibotSchema, { typeMode: 'input' }); + +// { +// $schema: "http://json-schema.org/draft-07/schema#", +// type: "string", +// pattern: "^[+-]?(?:\\d*\\.)?\\d+$" +// } + +toJsonSchema(ValibotSchema, { typeMode: 'output' }); + +// { +// $schema: "http://json-schema.org/draft-07/schema#", +// type: "number", +// maximum: 100 +// } +``` + +### Error mode + +The `errorMode` configuration controls how the converter handles unsupported schemas and actions. By default, the error mode is set to `'throw'`. To force the conversion of unsupported Valibot features, you can set it to `'ignore'`. + +> Unsupported schemas usually return an empty JSON schema (`{}`) and unsupported actions are usually ignored. + +```js +import { toJsonSchema } from '@valibot/to-json-schema'; +import * as v from 'valibot'; + +toJsonSchema(v.file(), { errorMode: 'ignore' }); // {} + +toJsonSchema(v.pipe(v.string(), v.creditCard()), { errorMode: 'ignore' }); // { type: "string" } +``` + +### Override functions + +The package provides powerful override capabilities to customize the JSON Schema conversion process. You can override the conversion of specific schemas, actions, or references. + +#### Override schema conversion + +Handle unsupported schemas or customize conversion behavior: + +```js +import { toJsonSchema } from '@valibot/to-json-schema'; +import * as v from 'valibot'; + +const ValibotSchema = v.object({ createdAt: v.date() }); + +toJsonSchema(ValibotSchema, { + overrideSchema(context) { + if (context.valibotSchema.type === 'date') { + return { type: 'string', format: 'date-time' }; + } + }, +}); + +// { +// $schema: "http://json-schema.org/draft-07/schema#", +// type: "object", +// properties: { +// createdAt: { type: "string" format: "date-time" } +// }, +// required: ["createdAt"] +// } +``` + +#### Override reference IDs + +Customize reference IDs for OpenAPI or other specifications: + +```js +import { toJsonSchemaDefs } from '@valibot/to-json-schema'; +import * as v from 'valibot'; + +const UserSchema = v.object({ name: v.string() }); + +toJsonSchemaDefs( + { UserSchema }, + { overrideRef: (context) => `#/schemas/${context.referenceId}` } +); +``` + +### Enhanced metadata support + +Use the generic `metadata` action to add title, description, and examples to your schemas or the individual `title`and `description` actions: + +```js +import { toJsonSchema } from '@valibot/to-json-schema'; +import * as v from 'valibot'; + +const ValibotSchema = v.pipe( + v.string(), + v.email(), + v.metadata({ + title: 'Email Schema', + description: 'A schema that validates email addresses.', + examples: ['jane@example.com'], + }) +); + +toJsonSchema(ValibotSchema); + +// { +// $schema: "http://json-schema.org/draft-07/schema#", +// type: "string", +// format: "email", +// title: "Email Schema", +// description: "A schema that validates email addresses.", +// examples: ["jane@example.com"] +// } +``` + +### Definitions + +Nested and recursive schemas can be broken in multiple reusable definitions. + +```js +import { toJsonSchema } from '@valibot/to-json-schema'; +import * as v from 'valibot'; + +const EmailSchema = v.pipe(v.string(), v.email()); +toJsonSchema(v.object({ email: EmailSchema }), { + definitions: { EmailSchema }, +}); + +// { +// $schema: "http://json-schema.org/draft-07/schema#", +// type: "object", +// properties: { +// email: { +// $ref: "#/$defs/EmailSchema" +// } +// }, +// required: ["email"], +// $defs: { +// EmailSchema: { +// type: "string", +// format: "email" +// } +// } +// } +``` + +Definitions are not required for converting `lazy` schemas. Missing definitions will be generated automatically. + +```js +import { toJsonSchema } from '@valibot/to-json-schema'; +import * as v from 'valibot'; + +const StringSchema = v.string(); +toJsonSchema(v.object({ key: v.lazy(() => StringSchema) })); + +// { +// $schema: "http://json-schema.org/draft-07/schema#", +// type: "object", +// properties: { +// key: { +// $ref: "#/$defs/0" +// } +// }, +// required: ["key"], +// $defs: { +// 0: { +// type: "string" +// } +// } +// } +``` + +## Additional functions + +### `toStandardJsonSchema` + +Converts a Valibot schema to the [Standard JSON Schema](https://standardschema.dev/) format. This format is useful when working with tools and libraries that support the Standard JSON Schema specification. + +```js +import { toStandardJsonSchema } from '@valibot/to-json-schema'; +import * as v from 'valibot'; + +const schema = toStandardJsonSchema( + v.object({ + id: v.pipe(v.string(), v.uuid()), + name: v.pipe(v.string(), v.nonEmpty()), + age: v.optional(v.number()), + }) +); +``` + +### `toJsonSchemaDefs` + +Converts only the provided Valibot schema definitions to JSON Schema definitions, without wrapping them in a root schema. This is particularly useful for OpenAPI specifications where you need only the schema definitions. + +```js +import { toJsonSchemaDefs } from '@valibot/to-json-schema'; +import * as v from 'valibot'; + +const EmailSchema = v.pipe(v.string(), v.email()); +const UserSchema = v.object({ + name: v.string(), + email: EmailSchema, +}); + +toJsonSchemaDefs({ EmailSchema, UserSchema }); + +// { +// EmailSchema: { +// type: "string", +// format: "email" +// }, +// UserSchema: { +// type: "object", +// properties: { +// name: { +// type: "string" +// }, +// email: { +// $ref: "#/$defs/EmailSchema" +// } +// }, +// required: ["name", "email"] +// } +// } +``` + +#### OpenAPI integration + +For OpenAPI specifications, you can customize reference IDs: + +```js +import { toJsonSchemaDefs } from '@valibot/to-json-schema'; +import * as v from 'valibot'; + +const ValibotSchema1 = v.string(); +const ValibotSchema2 = v.number(); +const ValibotSchema3 = v.tuple([ValibotSchema1, ValibotSchema2]); + +toJsonSchemaDefs( + { ValibotSchema1, ValibotSchema2, ValibotSchema3 }, + { overrideRef: (context) => `#/schemas/${context.referenceId}` } +); + +// { +// ValibotSchema1: { type: "string" }, +// ValibotSchema2: { type: "number" }, +// ValibotSchema3: { +// type: "array", +// items: [ +// { $ref: "#/schemas/ValibotSchema1" }, +// { $ref: "#/schemas/ValibotSchema2" } +// ], +// minItems: 2 +// } +// } +``` + +### Global definitions + +For advanced use cases, you can manage global schema definitions that will be automatically used when converting schemas. This is particularly useful for larger projects with many reusable schemas. + +```js +import { addGlobalDefs, toJsonSchema } from '@valibot/to-json-schema'; +import * as v from 'valibot'; + +const ValibotSchema1 = v.string(); +const ValibotSchema2 = v.number(); + +addGlobalDefs({ ValibotSchema1, ValibotSchema2 }); + +const ValibotSchema3 = v.tuple([ValibotSchema1, ValibotSchema2]); + +toJsonSchema(ValibotSchema3); + +// { +// $schema: "http://json-schema.org/draft-07/schema#", +// type: "array", +// items: [ +// { $ref: "#/$defs/ValibotSchema1" }, +// { $ref: "#/$defs/ValibotSchema2" } +// ], +// minItems: 2, +// $defs: { +// ValibotSchema1: { type: "string" }, +// ValibotSchema2: { type: "number" } +// } +// } +``` + +You can also convert global definitions directly using `toJsonSchemaDefs`: + +```js +const globalDefs = getGlobalDefs(); +if (globalDefs) { + const schemaDefs = toJsonSchemaDefs(globalDefs); +} +``` diff --git a/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.cjs b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..df334e0c983cc14852970a85f91554ee50a2218b --- /dev/null +++ b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.cjs @@ -0,0 +1,653 @@ + +//#region src/utils/addError.ts +/** +* Adds an error message to the errors array. +* +* @param errors The array of error messages. +* @param message The error message to add. +* +* @returns The new errors. +*/ +function addError(errors, message) { + if (errors) { + errors.push(message); + return errors; + } + return [message]; +} + +//#endregion +//#region src/utils/escapeRegExp.ts +const ESCAPE_REGEX = /[.*+?^${}()|[\]\\]/g; +/** +* Escapes special regex characters in a string. +* +* @param string The string to escape. +* +* @returns The escaped string. +*/ +function escapeRegExp(string) { + return string.replace(ESCAPE_REGEX, "\\$&"); +} + +//#endregion +//#region src/utils/handleError.ts +/** +* Throws an error or logs a warning based on the configuration. +* +* @param message The message to throw or log. +* @param config The conversion configuration. +*/ +function handleError(message, config) { + switch (config?.errorMode) { + case "ignore": break; + case "warn": + console.warn(message); + break; + default: throw new Error(message); + } +} + +//#endregion +//#region src/utils/isJsonConstValue.ts +/** +* Whether a value is JSON compatible for a const keyword. +* +* @param value The value to check. +* +* @returns Whether the value is JSON compatible. +*/ +function isJsonConstValue(value) { + return typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) || typeof value === "string"; +} + +//#endregion +//#region src/utils/isJsonEnumValues.ts +/** +* Whether values are JSON compatible for an enum keyword. +* +* @param values The values to check. +* +* @returns Whether the values are JSON compatible. +*/ +function isJsonEnumValues(values) { + return values.every(isJsonConstValue); +} + +//#endregion +//#region src/converters/convertAction/convertAction.ts +/** +* Converts any supported Valibot action to the JSON Schema format. +* +* @param jsonSchema The JSON Schema object. +* @param valibotAction The Valibot action object. +* @param config The conversion configuration. +* +* @returns The converted JSON Schema. +*/ +function convertAction(jsonSchema, valibotAction, config) { + if (config?.ignoreActions?.includes(valibotAction.type)) return jsonSchema; + let errors; + switch (valibotAction.type) { + case "base64": + jsonSchema.contentEncoding = "base64"; + break; + case "bic": + case "cuid2": + case "decimal": + case "digits": + case "domain": + case "emoji": + case "hash": + case "hexadecimal": + case "hex_color": + case "isrc": + case "iso_time_second": + case "iso_week": + case "mac": + case "mac48": + case "mac64": + case "nanoid": + case "octal": + case "slug": + case "ulid": + if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`); + else jsonSchema.pattern = valibotAction.requirement.source; + break; + case "description": + jsonSchema.description = valibotAction.description; + break; + case "email": + case "rfc_email": + jsonSchema.format = "email"; + break; + case "ends_with": + if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`); + else jsonSchema.pattern = `${escapeRegExp(valibotAction.requirement)}$`; + break; + case "empty": + if (jsonSchema.type === "array") jsonSchema.maxItems = 0; + else { + if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`); + jsonSchema.maxLength = 0; + } + break; + case "entries": + jsonSchema.minProperties = valibotAction.requirement; + jsonSchema.maxProperties = valibotAction.requirement; + break; + case "examples": + if (Array.isArray(jsonSchema.examples)) jsonSchema.examples = [...jsonSchema.examples, ...valibotAction.examples]; + else jsonSchema.examples = valibotAction.examples; + break; + case "gt_value": + if (jsonSchema.type !== "number" && jsonSchema.type !== "integer") errors = addError(errors, `The "gt_value" action is not supported on type "${jsonSchema.type}".`); + if (config?.target === "openapi-3.0") { + errors = addError(errors, "The \"gt_value\" action is not supported for OpenAPI 3.0."); + break; + } + jsonSchema.exclusiveMinimum = valibotAction.requirement; + break; + case "includes": + if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`); + else jsonSchema.pattern = escapeRegExp(valibotAction.requirement); + break; + case "integer": + jsonSchema.type = "integer"; + break; + case "ipv4": + jsonSchema.format = "ipv4"; + break; + case "ipv6": + jsonSchema.format = "ipv6"; + break; + case "iso_date": + jsonSchema.format = "date"; + break; + case "iso_date_time": + case "iso_timestamp": + jsonSchema.format = "date-time"; + break; + case "iso_time": + jsonSchema.format = "time"; + break; + case "jws_compact": + if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`); + else jsonSchema.pattern = valibotAction.requirement.source; + break; + case "length": + if (jsonSchema.type === "array") { + jsonSchema.minItems = valibotAction.requirement; + jsonSchema.maxItems = valibotAction.requirement; + } else { + if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`); + jsonSchema.minLength = valibotAction.requirement; + jsonSchema.maxLength = valibotAction.requirement; + } + break; + case "lt_value": + if (jsonSchema.type !== "number" && jsonSchema.type !== "integer") errors = addError(errors, `The "lt_value" action is not supported on type "${jsonSchema.type}".`); + if (config?.target === "openapi-3.0") { + errors = addError(errors, "The \"lt_value\" action is not supported for OpenAPI 3.0."); + break; + } + jsonSchema.exclusiveMaximum = valibotAction.requirement; + break; + case "max_entries": + jsonSchema.maxProperties = valibotAction.requirement; + break; + case "max_length": + if (jsonSchema.type === "array") jsonSchema.maxItems = valibotAction.requirement; + else { + if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`); + jsonSchema.maxLength = valibotAction.requirement; + } + break; + case "max_value": + if (jsonSchema.type !== "number" && jsonSchema.type !== "integer") errors = addError(errors, `The "max_value" action is not supported on type "${jsonSchema.type}".`); + jsonSchema.maximum = valibotAction.requirement; + break; + case "metadata": + if (typeof valibotAction.metadata.title === "string") jsonSchema.title = valibotAction.metadata.title; + if (typeof valibotAction.metadata.description === "string") jsonSchema.description = valibotAction.metadata.description; + if (Array.isArray(valibotAction.metadata.examples)) if (Array.isArray(jsonSchema.examples)) jsonSchema.examples = [...jsonSchema.examples, ...valibotAction.metadata.examples]; + else jsonSchema.examples = valibotAction.metadata.examples; + break; + case "min_entries": + jsonSchema.minProperties = valibotAction.requirement; + break; + case "min_length": + if (jsonSchema.type === "array") jsonSchema.minItems = valibotAction.requirement; + else { + if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`); + jsonSchema.minLength = valibotAction.requirement; + } + break; + case "min_value": + if (jsonSchema.type !== "number" && jsonSchema.type !== "integer") errors = addError(errors, `The "min_value" action is not supported on type "${jsonSchema.type}".`); + jsonSchema.minimum = valibotAction.requirement; + break; + case "multiple_of": + jsonSchema.multipleOf = valibotAction.requirement; + break; + case "non_empty": + if (jsonSchema.type === "array") jsonSchema.minItems = 1; + else { + if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`); + jsonSchema.minLength = 1; + } + break; + case "not_value": + if (!isJsonConstValue(valibotAction.requirement)) { + errors = addError(errors, "The requirement of the \"not_value\" action is not JSON compatible."); + break; + } + if (config?.target === "openapi-3.0") jsonSchema.not = { enum: [valibotAction.requirement] }; + else jsonSchema.not = { const: valibotAction.requirement }; + break; + case "not_values": + if (!isJsonEnumValues(valibotAction.requirement)) { + errors = addError(errors, "A requirement of the \"not_values\" action is not JSON compatible."); + break; + } + jsonSchema.not = { enum: valibotAction.requirement }; + break; + case "regex": + if (valibotAction.requirement.flags) errors = addError(errors, "RegExp flags are not supported by JSON Schema."); + if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`); + else jsonSchema.pattern = valibotAction.requirement.source; + break; + case "safe_integer": + jsonSchema.type = "integer"; + if (typeof jsonSchema.minimum !== "number" || jsonSchema.minimum < Number.MIN_SAFE_INTEGER) jsonSchema.minimum = Number.MIN_SAFE_INTEGER; + if (typeof jsonSchema.maximum !== "number" || jsonSchema.maximum > Number.MAX_SAFE_INTEGER) jsonSchema.maximum = Number.MAX_SAFE_INTEGER; + break; + case "starts_with": + if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`); + else jsonSchema.pattern = `^${escapeRegExp(valibotAction.requirement)}`; + break; + case "title": + jsonSchema.title = valibotAction.title; + break; + case "url": + jsonSchema.format = "uri"; + break; + case "uuid": + jsonSchema.format = "uuid"; + break; + case "value": + if (!isJsonConstValue(valibotAction.requirement)) { + errors = addError(errors, "The requirement of the \"value\" action is not JSON compatible."); + break; + } + if (config?.target === "openapi-3.0") jsonSchema.enum = [valibotAction.requirement]; + else jsonSchema.const = valibotAction.requirement; + break; + case "values": + if (!isJsonEnumValues(valibotAction.requirement)) { + errors = addError(errors, "A requirement of the \"values\" action is not JSON compatible."); + break; + } + jsonSchema.enum = valibotAction.requirement; + break; + default: errors = addError(errors, `The "${valibotAction.type}" action cannot be converted to JSON Schema.`); + } + if (config?.overrideAction) { + const actionOverride = config.overrideAction({ + valibotAction, + jsonSchema, + errors + }); + if (actionOverride) return { ...actionOverride }; + } + if (errors) for (const message of errors) handleError(message, config); + return jsonSchema; +} + +//#endregion +//#region src/converters/convertSchema/convertSchema.ts +/** +* Flattens a Valibot pipe by recursively expanding nested pipes. +* +* @param pipe The pipeline to flatten. +* +* @returns A flat pipeline. +*/ +function flattenPipe(pipe) { + return pipe.flatMap((item) => "pipe" in item ? flattenPipe(item.pipe) : item); +} +/** +* Returns the JSON Pointer reference for a definition key. +* +* @param referenceId The unescaped definition key. +* +* @returns The encoded JSON Pointer fragment. +*/ +function getDefinitionRef(referenceId) { + return `#/$defs/${referenceId.replaceAll("~", "~0").replaceAll("/", "~1")}`; +} +let refCount = 0; +/** +* Converts any supported Valibot schema to the JSON Schema format. +* +* @param jsonSchema The JSON Schema object. +* @param valibotSchema The Valibot schema object. +* @param config The conversion configuration. +* @param context The conversion context. +* @param skipRef Whether to skip using a reference. +* +* @returns The converted JSON Schema. +*/ +function convertSchema(jsonSchema, valibotSchema, config, context, skipRef = false) { + if (!skipRef) { + const referenceId = context.referenceMap.get(valibotSchema); + if (referenceId) { + jsonSchema.$ref = getDefinitionRef(referenceId); + if (config?.overrideRef) { + const refOverride = config.overrideRef({ + ...context, + referenceId, + valibotSchema, + jsonSchema + }); + if (refOverride) jsonSchema.$ref = refOverride; + } + return jsonSchema; + } + } + if ("pipe" in valibotSchema) { + const flatPipe = flattenPipe(valibotSchema.pipe); + let startIndex = 0; + let stopIndex = flatPipe.length - 1; + if (config?.typeMode === "input") { + const inputStopIndex = flatPipe.slice(1).findIndex((item) => item.kind === "schema" || item.kind === "transformation" && (item.type === "find_item" || item.type === "parse_json" || item.type === "raw_transform" || item.type === "reduce_items" || item.type === "stringify_json" || item.type === "to_bigint" || item.type === "to_boolean" || item.type === "to_date" || item.type === "to_number" || item.type === "to_string" || item.type === "transform")); + if (inputStopIndex !== -1) stopIndex = inputStopIndex; + } else if (config?.typeMode === "output") { + const outputStartIndex = flatPipe.findLastIndex((item) => item.kind === "schema"); + if (outputStartIndex !== -1) startIndex = outputStartIndex; + } + for (let index = startIndex; index <= stopIndex; index++) { + const valibotPipeItem = flatPipe[index]; + if (valibotPipeItem.kind === "schema") { + if (index > startIndex) handleError("Set the \"typeMode\" config to \"input\" or \"output\" to convert pipelines with multiple schemas.", config); + jsonSchema = convertSchema(jsonSchema, valibotPipeItem, config, context, true); + } else jsonSchema = convertAction(jsonSchema, valibotPipeItem, config); + } + return jsonSchema; + } + let errors; + switch (valibotSchema.type) { + case "boolean": + jsonSchema.type = "boolean"; + break; + case "null": + if (config?.target === "openapi-3.0") jsonSchema.enum = [null]; + else jsonSchema.type = "null"; + break; + case "number": + jsonSchema.type = "number"; + break; + case "string": + jsonSchema.type = "string"; + break; + case "array": + jsonSchema.type = "array"; + jsonSchema.items = convertSchema({}, valibotSchema.item, config, context); + break; + case "tuple": + case "tuple_with_rest": + case "loose_tuple": + case "strict_tuple": + jsonSchema.type = "array"; + if (config?.target === "openapi-3.0") { + jsonSchema.items = { anyOf: [] }; + jsonSchema.minItems = valibotSchema.items.length; + for (const item of valibotSchema.items) jsonSchema.items.anyOf.push(convertSchema({}, item, config, context)); + if (valibotSchema.type === "tuple_with_rest") jsonSchema.items.anyOf.push(convertSchema({}, valibotSchema.rest, config, context)); + else if (valibotSchema.type === "strict_tuple" || valibotSchema.type === "tuple") jsonSchema.maxItems = valibotSchema.items.length; + } else if (config?.target === "draft-2020-12") { + jsonSchema.prefixItems = []; + jsonSchema.minItems = valibotSchema.items.length; + for (const item of valibotSchema.items) jsonSchema.prefixItems.push(convertSchema({}, item, config, context)); + if (valibotSchema.type === "tuple_with_rest") jsonSchema.items = convertSchema({}, valibotSchema.rest, config, context); + else if (valibotSchema.type === "strict_tuple") jsonSchema.items = false; + } else { + jsonSchema.items = []; + jsonSchema.minItems = valibotSchema.items.length; + for (const item of valibotSchema.items) jsonSchema.items.push(convertSchema({}, item, config, context)); + if (valibotSchema.type === "tuple_with_rest") jsonSchema.additionalItems = convertSchema({}, valibotSchema.rest, config, context); + else if (valibotSchema.type === "strict_tuple") jsonSchema.additionalItems = false; + } + break; + case "object": + case "object_with_rest": + case "loose_object": + case "strict_object": + jsonSchema.type = "object"; + jsonSchema.properties = {}; + jsonSchema.required = []; + for (const key in valibotSchema.entries) { + const entry = valibotSchema.entries[key]; + jsonSchema.properties[key] = convertSchema({}, entry, config, context); + if (entry.type !== "exact_optional" && entry.type !== "nullish" && entry.type !== "optional") jsonSchema.required.push(key); + } + if (valibotSchema.type === "object_with_rest") jsonSchema.additionalProperties = convertSchema({}, valibotSchema.rest, config, context); + else if (valibotSchema.type === "strict_object") jsonSchema.additionalProperties = false; + break; + case "record": + if (config?.target === "openapi-3.0" && "pipe" in valibotSchema.key) errors = addError(errors, "The \"record\" schema with a schema for the key that contains a \"pipe\" cannot be converted to JSON Schema."); + if (valibotSchema.key.type !== "string") errors = addError(errors, `The "record" schema with the "${valibotSchema.key.type}" schema for the key cannot be converted to JSON Schema.`); + jsonSchema.type = "object"; + if (config?.target !== "openapi-3.0") jsonSchema.propertyNames = convertSchema({}, valibotSchema.key, config, context); + jsonSchema.additionalProperties = convertSchema({}, valibotSchema.value, config, context); + break; + case "any": + case "unknown": break; + case "never": + jsonSchema.not = {}; + break; + case "nullable": + case "nullish": + if (config?.target === "openapi-3.0") { + const innerSchema = convertSchema({}, valibotSchema.wrapped, config, context); + Object.assign(jsonSchema, innerSchema); + jsonSchema.nullable = true; + } else jsonSchema.anyOf = [convertSchema({}, valibotSchema.wrapped, config, context), { type: "null" }]; + if (valibotSchema.default !== void 0) jsonSchema.default = typeof valibotSchema.default === "function" ? valibotSchema.default() : valibotSchema.default; + break; + case "exact_optional": + case "optional": + case "undefinedable": + jsonSchema = convertSchema(jsonSchema, valibotSchema.wrapped, config, context); + if (valibotSchema.default !== void 0) jsonSchema.default = typeof valibotSchema.default === "function" ? valibotSchema.default() : valibotSchema.default; + break; + case "literal": + if (typeof valibotSchema.literal !== "boolean" && typeof valibotSchema.literal !== "number" && typeof valibotSchema.literal !== "string") errors = addError(errors, "The value of the \"literal\" schema is not JSON compatible."); + if (config?.target === "openapi-3.0") jsonSchema.enum = [valibotSchema.literal]; + else jsonSchema.const = valibotSchema.literal; + break; + case "enum": + jsonSchema.enum = valibotSchema.options; + if (valibotSchema.options.every((option) => typeof option === "string")) jsonSchema.type = "string"; + else if (valibotSchema.options.every((option) => typeof option === "number")) jsonSchema.type = "number"; + else if (config?.target !== "openapi-3.0") jsonSchema.type = ["string", "number"]; + break; + case "picklist": { + const hasInvalidOption = valibotSchema.options.some((option) => typeof option !== "number" && typeof option !== "string"); + if (hasInvalidOption) errors = addError(errors, "An option of the \"picklist\" schema is not JSON compatible."); + jsonSchema.enum = valibotSchema.options; + if (valibotSchema.options.every((option) => typeof option === "string")) jsonSchema.type = "string"; + else if (valibotSchema.options.every((option) => typeof option === "number")) jsonSchema.type = "number"; + else if (!hasInvalidOption && config?.target !== "openapi-3.0") jsonSchema.type = ["string", "number"]; + break; + } + case "union": + jsonSchema.anyOf = valibotSchema.options.map((option) => convertSchema({}, option, config, context)); + break; + case "variant": + jsonSchema.oneOf = valibotSchema.options.map((option) => convertSchema({}, option, config, context)); + break; + case "intersect": + jsonSchema.allOf = valibotSchema.options.map((option) => convertSchema({}, option, config, context)); + break; + case "lazy": { + let wrappedValibotSchema = context.getterMap.get(valibotSchema.getter); + if (!wrappedValibotSchema) { + wrappedValibotSchema = valibotSchema.getter(void 0); + context.getterMap.set(valibotSchema.getter, wrappedValibotSchema); + } + let referenceId = context.referenceMap.get(wrappedValibotSchema); + if (!referenceId) { + referenceId = `${refCount++}`; + context.referenceMap.set(wrappedValibotSchema, referenceId); + context.definitions[referenceId] = convertSchema({}, wrappedValibotSchema, config, context, true); + } + jsonSchema.$ref = getDefinitionRef(referenceId); + if (config?.overrideRef) { + const refOverride = config.overrideRef({ + ...context, + referenceId, + valibotSchema: wrappedValibotSchema, + jsonSchema + }); + if (refOverride) jsonSchema.$ref = refOverride; + } + break; + } + default: errors = addError(errors, `The "${valibotSchema.type}" schema cannot be converted to JSON Schema.`); + } + if (config?.overrideSchema) { + const schemaOverride = config.overrideSchema({ + ...context, + referenceId: context.referenceMap.get(valibotSchema), + valibotSchema, + jsonSchema, + errors + }); + if (schemaOverride) return { ...schemaOverride }; + } + if (errors) for (const message of errors) handleError(message, config); + return jsonSchema; +} + +//#endregion +//#region src/storages/globalDefs/globalDefs.ts +let store; +/** +* Adds new definitions to the global schema definitions. +* +* @param definitions The schema definitions. +* +* @beta +*/ +function addGlobalDefs(definitions) { + store = { + ...store ?? {}, + ...definitions + }; +} +/** +* Returns the current global schema definitions. +* +* @returns The schema definitions. +* +* @beta +*/ +function getGlobalDefs() { + return store; +} + +//#endregion +//#region src/functions/toJsonSchema/toJsonSchema.ts +/** +* Converts a Valibot schema to the JSON Schema format. +* +* @param schema The Valibot schema object. +* @param config The JSON Schema configuration. +* +* @returns The converted JSON Schema. +*/ +function toJsonSchema(schema, config) { + const context = { + definitions: {}, + referenceMap: /* @__PURE__ */ new Map(), + getterMap: /* @__PURE__ */ new Map() + }; + const definitions = config?.definitions ?? getGlobalDefs(); + if (definitions) { + for (const key in definitions) context.referenceMap.set(definitions[key], key); + for (const key in definitions) context.definitions[key] = convertSchema({}, definitions[key], config, context, true); + } + const jsonSchema = convertSchema({}, schema, config, context); + const target = config?.target ?? "draft-07"; + if (target === "draft-2020-12") jsonSchema.$schema = "https://json-schema.org/draft/2020-12/schema"; + else if (target === "draft-07") jsonSchema.$schema = "http://json-schema.org/draft-07/schema#"; + if (context.referenceMap.size) jsonSchema.$defs = context.definitions; + return jsonSchema; +} + +//#endregion +//#region src/functions/toJsonSchemaDefs/toJsonSchemaDefs.ts +/** +* Converts Valibot schema definitions to JSON Schema definitions. +* +* @param definitions The Valibot schema definitions. +* @param config The JSON Schema configuration. +* +* @returns The converted JSON Schema definitions. +*/ +function toJsonSchemaDefs(definitions, config) { + const context = { + definitions: {}, + referenceMap: /* @__PURE__ */ new Map(), + getterMap: /* @__PURE__ */ new Map() + }; + for (const key in definitions) context.referenceMap.set(definitions[key], key); + for (const key in definitions) context.definitions[key] = convertSchema({}, definitions[key], config, context, true); + return context.definitions; +} + +//#endregion +//#region src/functions/toStandardJsonSchema/toStandardJsonSchema.ts +const SUPPORTED_TARGETS = [ + "draft-07", + "draft-2020-12", + "openapi-3.0" +]; +/** +* Converts a Valibot schema to the Standard JSON Schema format. +* +* @param schema The Valibot schema object. +* +* @returns The Standard JSON Schema. +*/ +function toStandardJsonSchema(schema) { + return { "~standard": { + ...schema["~standard"], + jsonSchema: { + input(options) { + if (SUPPORTED_TARGETS.includes(options.target)) return toJsonSchema(schema, { + typeMode: "input", + target: options.target, + ...options.libraryOptions + }); + throw new Error(`Unsupported target: ${options.target}`); + }, + output(options) { + if (SUPPORTED_TARGETS.includes(options.target)) return toJsonSchema(schema, { + typeMode: "output", + target: options.target, + ...options.libraryOptions + }); + throw new Error(`Unsupported target: ${options.target}`); + } + } + } }; +} + +//#endregion +exports.addGlobalDefs = addGlobalDefs; +exports.getGlobalDefs = getGlobalDefs; +exports.toJsonSchema = toJsonSchema; +exports.toJsonSchemaDefs = toJsonSchemaDefs; +exports.toStandardJsonSchema = toStandardJsonSchema; \ No newline at end of file diff --git a/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.d.cts b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..34dc49ce611a22d7870d81401235d90492cf2299 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.d.cts @@ -0,0 +1,955 @@ +//#region ../../library/src/types/metadata.d.ts +/** +* Base metadata interface. +*/ +interface BaseMetadata { + /** + * The object kind. + */ + readonly kind: "metadata"; + /** + * The metadata type. + */ + readonly type: string; + /** + * The metadata reference. + */ + readonly reference: (...args: any[]) => BaseMetadata; + /** + * The input, output and issue type. + * + * @internal + */ + readonly "~types"?: { + readonly input: TInput$1; + readonly output: TInput$1; + readonly issue: never; + } | undefined; +} +//#endregion +//#region ../../library/src/types/dataset.d.ts +/** +* Unknown dataset interface. +*/ +interface UnknownDataset { + /** + * Whether is's typed. + */ + typed?: false; + /** + * The dataset value. + */ + value: unknown; + /** + * The dataset issues. + */ + issues?: undefined; +} +/** +* Success dataset interface. +*/ +interface SuccessDataset { + /** + * Whether is's typed. + */ + typed: true; + /** + * The dataset value. + */ + value: TValue$1; + /** + * The dataset issues. + */ + issues?: undefined; +} +/** +* Partial dataset interface. +*/ +interface PartialDataset> { + /** + * Whether is's typed. + */ + typed: true; + /** + * The dataset value. + */ + value: TValue$1; + /** + * The dataset issues. + */ + issues: [TIssue, ...TIssue[]]; +} +/** +* Failure dataset interface. +*/ +interface FailureDataset> { + /** + * Whether is's typed. + */ + typed: false; + /** + * The dataset value. + */ + value: unknown; + /** + * The dataset issues. + */ + issues: [TIssue, ...TIssue[]]; +} +/** +* Output dataset type. +*/ +type OutputDataset> = SuccessDataset | PartialDataset | FailureDataset; +//#endregion +//#region ../../library/src/types/standard.d.ts +/** +* The Standard Schema properties interface. +*/ +interface StandardProps { + /** + * The version number of the standard. + */ + readonly version: 1; + /** + * The vendor name of the schema library. + */ + readonly vendor: "valibot"; + /** + * Validates unknown input values. + */ + readonly validate: (value: unknown) => StandardResult | Promise>; + /** + * Inferred types associated with the schema. + */ + readonly types?: StandardTypes | undefined; +} +/** +* The result interface of the validate function. +*/ +type StandardResult = StandardSuccessResult | StandardFailureResult; +/** +* The result interface if validation succeeds. +*/ +interface StandardSuccessResult { + /** + * The typed output value. + */ + readonly value: TOutput; + /** + * The non-existent issues. + */ + readonly issues?: undefined; +} +/** +* The result interface if validation fails. +*/ +interface StandardFailureResult { + /** + * The issues of failed validation. + */ + readonly issues: readonly StandardIssue[]; +} +/** +* The issue interface of the failure output. +*/ +interface StandardIssue { + /** + * The error message of the issue. + */ + readonly message: string; + /** + * The path of the issue, if any. + */ + readonly path?: readonly (PropertyKey | StandardPathItem)[] | undefined; +} +/** +* The path item interface of the issue. +*/ +interface StandardPathItem { + /** + * The key of the path item. + */ + readonly key: PropertyKey; +} +/** +* The Standard Schema types interface. +*/ +interface StandardTypes { + /** + * The input type of the schema. + */ + readonly input: TInput$1; + /** + * The output type of the schema. + */ + readonly output: TOutput; +} +//#endregion +//#region ../../library/src/types/schema.d.ts +/** +* Base schema interface. +*/ +interface BaseSchema> { + /** + * The object kind. + */ + readonly kind: "schema"; + /** + * The schema type. + */ + readonly type: string; + /** + * The schema reference. + */ + readonly reference: (...args: any[]) => BaseSchema>; + /** + * The expected property. + */ + readonly expects: string; + /** + * Whether it's async. + */ + readonly async: false; + /** + * The Standard Schema properties. + * + * @internal + */ + readonly "~standard": StandardProps; + /** + * Parses unknown input values. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly "~run": (dataset: UnknownDataset, config: Config>) => OutputDataset; + /** + * The input, output and issue type. + * + * @internal + */ + readonly "~types"?: { + readonly input: TInput$1; + readonly output: TOutput; + readonly issue: TIssue; + } | undefined; +} +/** +* Base schema async interface. +*/ +interface BaseSchemaAsync> extends Omit, "reference" | "async" | "~run"> { + /** + * The schema reference. + */ + readonly reference: (...args: any[]) => BaseSchema> | BaseSchemaAsync>; + /** + * Whether it's async. + */ + readonly async: true; + /** + * Parses unknown input values. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly "~run": (dataset: UnknownDataset, config: Config>) => Promise>; +} +//#endregion +//#region ../../library/src/types/transformation.d.ts +/** +* Base transformation interface. +*/ +interface BaseTransformation> { + /** + * The object kind. + */ + readonly kind: "transformation"; + /** + * The transformation type. + */ + readonly type: string; + /** + * The transformation reference. + */ + readonly reference: (...args: any[]) => BaseTransformation>; + /** + * Whether it's async. + */ + readonly async: false; + /** + * Transforms known input values. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly "~run": (dataset: SuccessDataset, config: Config>) => OutputDataset | TIssue>; + /** + * The input, output and issue type. + * + * @internal + */ + readonly "~types"?: { + readonly input: TInput$1; + readonly output: TOutput; + readonly issue: TIssue; + } | undefined; +} +/** +* Base transformation async interface. +*/ +interface BaseTransformationAsync> extends Omit, "reference" | "async" | "~run"> { + /** + * The transformation reference. + */ + readonly reference: (...args: any[]) => BaseTransformation> | BaseTransformationAsync>; + /** + * Whether it's async. + */ + readonly async: true; + /** + * Transforms known input values. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly "~run": (dataset: SuccessDataset, config: Config>) => Promise | TIssue>>; +} +//#endregion +//#region ../../library/src/types/validation.d.ts +/** +* Base validation interface. +*/ +interface BaseValidation> { + /** + * The object kind. + */ + readonly kind: "validation"; + /** + * The validation type. + */ + readonly type: string; + /** + * The validation reference. + */ + readonly reference: (...args: any[]) => BaseValidation>; + /** + * The expected property. + */ + readonly expects: string | null; + /** + * Whether it's async. + */ + readonly async: false; + /** + * Validates known input values. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly "~run": (dataset: OutputDataset>, config: Config>) => OutputDataset | TIssue>; + /** + * The input, output and issue type. + * + * @internal + */ + readonly "~types"?: { + readonly input: TInput$1; + readonly output: TOutput; + readonly issue: TIssue; + } | undefined; +} +/** +* Base validation async interface. +*/ +interface BaseValidationAsync> extends Omit, "reference" | "async" | "~run"> { + /** + * The validation reference. + */ + readonly reference: (...args: any[]) => BaseValidation> | BaseValidationAsync>; + /** + * Whether it's async. + */ + readonly async: true; + /** + * Validates known input values. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly "~run": (dataset: OutputDataset>, config: Config>) => Promise | TIssue>>; +} +//#endregion +//#region ../../library/src/types/infer.d.ts +/** +* Infer input type. +*/ +type InferInput> | BaseSchemaAsync> | BaseValidation> | BaseValidationAsync> | BaseTransformation> | BaseTransformationAsync> | BaseMetadata> = NonNullable["input"]; +/** +* Infer output type. +*/ +type InferOutput> | BaseSchemaAsync> | BaseValidation> | BaseValidationAsync> | BaseTransformation> | BaseTransformationAsync> | BaseMetadata> = NonNullable["output"]; +//#endregion +//#region ../../library/src/types/utils.d.ts +/** +* Constructs a type that is maybe readonly. +*/ +type MaybeReadonly = TValue$1 | Readonly; +//#endregion +//#region ../../library/src/types/other.d.ts +/** +* Error message type. +*/ +type ErrorMessage> = ((issue: TIssue) => string) | string; +//#endregion +//#region ../../library/src/types/issue.d.ts +/** +* Array path item interface. +*/ +interface ArrayPathItem { + /** + * The path item type. + */ + readonly type: "array"; + /** + * The path item origin. + */ + readonly origin: "value"; + /** + * The path item input. + */ + readonly input: MaybeReadonly; + /** + * The path item key. + */ + readonly key: number; + /** + * The path item value. + */ + readonly value: unknown; +} +/** +* Map path item interface. +*/ +interface MapPathItem { + /** + * The path item type. + */ + readonly type: "map"; + /** + * The path item origin. + */ + readonly origin: "key" | "value"; + /** + * The path item input. + */ + readonly input: Map; + /** + * The path item key. + */ + readonly key: unknown; + /** + * The path item value. + */ + readonly value: unknown; +} +/** +* Object path item interface. +*/ +interface ObjectPathItem { + /** + * The path item type. + */ + readonly type: "object"; + /** + * The path item origin. + */ + readonly origin: "key" | "value"; + /** + * The path item input. + */ + readonly input: Record; + /** + * The path item key. + */ + readonly key: string; + /** + * The path item value. + */ + readonly value: unknown; +} +/** +* Set path item interface. +*/ +interface SetPathItem { + /** + * The path item type. + */ + readonly type: "set"; + /** + * The path item origin. + */ + readonly origin: "value"; + /** + * The path item input. + */ + readonly input: Set; + /** + * The path item key. + */ + readonly key: null; + /** + * The path item key. + */ + readonly value: unknown; +} +/** +* Unknown path item interface. +*/ +interface UnknownPathItem { + /** + * The path item type. + */ + readonly type: "unknown"; + /** + * The path item origin. + */ + readonly origin: "key" | "value"; + /** + * The path item input. + */ + readonly input: unknown; + /** + * The path item key. + */ + readonly key: unknown; + /** + * The path item value. + */ + readonly value: unknown; +} +/** +* Issue path item type. +*/ +type IssuePathItem = ArrayPathItem | MapPathItem | ObjectPathItem | SetPathItem | UnknownPathItem; +/** +* Base issue interface. +*/ +interface BaseIssue extends Config> { + /** + * The issue kind. + */ + readonly kind: "schema" | "validation" | "transformation"; + /** + * The issue type. + */ + readonly type: string; + /** + * The raw input data. + */ + readonly input: TInput$1; + /** + * The expected property. + */ + readonly expected: string | null; + /** + * The received property. + */ + readonly received: string; + /** + * The error message. + */ + readonly message: string; + /** + * The input requirement. + */ + readonly requirement?: unknown | undefined; + /** + * The issue path. + */ + readonly path?: [IssuePathItem, ...IssuePathItem[]] | undefined; + /** + * The sub issues. + */ + readonly issues?: [BaseIssue, ...BaseIssue[]] | undefined; +} +//#endregion +//#region ../../library/src/types/config.d.ts +/** +* Config interface. +*/ +interface Config> { + /** + * The selected language. + */ + readonly lang?: string | undefined; + /** + * The error message. + */ + readonly message?: ErrorMessage | undefined; + /** + * Whether it should be aborted early. + */ + readonly abortEarly?: boolean | undefined; + /** + * Whether a pipe should be aborted early. + */ + readonly abortPipeEarly?: boolean | undefined; +} +//#endregion +//#region ../../library/src/types/pipe.d.ts +/** +* Pipe action type. +*/ +type PipeAction> = BaseValidation | BaseTransformation | BaseMetadata; +//#endregion +//#region src/types/schema.d.ts +type JsonSchemaTypeName = "string" | "number" | "integer" | "boolean" | "object" | "array" | "null"; +type JsonSchemaType = string | number | boolean | JsonSchemaObject | JsonSchemaArray | null; +interface JsonSchemaObject { + [key: string]: JsonSchemaType; +} +interface JsonSchemaArray extends Array {} +type JsonSchemaDefinition = JsonSchema | boolean; +/** +* JSON Schema interface. +*/ +interface JsonSchema { + $id?: string | undefined; + $ref?: string | undefined; + $schema?: string | undefined; + $comment?: string | undefined; + $defs?: Record | undefined; + type?: JsonSchemaTypeName | JsonSchemaTypeName[] | undefined; + nullable?: boolean | undefined; + enum?: JsonSchemaType[] | undefined; + const?: JsonSchemaType | undefined; + multipleOf?: number | undefined; + maximum?: number | undefined; + exclusiveMaximum?: number | undefined; + minimum?: number | undefined; + exclusiveMinimum?: number | undefined; + maxLength?: number | undefined; + minLength?: number | undefined; + pattern?: string | undefined; + items?: JsonSchemaDefinition | JsonSchemaDefinition[] | undefined; + prefixItems?: JsonSchemaDefinition[] | undefined; + additionalItems?: JsonSchemaDefinition | undefined; + maxItems?: number | undefined; + minItems?: number | undefined; + uniqueItems?: boolean | undefined; + contains?: JsonSchemaDefinition | undefined; + maxProperties?: number | undefined; + minProperties?: number | undefined; + required?: string[] | undefined; + properties?: Record | undefined; + patternProperties?: Record | undefined; + additionalProperties?: JsonSchemaDefinition | undefined; + dependencies?: Record | undefined; + propertyNames?: JsonSchemaDefinition | undefined; + if?: JsonSchemaDefinition | undefined; + then?: JsonSchemaDefinition | undefined; + else?: JsonSchemaDefinition | undefined; + allOf?: JsonSchemaDefinition[] | undefined; + anyOf?: JsonSchemaDefinition[] | undefined; + oneOf?: JsonSchemaDefinition[] | undefined; + not?: JsonSchemaDefinition | undefined; + format?: string | undefined; + contentMediaType?: string | undefined; + contentEncoding?: string | undefined; + definitions?: Record | undefined; + title?: string | undefined; + description?: string | undefined; + default?: JsonSchemaType | undefined; + readOnly?: boolean | undefined; + writeOnly?: boolean | undefined; + examples?: JsonSchemaType | undefined; +} +/** +* JSON Schema 7 interface. +* +* @deprecated Use `JsonSchema` instead. +*/ +interface JSONSchema7 extends JsonSchema {} +//#endregion +//#region src/types/config.d.ts +/** +* JSON Schema conversion context interface. +*/ +interface ConversionContext { + /** + * The JSON Schema definitions that have already been created. + */ + readonly definitions: Record; + /** + * The JSON Schema reference map that is used to look up the reference ID + * for a given Valibot schema. + */ + readonly referenceMap: Map>, string>; + /** + * The lazy schema getter map that is used internally to ensure that + * recursive lazy schemas are unwrapped only once. + */ + readonly getterMap: Map<(input: unknown) => BaseSchema>, BaseSchema>>; +} +/** +* JSON Schema override context interface for schemas. +* +* @beta +*/ +interface OverrideSchemaContext extends ConversionContext { + /** + * The JSON Schema reference ID. + */ + readonly referenceId: string | undefined; + /** + * The Valibot schema to be converted. + */ + readonly valibotSchema: BaseSchema>; + /** + * The converted JSON Schema. + */ + readonly jsonSchema: JsonSchema; + /** + * The errors of the current Valibot schema conversion. + */ + readonly errors: [string, ...string[]] | undefined; +} +/** +* JSON Schema override context interface for actions. +* +* @beta +*/ +interface OverrideActionContext { + /** + * The Valibot action to be converted. + */ + readonly valibotAction: PipeAction>; + /** + * The converted JSON Schema. + */ + readonly jsonSchema: JsonSchema; + /** + * The errors of the current Valibot action conversion. + */ + readonly errors: [string, ...string[]] | undefined; +} +/** +* JSON Schema override context interface for references. +* +* @beta +*/ +interface OverrideRefContext extends ConversionContext { + /** + * The JSON Schema reference ID. + */ + readonly referenceId: string; + /** + * The Valibot schema to be converted. + */ + readonly valibotSchema: BaseSchema>; + /** + * The converted JSON Schema. + */ + readonly jsonSchema: JsonSchema; +} +/** +* JSON Schema conversion config interface. +*/ +interface ConversionConfig { + /** + * The target JSON Schema draft version. Defaults to 'draft-07'. + */ + readonly target?: "draft-07" | "draft-2020-12" | "openapi-3.0"; + /** + * Whether to convert the input or output type of the Valibot schema to JSON Schema. + * + * When set to 'input', conversion stops before the first potential type + * transformation action or second schema in any pipeline. + * + * When set to 'output', conversion of any pipelines starts from the last + * schema in the pipeline. Therefore, the output type must be specified + * explicitly with a schema after the last type transformation action. + * + * @beta + */ + readonly typeMode?: "ignore" | "input" | "output"; + /** + * The policy for handling incompatible schemas and actions. + */ + readonly errorMode?: "throw" | "warn" | "ignore"; + /** + * The schema definitions for constructing recursive schemas. If not + * specified, the definitions are generated automatically as needed. + */ + readonly definitions?: Record>>; + /** + * Overrides the JSON Schema conversion for a specific Valibot schema. + * + * Only return a JSON Schema if you want to override the default conversion + * behaviour and suppress errors for a specific schema. Returning either + * `null` or `undefined` will skip the override. + * + * @param context The conversion context. + * + * @returns A JSON Schema, if overridden. + * + * @beta + */ + readonly overrideSchema?: (context: OverrideSchemaContext) => JsonSchema | null | undefined; + /** + * The actions that should be ignored during the conversion. + * + * @beta + */ + readonly ignoreActions?: string[]; + /** + * Overrides the JSON Schema reference for a specific Valibot action. + * + * Only return a JSON Schema if you want to override the default conversion + * behaviour and suppress errors for a specific action. Returning either + * `null` or `undefined` will skip the override. + * + * @param context The conversion context. + * + * @returns A JSON Schema, if overridden. + * + * @beta + */ + readonly overrideAction?: (context: OverrideActionContext) => JsonSchema | null | undefined; + /** + * Overrides the JSON Schema reference for a specific reference ID. + * + * @param context The conversion context. + * + * @returns A reference ID, if overridden. + * + * @beta + */ + readonly overrideRef?: (context: OverrideRefContext) => string | null | undefined; +} +//#endregion +//#region src/types/standard.d.ts +/** +* JSON Schema interface. +*/ +interface StandardJsonSchema { + /** + * The Standard JSON Schema properties. + */ + readonly "~standard": StandardJsonProps; +} +/** +* The Standard JSON Schema properties interface. +*/ +interface StandardJsonProps extends StandardProps { + /** + * Methods for generating the input/output JSON Schema. + */ + readonly jsonSchema: StandardJsonConverter; +} +/** +* The Standard JSON Schema converter interface. +*/ +interface StandardJsonConverter { + /** + * Converts the input type to JSON Schema. May throw if conversion is not supported. + */ + readonly input: (options: StandardJsonOptions) => Record; + /** + * Converts the output type to JSON Schema. May throw if conversion is not supported. + */ + readonly output: (options: StandardJsonOptions) => Record; +} +/** +* The target version of the generated JSON Schema. +*/ +type StandardJsonTarget = "draft-2020-12" | "draft-07" | "openapi-3.0" | ({} & string); +/** +* The options for the input/output methods. +*/ +interface StandardJsonOptions { + /** + * Specifies the target version of the generated JSON Schema. + */ + readonly target: StandardJsonTarget; + /** + * Explicit support for additional vendor-specific parameters, if needed. + */ + readonly libraryOptions?: Record | undefined; +} +//#endregion +//#region src/functions/toJsonSchema/toJsonSchema.d.ts +/** +* Converts a Valibot schema to the JSON Schema format. +* +* @param schema The Valibot schema object. +* @param config The JSON Schema configuration. +* +* @returns The converted JSON Schema. +*/ +declare function toJsonSchema(schema: BaseSchema>, config?: ConversionConfig): JsonSchema; +//#endregion +//#region src/functions/toJsonSchemaDefs/toJsonSchemaDefs.d.ts +/** +* Converts Valibot schema definitions to JSON Schema definitions. +* +* @param definitions The Valibot schema definitions. +* @param config The JSON Schema configuration. +* +* @returns The converted JSON Schema definitions. +*/ +declare function toJsonSchemaDefs>>>(definitions: TDefinitions, config?: Omit): { [TKey in keyof TDefinitions]: JsonSchema }; +//#endregion +//#region src/functions/toStandardJsonSchema/toStandardJsonSchema.d.ts +/** +* Converts a Valibot schema to the Standard JSON Schema format. +* +* @param schema The Valibot schema object. +* +* @returns The Standard JSON Schema. +*/ +declare function toStandardJsonSchema>>(schema: TSchema): StandardJsonSchema, InferOutput>; +//#endregion +//#region src/storages/globalDefs/globalDefs.d.ts +/** +* Adds new definitions to the global schema definitions. +* +* @param definitions The schema definitions. +* +* @beta +*/ +declare function addGlobalDefs(definitions: Record>>): void; +/** +* Returns the current global schema definitions. +* +* @returns The schema definitions. +* +* @beta +*/ +declare function getGlobalDefs(): Record>> | undefined; +//#endregion +export { ConversionConfig, ConversionContext, JSONSchema7, JsonSchema, OverrideActionContext, OverrideRefContext, OverrideSchemaContext, StandardJsonSchema, addGlobalDefs, getGlobalDefs, toJsonSchema, toJsonSchemaDefs, toStandardJsonSchema }; \ No newline at end of file diff --git a/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.d.mts b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..34dc49ce611a22d7870d81401235d90492cf2299 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.d.mts @@ -0,0 +1,955 @@ +//#region ../../library/src/types/metadata.d.ts +/** +* Base metadata interface. +*/ +interface BaseMetadata { + /** + * The object kind. + */ + readonly kind: "metadata"; + /** + * The metadata type. + */ + readonly type: string; + /** + * The metadata reference. + */ + readonly reference: (...args: any[]) => BaseMetadata; + /** + * The input, output and issue type. + * + * @internal + */ + readonly "~types"?: { + readonly input: TInput$1; + readonly output: TInput$1; + readonly issue: never; + } | undefined; +} +//#endregion +//#region ../../library/src/types/dataset.d.ts +/** +* Unknown dataset interface. +*/ +interface UnknownDataset { + /** + * Whether is's typed. + */ + typed?: false; + /** + * The dataset value. + */ + value: unknown; + /** + * The dataset issues. + */ + issues?: undefined; +} +/** +* Success dataset interface. +*/ +interface SuccessDataset { + /** + * Whether is's typed. + */ + typed: true; + /** + * The dataset value. + */ + value: TValue$1; + /** + * The dataset issues. + */ + issues?: undefined; +} +/** +* Partial dataset interface. +*/ +interface PartialDataset> { + /** + * Whether is's typed. + */ + typed: true; + /** + * The dataset value. + */ + value: TValue$1; + /** + * The dataset issues. + */ + issues: [TIssue, ...TIssue[]]; +} +/** +* Failure dataset interface. +*/ +interface FailureDataset> { + /** + * Whether is's typed. + */ + typed: false; + /** + * The dataset value. + */ + value: unknown; + /** + * The dataset issues. + */ + issues: [TIssue, ...TIssue[]]; +} +/** +* Output dataset type. +*/ +type OutputDataset> = SuccessDataset | PartialDataset | FailureDataset; +//#endregion +//#region ../../library/src/types/standard.d.ts +/** +* The Standard Schema properties interface. +*/ +interface StandardProps { + /** + * The version number of the standard. + */ + readonly version: 1; + /** + * The vendor name of the schema library. + */ + readonly vendor: "valibot"; + /** + * Validates unknown input values. + */ + readonly validate: (value: unknown) => StandardResult | Promise>; + /** + * Inferred types associated with the schema. + */ + readonly types?: StandardTypes | undefined; +} +/** +* The result interface of the validate function. +*/ +type StandardResult = StandardSuccessResult | StandardFailureResult; +/** +* The result interface if validation succeeds. +*/ +interface StandardSuccessResult { + /** + * The typed output value. + */ + readonly value: TOutput; + /** + * The non-existent issues. + */ + readonly issues?: undefined; +} +/** +* The result interface if validation fails. +*/ +interface StandardFailureResult { + /** + * The issues of failed validation. + */ + readonly issues: readonly StandardIssue[]; +} +/** +* The issue interface of the failure output. +*/ +interface StandardIssue { + /** + * The error message of the issue. + */ + readonly message: string; + /** + * The path of the issue, if any. + */ + readonly path?: readonly (PropertyKey | StandardPathItem)[] | undefined; +} +/** +* The path item interface of the issue. +*/ +interface StandardPathItem { + /** + * The key of the path item. + */ + readonly key: PropertyKey; +} +/** +* The Standard Schema types interface. +*/ +interface StandardTypes { + /** + * The input type of the schema. + */ + readonly input: TInput$1; + /** + * The output type of the schema. + */ + readonly output: TOutput; +} +//#endregion +//#region ../../library/src/types/schema.d.ts +/** +* Base schema interface. +*/ +interface BaseSchema> { + /** + * The object kind. + */ + readonly kind: "schema"; + /** + * The schema type. + */ + readonly type: string; + /** + * The schema reference. + */ + readonly reference: (...args: any[]) => BaseSchema>; + /** + * The expected property. + */ + readonly expects: string; + /** + * Whether it's async. + */ + readonly async: false; + /** + * The Standard Schema properties. + * + * @internal + */ + readonly "~standard": StandardProps; + /** + * Parses unknown input values. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly "~run": (dataset: UnknownDataset, config: Config>) => OutputDataset; + /** + * The input, output and issue type. + * + * @internal + */ + readonly "~types"?: { + readonly input: TInput$1; + readonly output: TOutput; + readonly issue: TIssue; + } | undefined; +} +/** +* Base schema async interface. +*/ +interface BaseSchemaAsync> extends Omit, "reference" | "async" | "~run"> { + /** + * The schema reference. + */ + readonly reference: (...args: any[]) => BaseSchema> | BaseSchemaAsync>; + /** + * Whether it's async. + */ + readonly async: true; + /** + * Parses unknown input values. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly "~run": (dataset: UnknownDataset, config: Config>) => Promise>; +} +//#endregion +//#region ../../library/src/types/transformation.d.ts +/** +* Base transformation interface. +*/ +interface BaseTransformation> { + /** + * The object kind. + */ + readonly kind: "transformation"; + /** + * The transformation type. + */ + readonly type: string; + /** + * The transformation reference. + */ + readonly reference: (...args: any[]) => BaseTransformation>; + /** + * Whether it's async. + */ + readonly async: false; + /** + * Transforms known input values. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly "~run": (dataset: SuccessDataset, config: Config>) => OutputDataset | TIssue>; + /** + * The input, output and issue type. + * + * @internal + */ + readonly "~types"?: { + readonly input: TInput$1; + readonly output: TOutput; + readonly issue: TIssue; + } | undefined; +} +/** +* Base transformation async interface. +*/ +interface BaseTransformationAsync> extends Omit, "reference" | "async" | "~run"> { + /** + * The transformation reference. + */ + readonly reference: (...args: any[]) => BaseTransformation> | BaseTransformationAsync>; + /** + * Whether it's async. + */ + readonly async: true; + /** + * Transforms known input values. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly "~run": (dataset: SuccessDataset, config: Config>) => Promise | TIssue>>; +} +//#endregion +//#region ../../library/src/types/validation.d.ts +/** +* Base validation interface. +*/ +interface BaseValidation> { + /** + * The object kind. + */ + readonly kind: "validation"; + /** + * The validation type. + */ + readonly type: string; + /** + * The validation reference. + */ + readonly reference: (...args: any[]) => BaseValidation>; + /** + * The expected property. + */ + readonly expects: string | null; + /** + * Whether it's async. + */ + readonly async: false; + /** + * Validates known input values. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly "~run": (dataset: OutputDataset>, config: Config>) => OutputDataset | TIssue>; + /** + * The input, output and issue type. + * + * @internal + */ + readonly "~types"?: { + readonly input: TInput$1; + readonly output: TOutput; + readonly issue: TIssue; + } | undefined; +} +/** +* Base validation async interface. +*/ +interface BaseValidationAsync> extends Omit, "reference" | "async" | "~run"> { + /** + * The validation reference. + */ + readonly reference: (...args: any[]) => BaseValidation> | BaseValidationAsync>; + /** + * Whether it's async. + */ + readonly async: true; + /** + * Validates known input values. + * + * @param dataset The input dataset. + * @param config The configuration. + * + * @returns The output dataset. + * + * @internal + */ + readonly "~run": (dataset: OutputDataset>, config: Config>) => Promise | TIssue>>; +} +//#endregion +//#region ../../library/src/types/infer.d.ts +/** +* Infer input type. +*/ +type InferInput> | BaseSchemaAsync> | BaseValidation> | BaseValidationAsync> | BaseTransformation> | BaseTransformationAsync> | BaseMetadata> = NonNullable["input"]; +/** +* Infer output type. +*/ +type InferOutput> | BaseSchemaAsync> | BaseValidation> | BaseValidationAsync> | BaseTransformation> | BaseTransformationAsync> | BaseMetadata> = NonNullable["output"]; +//#endregion +//#region ../../library/src/types/utils.d.ts +/** +* Constructs a type that is maybe readonly. +*/ +type MaybeReadonly = TValue$1 | Readonly; +//#endregion +//#region ../../library/src/types/other.d.ts +/** +* Error message type. +*/ +type ErrorMessage> = ((issue: TIssue) => string) | string; +//#endregion +//#region ../../library/src/types/issue.d.ts +/** +* Array path item interface. +*/ +interface ArrayPathItem { + /** + * The path item type. + */ + readonly type: "array"; + /** + * The path item origin. + */ + readonly origin: "value"; + /** + * The path item input. + */ + readonly input: MaybeReadonly; + /** + * The path item key. + */ + readonly key: number; + /** + * The path item value. + */ + readonly value: unknown; +} +/** +* Map path item interface. +*/ +interface MapPathItem { + /** + * The path item type. + */ + readonly type: "map"; + /** + * The path item origin. + */ + readonly origin: "key" | "value"; + /** + * The path item input. + */ + readonly input: Map; + /** + * The path item key. + */ + readonly key: unknown; + /** + * The path item value. + */ + readonly value: unknown; +} +/** +* Object path item interface. +*/ +interface ObjectPathItem { + /** + * The path item type. + */ + readonly type: "object"; + /** + * The path item origin. + */ + readonly origin: "key" | "value"; + /** + * The path item input. + */ + readonly input: Record; + /** + * The path item key. + */ + readonly key: string; + /** + * The path item value. + */ + readonly value: unknown; +} +/** +* Set path item interface. +*/ +interface SetPathItem { + /** + * The path item type. + */ + readonly type: "set"; + /** + * The path item origin. + */ + readonly origin: "value"; + /** + * The path item input. + */ + readonly input: Set; + /** + * The path item key. + */ + readonly key: null; + /** + * The path item key. + */ + readonly value: unknown; +} +/** +* Unknown path item interface. +*/ +interface UnknownPathItem { + /** + * The path item type. + */ + readonly type: "unknown"; + /** + * The path item origin. + */ + readonly origin: "key" | "value"; + /** + * The path item input. + */ + readonly input: unknown; + /** + * The path item key. + */ + readonly key: unknown; + /** + * The path item value. + */ + readonly value: unknown; +} +/** +* Issue path item type. +*/ +type IssuePathItem = ArrayPathItem | MapPathItem | ObjectPathItem | SetPathItem | UnknownPathItem; +/** +* Base issue interface. +*/ +interface BaseIssue extends Config> { + /** + * The issue kind. + */ + readonly kind: "schema" | "validation" | "transformation"; + /** + * The issue type. + */ + readonly type: string; + /** + * The raw input data. + */ + readonly input: TInput$1; + /** + * The expected property. + */ + readonly expected: string | null; + /** + * The received property. + */ + readonly received: string; + /** + * The error message. + */ + readonly message: string; + /** + * The input requirement. + */ + readonly requirement?: unknown | undefined; + /** + * The issue path. + */ + readonly path?: [IssuePathItem, ...IssuePathItem[]] | undefined; + /** + * The sub issues. + */ + readonly issues?: [BaseIssue, ...BaseIssue[]] | undefined; +} +//#endregion +//#region ../../library/src/types/config.d.ts +/** +* Config interface. +*/ +interface Config> { + /** + * The selected language. + */ + readonly lang?: string | undefined; + /** + * The error message. + */ + readonly message?: ErrorMessage | undefined; + /** + * Whether it should be aborted early. + */ + readonly abortEarly?: boolean | undefined; + /** + * Whether a pipe should be aborted early. + */ + readonly abortPipeEarly?: boolean | undefined; +} +//#endregion +//#region ../../library/src/types/pipe.d.ts +/** +* Pipe action type. +*/ +type PipeAction> = BaseValidation | BaseTransformation | BaseMetadata; +//#endregion +//#region src/types/schema.d.ts +type JsonSchemaTypeName = "string" | "number" | "integer" | "boolean" | "object" | "array" | "null"; +type JsonSchemaType = string | number | boolean | JsonSchemaObject | JsonSchemaArray | null; +interface JsonSchemaObject { + [key: string]: JsonSchemaType; +} +interface JsonSchemaArray extends Array {} +type JsonSchemaDefinition = JsonSchema | boolean; +/** +* JSON Schema interface. +*/ +interface JsonSchema { + $id?: string | undefined; + $ref?: string | undefined; + $schema?: string | undefined; + $comment?: string | undefined; + $defs?: Record | undefined; + type?: JsonSchemaTypeName | JsonSchemaTypeName[] | undefined; + nullable?: boolean | undefined; + enum?: JsonSchemaType[] | undefined; + const?: JsonSchemaType | undefined; + multipleOf?: number | undefined; + maximum?: number | undefined; + exclusiveMaximum?: number | undefined; + minimum?: number | undefined; + exclusiveMinimum?: number | undefined; + maxLength?: number | undefined; + minLength?: number | undefined; + pattern?: string | undefined; + items?: JsonSchemaDefinition | JsonSchemaDefinition[] | undefined; + prefixItems?: JsonSchemaDefinition[] | undefined; + additionalItems?: JsonSchemaDefinition | undefined; + maxItems?: number | undefined; + minItems?: number | undefined; + uniqueItems?: boolean | undefined; + contains?: JsonSchemaDefinition | undefined; + maxProperties?: number | undefined; + minProperties?: number | undefined; + required?: string[] | undefined; + properties?: Record | undefined; + patternProperties?: Record | undefined; + additionalProperties?: JsonSchemaDefinition | undefined; + dependencies?: Record | undefined; + propertyNames?: JsonSchemaDefinition | undefined; + if?: JsonSchemaDefinition | undefined; + then?: JsonSchemaDefinition | undefined; + else?: JsonSchemaDefinition | undefined; + allOf?: JsonSchemaDefinition[] | undefined; + anyOf?: JsonSchemaDefinition[] | undefined; + oneOf?: JsonSchemaDefinition[] | undefined; + not?: JsonSchemaDefinition | undefined; + format?: string | undefined; + contentMediaType?: string | undefined; + contentEncoding?: string | undefined; + definitions?: Record | undefined; + title?: string | undefined; + description?: string | undefined; + default?: JsonSchemaType | undefined; + readOnly?: boolean | undefined; + writeOnly?: boolean | undefined; + examples?: JsonSchemaType | undefined; +} +/** +* JSON Schema 7 interface. +* +* @deprecated Use `JsonSchema` instead. +*/ +interface JSONSchema7 extends JsonSchema {} +//#endregion +//#region src/types/config.d.ts +/** +* JSON Schema conversion context interface. +*/ +interface ConversionContext { + /** + * The JSON Schema definitions that have already been created. + */ + readonly definitions: Record; + /** + * The JSON Schema reference map that is used to look up the reference ID + * for a given Valibot schema. + */ + readonly referenceMap: Map>, string>; + /** + * The lazy schema getter map that is used internally to ensure that + * recursive lazy schemas are unwrapped only once. + */ + readonly getterMap: Map<(input: unknown) => BaseSchema>, BaseSchema>>; +} +/** +* JSON Schema override context interface for schemas. +* +* @beta +*/ +interface OverrideSchemaContext extends ConversionContext { + /** + * The JSON Schema reference ID. + */ + readonly referenceId: string | undefined; + /** + * The Valibot schema to be converted. + */ + readonly valibotSchema: BaseSchema>; + /** + * The converted JSON Schema. + */ + readonly jsonSchema: JsonSchema; + /** + * The errors of the current Valibot schema conversion. + */ + readonly errors: [string, ...string[]] | undefined; +} +/** +* JSON Schema override context interface for actions. +* +* @beta +*/ +interface OverrideActionContext { + /** + * The Valibot action to be converted. + */ + readonly valibotAction: PipeAction>; + /** + * The converted JSON Schema. + */ + readonly jsonSchema: JsonSchema; + /** + * The errors of the current Valibot action conversion. + */ + readonly errors: [string, ...string[]] | undefined; +} +/** +* JSON Schema override context interface for references. +* +* @beta +*/ +interface OverrideRefContext extends ConversionContext { + /** + * The JSON Schema reference ID. + */ + readonly referenceId: string; + /** + * The Valibot schema to be converted. + */ + readonly valibotSchema: BaseSchema>; + /** + * The converted JSON Schema. + */ + readonly jsonSchema: JsonSchema; +} +/** +* JSON Schema conversion config interface. +*/ +interface ConversionConfig { + /** + * The target JSON Schema draft version. Defaults to 'draft-07'. + */ + readonly target?: "draft-07" | "draft-2020-12" | "openapi-3.0"; + /** + * Whether to convert the input or output type of the Valibot schema to JSON Schema. + * + * When set to 'input', conversion stops before the first potential type + * transformation action or second schema in any pipeline. + * + * When set to 'output', conversion of any pipelines starts from the last + * schema in the pipeline. Therefore, the output type must be specified + * explicitly with a schema after the last type transformation action. + * + * @beta + */ + readonly typeMode?: "ignore" | "input" | "output"; + /** + * The policy for handling incompatible schemas and actions. + */ + readonly errorMode?: "throw" | "warn" | "ignore"; + /** + * The schema definitions for constructing recursive schemas. If not + * specified, the definitions are generated automatically as needed. + */ + readonly definitions?: Record>>; + /** + * Overrides the JSON Schema conversion for a specific Valibot schema. + * + * Only return a JSON Schema if you want to override the default conversion + * behaviour and suppress errors for a specific schema. Returning either + * `null` or `undefined` will skip the override. + * + * @param context The conversion context. + * + * @returns A JSON Schema, if overridden. + * + * @beta + */ + readonly overrideSchema?: (context: OverrideSchemaContext) => JsonSchema | null | undefined; + /** + * The actions that should be ignored during the conversion. + * + * @beta + */ + readonly ignoreActions?: string[]; + /** + * Overrides the JSON Schema reference for a specific Valibot action. + * + * Only return a JSON Schema if you want to override the default conversion + * behaviour and suppress errors for a specific action. Returning either + * `null` or `undefined` will skip the override. + * + * @param context The conversion context. + * + * @returns A JSON Schema, if overridden. + * + * @beta + */ + readonly overrideAction?: (context: OverrideActionContext) => JsonSchema | null | undefined; + /** + * Overrides the JSON Schema reference for a specific reference ID. + * + * @param context The conversion context. + * + * @returns A reference ID, if overridden. + * + * @beta + */ + readonly overrideRef?: (context: OverrideRefContext) => string | null | undefined; +} +//#endregion +//#region src/types/standard.d.ts +/** +* JSON Schema interface. +*/ +interface StandardJsonSchema { + /** + * The Standard JSON Schema properties. + */ + readonly "~standard": StandardJsonProps; +} +/** +* The Standard JSON Schema properties interface. +*/ +interface StandardJsonProps extends StandardProps { + /** + * Methods for generating the input/output JSON Schema. + */ + readonly jsonSchema: StandardJsonConverter; +} +/** +* The Standard JSON Schema converter interface. +*/ +interface StandardJsonConverter { + /** + * Converts the input type to JSON Schema. May throw if conversion is not supported. + */ + readonly input: (options: StandardJsonOptions) => Record; + /** + * Converts the output type to JSON Schema. May throw if conversion is not supported. + */ + readonly output: (options: StandardJsonOptions) => Record; +} +/** +* The target version of the generated JSON Schema. +*/ +type StandardJsonTarget = "draft-2020-12" | "draft-07" | "openapi-3.0" | ({} & string); +/** +* The options for the input/output methods. +*/ +interface StandardJsonOptions { + /** + * Specifies the target version of the generated JSON Schema. + */ + readonly target: StandardJsonTarget; + /** + * Explicit support for additional vendor-specific parameters, if needed. + */ + readonly libraryOptions?: Record | undefined; +} +//#endregion +//#region src/functions/toJsonSchema/toJsonSchema.d.ts +/** +* Converts a Valibot schema to the JSON Schema format. +* +* @param schema The Valibot schema object. +* @param config The JSON Schema configuration. +* +* @returns The converted JSON Schema. +*/ +declare function toJsonSchema(schema: BaseSchema>, config?: ConversionConfig): JsonSchema; +//#endregion +//#region src/functions/toJsonSchemaDefs/toJsonSchemaDefs.d.ts +/** +* Converts Valibot schema definitions to JSON Schema definitions. +* +* @param definitions The Valibot schema definitions. +* @param config The JSON Schema configuration. +* +* @returns The converted JSON Schema definitions. +*/ +declare function toJsonSchemaDefs>>>(definitions: TDefinitions, config?: Omit): { [TKey in keyof TDefinitions]: JsonSchema }; +//#endregion +//#region src/functions/toStandardJsonSchema/toStandardJsonSchema.d.ts +/** +* Converts a Valibot schema to the Standard JSON Schema format. +* +* @param schema The Valibot schema object. +* +* @returns The Standard JSON Schema. +*/ +declare function toStandardJsonSchema>>(schema: TSchema): StandardJsonSchema, InferOutput>; +//#endregion +//#region src/storages/globalDefs/globalDefs.d.ts +/** +* Adds new definitions to the global schema definitions. +* +* @param definitions The schema definitions. +* +* @beta +*/ +declare function addGlobalDefs(definitions: Record>>): void; +/** +* Returns the current global schema definitions. +* +* @returns The schema definitions. +* +* @beta +*/ +declare function getGlobalDefs(): Record>> | undefined; +//#endregion +export { ConversionConfig, ConversionContext, JSONSchema7, JsonSchema, OverrideActionContext, OverrideRefContext, OverrideSchemaContext, StandardJsonSchema, addGlobalDefs, getGlobalDefs, toJsonSchema, toJsonSchemaDefs, toStandardJsonSchema }; \ No newline at end of file diff --git a/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.min.cjs b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.min.cjs new file mode 100644 index 0000000000000000000000000000000000000000..808ec2dd92b62a1c1f62cc068f306a1eb8cba815 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.min.cjs @@ -0,0 +1 @@ +function e(e,t){return e?(e.push(t),e):[t]}const t=/[.*+?^${}()|[\]\\]/g;function n(e){return e.replace(t,`\\$&`)}function r(e,t){switch(t?.errorMode){case`ignore`:break;case`warn`:console.warn(e);break;default:throw Error(e)}}function i(e){return typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e)||typeof e==`string`}function a(e){return e.every(i)}function o(t,o,s){if(s?.ignoreActions?.includes(o.type))return t;let c;switch(o.type){case`base64`:t.contentEncoding=`base64`;break;case`bic`:case`cuid2`:case`decimal`:case`digits`:case`domain`:case`emoji`:case`hash`:case`hexadecimal`:case`hex_color`:case`isrc`:case`iso_time_second`:case`iso_week`:case`mac`:case`mac48`:case`mac64`:case`nanoid`:case`octal`:case`slug`:case`ulid`:t.pattern?c=e(c,`The "${o.type}" action is not supported in combination with another regex action.`):t.pattern=o.requirement.source;break;case`description`:t.description=o.description;break;case`email`:case`rfc_email`:t.format=`email`;break;case`ends_with`:t.pattern?c=e(c,`The "${o.type}" action is not supported in combination with another regex action.`):t.pattern=`${n(o.requirement)}$`;break;case`empty`:t.type===`array`?t.maxItems=0:(t.type!==`string`&&(c=e(c,`The "${o.type}" action is not supported on type "${t.type}".`)),t.maxLength=0);break;case`entries`:t.minProperties=o.requirement,t.maxProperties=o.requirement;break;case`examples`:Array.isArray(t.examples)?t.examples=[...t.examples,...o.examples]:t.examples=o.examples;break;case`gt_value`:if(t.type!==`number`&&t.type!==`integer`&&(c=e(c,`The "gt_value" action is not supported on type "${t.type}".`)),s?.target===`openapi-3.0`){c=e(c,`The "gt_value" action is not supported for OpenAPI 3.0.`);break}t.exclusiveMinimum=o.requirement;break;case`includes`:t.pattern?c=e(c,`The "${o.type}" action is not supported in combination with another regex action.`):t.pattern=n(o.requirement);break;case`integer`:t.type=`integer`;break;case`ipv4`:t.format=`ipv4`;break;case`ipv6`:t.format=`ipv6`;break;case`iso_date`:t.format=`date`;break;case`iso_date_time`:case`iso_timestamp`:t.format=`date-time`;break;case`iso_time`:t.format=`time`;break;case`jws_compact`:t.pattern?c=e(c,`The "${o.type}" action is not supported in combination with another regex action.`):t.pattern=o.requirement.source;break;case`length`:t.type===`array`?(t.minItems=o.requirement,t.maxItems=o.requirement):(t.type!==`string`&&(c=e(c,`The "${o.type}" action is not supported on type "${t.type}".`)),t.minLength=o.requirement,t.maxLength=o.requirement);break;case`lt_value`:if(t.type!==`number`&&t.type!==`integer`&&(c=e(c,`The "lt_value" action is not supported on type "${t.type}".`)),s?.target===`openapi-3.0`){c=e(c,`The "lt_value" action is not supported for OpenAPI 3.0.`);break}t.exclusiveMaximum=o.requirement;break;case`max_entries`:t.maxProperties=o.requirement;break;case`max_length`:t.type===`array`?t.maxItems=o.requirement:(t.type!==`string`&&(c=e(c,`The "${o.type}" action is not supported on type "${t.type}".`)),t.maxLength=o.requirement);break;case`max_value`:t.type!==`number`&&t.type!==`integer`&&(c=e(c,`The "max_value" action is not supported on type "${t.type}".`)),t.maximum=o.requirement;break;case`metadata`:typeof o.metadata.title==`string`&&(t.title=o.metadata.title),typeof o.metadata.description==`string`&&(t.description=o.metadata.description),Array.isArray(o.metadata.examples)&&(Array.isArray(t.examples)?t.examples=[...t.examples,...o.metadata.examples]:t.examples=o.metadata.examples);break;case`min_entries`:t.minProperties=o.requirement;break;case`min_length`:t.type===`array`?t.minItems=o.requirement:(t.type!==`string`&&(c=e(c,`The "${o.type}" action is not supported on type "${t.type}".`)),t.minLength=o.requirement);break;case`min_value`:t.type!==`number`&&t.type!==`integer`&&(c=e(c,`The "min_value" action is not supported on type "${t.type}".`)),t.minimum=o.requirement;break;case`multiple_of`:t.multipleOf=o.requirement;break;case`non_empty`:t.type===`array`?t.minItems=1:(t.type!==`string`&&(c=e(c,`The "${o.type}" action is not supported on type "${t.type}".`)),t.minLength=1);break;case`not_value`:if(!i(o.requirement)){c=e(c,`The requirement of the "not_value" action is not JSON compatible.`);break}s?.target===`openapi-3.0`?t.not={enum:[o.requirement]}:t.not={const:o.requirement};break;case`not_values`:if(!a(o.requirement)){c=e(c,`A requirement of the "not_values" action is not JSON compatible.`);break}t.not={enum:o.requirement};break;case`regex`:o.requirement.flags&&(c=e(c,`RegExp flags are not supported by JSON Schema.`)),t.pattern?c=e(c,`The "${o.type}" action is not supported in combination with another regex action.`):t.pattern=o.requirement.source;break;case`safe_integer`:t.type=`integer`,(typeof t.minimum!=`number`||t.minimum<-(2**53-1))&&(t.minimum=-(2**53-1)),(typeof t.maximum!=`number`||t.maximum>2**53-1)&&(t.maximum=2**53-1);break;case`starts_with`:t.pattern?c=e(c,`The "${o.type}" action is not supported in combination with another regex action.`):t.pattern=`^${n(o.requirement)}`;break;case`title`:t.title=o.title;break;case`url`:t.format=`uri`;break;case`uuid`:t.format=`uuid`;break;case`value`:if(!i(o.requirement)){c=e(c,`The requirement of the "value" action is not JSON compatible.`);break}s?.target===`openapi-3.0`?t.enum=[o.requirement]:t.const=o.requirement;break;case`values`:if(!a(o.requirement)){c=e(c,`A requirement of the "values" action is not JSON compatible.`);break}t.enum=o.requirement;break;default:c=e(c,`The "${o.type}" action cannot be converted to JSON Schema.`)}if(s?.overrideAction){let e=s.overrideAction({valibotAction:o,jsonSchema:t,errors:c});if(e)return{...e}}if(c)for(let e of c)r(e,s);return t}function s(e){return e.flatMap(e=>`pipe`in e?s(e.pipe):e)}function c(e){return`#/$defs/${e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}`}let l=0;function u(t,n,i,a,d=!1){if(!d){let e=a.referenceMap.get(n);if(e){if(t.$ref=c(e),i?.overrideRef){let r=i.overrideRef({...a,referenceId:e,valibotSchema:n,jsonSchema:t});r&&(t.$ref=r)}return t}}if(`pipe`in n){let e=s(n.pipe),c=0,l=e.length-1;if(i?.typeMode===`input`){let t=e.slice(1).findIndex(e=>e.kind===`schema`||e.kind===`transformation`&&(e.type===`find_item`||e.type===`parse_json`||e.type===`raw_transform`||e.type===`reduce_items`||e.type===`stringify_json`||e.type===`to_bigint`||e.type===`to_boolean`||e.type===`to_date`||e.type===`to_number`||e.type===`to_string`||e.type===`transform`));t!==-1&&(l=t)}else if(i?.typeMode===`output`){let t=e.findLastIndex(e=>e.kind===`schema`);t!==-1&&(c=t)}for(let n=c;n<=l;n++){let s=e[n];s.kind===`schema`?(n>c&&r(`Set the "typeMode" config to "input" or "output" to convert pipelines with multiple schemas.`,i),t=u(t,s,i,a,!0)):t=o(t,s,i)}return t}let f;switch(n.type){case`boolean`:t.type=`boolean`;break;case`null`:i?.target===`openapi-3.0`?t.enum=[null]:t.type=`null`;break;case`number`:t.type=`number`;break;case`string`:t.type=`string`;break;case`array`:t.type=`array`,t.items=u({},n.item,i,a);break;case`tuple`:case`tuple_with_rest`:case`loose_tuple`:case`strict_tuple`:if(t.type=`array`,i?.target===`openapi-3.0`){t.items={anyOf:[]},t.minItems=n.items.length;for(let e of n.items)t.items.anyOf.push(u({},e,i,a));n.type===`tuple_with_rest`?t.items.anyOf.push(u({},n.rest,i,a)):(n.type===`strict_tuple`||n.type===`tuple`)&&(t.maxItems=n.items.length)}else if(i?.target===`draft-2020-12`){t.prefixItems=[],t.minItems=n.items.length;for(let e of n.items)t.prefixItems.push(u({},e,i,a));n.type===`tuple_with_rest`?t.items=u({},n.rest,i,a):n.type===`strict_tuple`&&(t.items=!1)}else{t.items=[],t.minItems=n.items.length;for(let e of n.items)t.items.push(u({},e,i,a));n.type===`tuple_with_rest`?t.additionalItems=u({},n.rest,i,a):n.type===`strict_tuple`&&(t.additionalItems=!1)}break;case`object`:case`object_with_rest`:case`loose_object`:case`strict_object`:for(let e in t.type=`object`,t.properties={},t.required=[],n.entries){let r=n.entries[e];t.properties[e]=u({},r,i,a),r.type!==`exact_optional`&&r.type!==`nullish`&&r.type!==`optional`&&t.required.push(e)}n.type===`object_with_rest`?t.additionalProperties=u({},n.rest,i,a):n.type===`strict_object`&&(t.additionalProperties=!1);break;case`record`:i?.target===`openapi-3.0`&&`pipe`in n.key&&(f=e(f,`The "record" schema with a schema for the key that contains a "pipe" cannot be converted to JSON Schema.`)),n.key.type!==`string`&&(f=e(f,`The "record" schema with the "${n.key.type}" schema for the key cannot be converted to JSON Schema.`)),t.type=`object`,i?.target!==`openapi-3.0`&&(t.propertyNames=u({},n.key,i,a)),t.additionalProperties=u({},n.value,i,a);break;case`any`:case`unknown`:break;case`never`:t.not={};break;case`nullable`:case`nullish`:if(i?.target===`openapi-3.0`){let e=u({},n.wrapped,i,a);Object.assign(t,e),t.nullable=!0}else t.anyOf=[u({},n.wrapped,i,a),{type:`null`}];n.default!==void 0&&(t.default=typeof n.default==`function`?n.default():n.default);break;case`exact_optional`:case`optional`:case`undefinedable`:t=u(t,n.wrapped,i,a),n.default!==void 0&&(t.default=typeof n.default==`function`?n.default():n.default);break;case`literal`:typeof n.literal!=`boolean`&&typeof n.literal!=`number`&&typeof n.literal!=`string`&&(f=e(f,`The value of the "literal" schema is not JSON compatible.`)),i?.target===`openapi-3.0`?t.enum=[n.literal]:t.const=n.literal;break;case`enum`:t.enum=n.options,n.options.every(e=>typeof e==`string`)?t.type=`string`:n.options.every(e=>typeof e==`number`)?t.type=`number`:i?.target!==`openapi-3.0`&&(t.type=[`string`,`number`]);break;case`picklist`:{let r=n.options.some(e=>typeof e!=`number`&&typeof e!=`string`);r&&(f=e(f,`An option of the "picklist" schema is not JSON compatible.`)),t.enum=n.options,n.options.every(e=>typeof e==`string`)?t.type=`string`:n.options.every(e=>typeof e==`number`)?t.type=`number`:!r&&i?.target!==`openapi-3.0`&&(t.type=[`string`,`number`]);break}case`union`:t.anyOf=n.options.map(e=>u({},e,i,a));break;case`variant`:t.oneOf=n.options.map(e=>u({},e,i,a));break;case`intersect`:t.allOf=n.options.map(e=>u({},e,i,a));break;case`lazy`:{let e=a.getterMap.get(n.getter);e||(e=n.getter(void 0),a.getterMap.set(n.getter,e));let r=a.referenceMap.get(e);if(r||(r=`${l++}`,a.referenceMap.set(e,r),a.definitions[r]=u({},e,i,a,!0)),t.$ref=c(r),i?.overrideRef){let n=i.overrideRef({...a,referenceId:r,valibotSchema:e,jsonSchema:t});n&&(t.$ref=n)}break}default:f=e(f,`The "${n.type}" schema cannot be converted to JSON Schema.`)}if(i?.overrideSchema){let e=i.overrideSchema({...a,referenceId:a.referenceMap.get(n),valibotSchema:n,jsonSchema:t,errors:f});if(e)return{...e}}if(f)for(let e of f)r(e,i);return t}let d;function f(e){d={...d??{},...e}}function p(){return d}function m(e,t){let n={definitions:{},referenceMap:new Map,getterMap:new Map},r=t?.definitions??p();if(r){for(let e in r)n.referenceMap.set(r[e],e);for(let e in r)n.definitions[e]=u({},r[e],t,n,!0)}let i=u({},e,t,n),a=t?.target??`draft-07`;return a===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:a===`draft-07`&&(i.$schema=`http://json-schema.org/draft-07/schema#`),n.referenceMap.size&&(i.$defs=n.definitions),i}function h(e,t){let n={definitions:{},referenceMap:new Map,getterMap:new Map};for(let t in e)n.referenceMap.set(e[t],t);for(let r in e)n.definitions[r]=u({},e[r],t,n,!0);return n.definitions}const g=[`draft-07`,`draft-2020-12`,`openapi-3.0`];function _(e){return{"~standard":{...e[`~standard`],jsonSchema:{input(t){if(g.includes(t.target))return m(e,{typeMode:`input`,target:t.target,...t.libraryOptions});throw Error(`Unsupported target: ${t.target}`)},output(t){if(g.includes(t.target))return m(e,{typeMode:`output`,target:t.target,...t.libraryOptions});throw Error(`Unsupported target: ${t.target}`)}}}}}exports.addGlobalDefs=f,exports.getGlobalDefs=p,exports.toJsonSchema=m,exports.toJsonSchemaDefs=h,exports.toStandardJsonSchema=_; \ No newline at end of file diff --git a/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.min.mjs b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.min.mjs new file mode 100644 index 0000000000000000000000000000000000000000..aca89dc61d3bcb591bd60bdd82d7fcc10d270fdc --- /dev/null +++ b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.min.mjs @@ -0,0 +1 @@ +function e(e,t){return e?(e.push(t),e):[t]}const t=/[.*+?^${}()|[\]\\]/g;function n(e){return e.replace(t,`\\$&`)}function r(e,t){switch(t?.errorMode){case`ignore`:break;case`warn`:console.warn(e);break;default:throw Error(e)}}function i(e){return typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e)||typeof e==`string`}function a(e){return e.every(i)}function o(t,o,s){if(s?.ignoreActions?.includes(o.type))return t;let c;switch(o.type){case`base64`:t.contentEncoding=`base64`;break;case`bic`:case`cuid2`:case`decimal`:case`digits`:case`domain`:case`emoji`:case`hash`:case`hexadecimal`:case`hex_color`:case`isrc`:case`iso_time_second`:case`iso_week`:case`mac`:case`mac48`:case`mac64`:case`nanoid`:case`octal`:case`slug`:case`ulid`:t.pattern?c=e(c,`The "${o.type}" action is not supported in combination with another regex action.`):t.pattern=o.requirement.source;break;case`description`:t.description=o.description;break;case`email`:case`rfc_email`:t.format=`email`;break;case`ends_with`:t.pattern?c=e(c,`The "${o.type}" action is not supported in combination with another regex action.`):t.pattern=`${n(o.requirement)}$`;break;case`empty`:t.type===`array`?t.maxItems=0:(t.type!==`string`&&(c=e(c,`The "${o.type}" action is not supported on type "${t.type}".`)),t.maxLength=0);break;case`entries`:t.minProperties=o.requirement,t.maxProperties=o.requirement;break;case`examples`:Array.isArray(t.examples)?t.examples=[...t.examples,...o.examples]:t.examples=o.examples;break;case`gt_value`:if(t.type!==`number`&&t.type!==`integer`&&(c=e(c,`The "gt_value" action is not supported on type "${t.type}".`)),s?.target===`openapi-3.0`){c=e(c,`The "gt_value" action is not supported for OpenAPI 3.0.`);break}t.exclusiveMinimum=o.requirement;break;case`includes`:t.pattern?c=e(c,`The "${o.type}" action is not supported in combination with another regex action.`):t.pattern=n(o.requirement);break;case`integer`:t.type=`integer`;break;case`ipv4`:t.format=`ipv4`;break;case`ipv6`:t.format=`ipv6`;break;case`iso_date`:t.format=`date`;break;case`iso_date_time`:case`iso_timestamp`:t.format=`date-time`;break;case`iso_time`:t.format=`time`;break;case`jws_compact`:t.pattern?c=e(c,`The "${o.type}" action is not supported in combination with another regex action.`):t.pattern=o.requirement.source;break;case`length`:t.type===`array`?(t.minItems=o.requirement,t.maxItems=o.requirement):(t.type!==`string`&&(c=e(c,`The "${o.type}" action is not supported on type "${t.type}".`)),t.minLength=o.requirement,t.maxLength=o.requirement);break;case`lt_value`:if(t.type!==`number`&&t.type!==`integer`&&(c=e(c,`The "lt_value" action is not supported on type "${t.type}".`)),s?.target===`openapi-3.0`){c=e(c,`The "lt_value" action is not supported for OpenAPI 3.0.`);break}t.exclusiveMaximum=o.requirement;break;case`max_entries`:t.maxProperties=o.requirement;break;case`max_length`:t.type===`array`?t.maxItems=o.requirement:(t.type!==`string`&&(c=e(c,`The "${o.type}" action is not supported on type "${t.type}".`)),t.maxLength=o.requirement);break;case`max_value`:t.type!==`number`&&t.type!==`integer`&&(c=e(c,`The "max_value" action is not supported on type "${t.type}".`)),t.maximum=o.requirement;break;case`metadata`:typeof o.metadata.title==`string`&&(t.title=o.metadata.title),typeof o.metadata.description==`string`&&(t.description=o.metadata.description),Array.isArray(o.metadata.examples)&&(Array.isArray(t.examples)?t.examples=[...t.examples,...o.metadata.examples]:t.examples=o.metadata.examples);break;case`min_entries`:t.minProperties=o.requirement;break;case`min_length`:t.type===`array`?t.minItems=o.requirement:(t.type!==`string`&&(c=e(c,`The "${o.type}" action is not supported on type "${t.type}".`)),t.minLength=o.requirement);break;case`min_value`:t.type!==`number`&&t.type!==`integer`&&(c=e(c,`The "min_value" action is not supported on type "${t.type}".`)),t.minimum=o.requirement;break;case`multiple_of`:t.multipleOf=o.requirement;break;case`non_empty`:t.type===`array`?t.minItems=1:(t.type!==`string`&&(c=e(c,`The "${o.type}" action is not supported on type "${t.type}".`)),t.minLength=1);break;case`not_value`:if(!i(o.requirement)){c=e(c,`The requirement of the "not_value" action is not JSON compatible.`);break}s?.target===`openapi-3.0`?t.not={enum:[o.requirement]}:t.not={const:o.requirement};break;case`not_values`:if(!a(o.requirement)){c=e(c,`A requirement of the "not_values" action is not JSON compatible.`);break}t.not={enum:o.requirement};break;case`regex`:o.requirement.flags&&(c=e(c,`RegExp flags are not supported by JSON Schema.`)),t.pattern?c=e(c,`The "${o.type}" action is not supported in combination with another regex action.`):t.pattern=o.requirement.source;break;case`safe_integer`:t.type=`integer`,(typeof t.minimum!=`number`||t.minimum<-(2**53-1))&&(t.minimum=-(2**53-1)),(typeof t.maximum!=`number`||t.maximum>2**53-1)&&(t.maximum=2**53-1);break;case`starts_with`:t.pattern?c=e(c,`The "${o.type}" action is not supported in combination with another regex action.`):t.pattern=`^${n(o.requirement)}`;break;case`title`:t.title=o.title;break;case`url`:t.format=`uri`;break;case`uuid`:t.format=`uuid`;break;case`value`:if(!i(o.requirement)){c=e(c,`The requirement of the "value" action is not JSON compatible.`);break}s?.target===`openapi-3.0`?t.enum=[o.requirement]:t.const=o.requirement;break;case`values`:if(!a(o.requirement)){c=e(c,`A requirement of the "values" action is not JSON compatible.`);break}t.enum=o.requirement;break;default:c=e(c,`The "${o.type}" action cannot be converted to JSON Schema.`)}if(s?.overrideAction){let e=s.overrideAction({valibotAction:o,jsonSchema:t,errors:c});if(e)return{...e}}if(c)for(let e of c)r(e,s);return t}function s(e){return e.flatMap(e=>`pipe`in e?s(e.pipe):e)}function c(e){return`#/$defs/${e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}`}let l=0;function u(t,n,i,a,d=!1){if(!d){let e=a.referenceMap.get(n);if(e){if(t.$ref=c(e),i?.overrideRef){let r=i.overrideRef({...a,referenceId:e,valibotSchema:n,jsonSchema:t});r&&(t.$ref=r)}return t}}if(`pipe`in n){let e=s(n.pipe),c=0,l=e.length-1;if(i?.typeMode===`input`){let t=e.slice(1).findIndex(e=>e.kind===`schema`||e.kind===`transformation`&&(e.type===`find_item`||e.type===`parse_json`||e.type===`raw_transform`||e.type===`reduce_items`||e.type===`stringify_json`||e.type===`to_bigint`||e.type===`to_boolean`||e.type===`to_date`||e.type===`to_number`||e.type===`to_string`||e.type===`transform`));t!==-1&&(l=t)}else if(i?.typeMode===`output`){let t=e.findLastIndex(e=>e.kind===`schema`);t!==-1&&(c=t)}for(let n=c;n<=l;n++){let s=e[n];s.kind===`schema`?(n>c&&r(`Set the "typeMode" config to "input" or "output" to convert pipelines with multiple schemas.`,i),t=u(t,s,i,a,!0)):t=o(t,s,i)}return t}let f;switch(n.type){case`boolean`:t.type=`boolean`;break;case`null`:i?.target===`openapi-3.0`?t.enum=[null]:t.type=`null`;break;case`number`:t.type=`number`;break;case`string`:t.type=`string`;break;case`array`:t.type=`array`,t.items=u({},n.item,i,a);break;case`tuple`:case`tuple_with_rest`:case`loose_tuple`:case`strict_tuple`:if(t.type=`array`,i?.target===`openapi-3.0`){t.items={anyOf:[]},t.minItems=n.items.length;for(let e of n.items)t.items.anyOf.push(u({},e,i,a));n.type===`tuple_with_rest`?t.items.anyOf.push(u({},n.rest,i,a)):(n.type===`strict_tuple`||n.type===`tuple`)&&(t.maxItems=n.items.length)}else if(i?.target===`draft-2020-12`){t.prefixItems=[],t.minItems=n.items.length;for(let e of n.items)t.prefixItems.push(u({},e,i,a));n.type===`tuple_with_rest`?t.items=u({},n.rest,i,a):n.type===`strict_tuple`&&(t.items=!1)}else{t.items=[],t.minItems=n.items.length;for(let e of n.items)t.items.push(u({},e,i,a));n.type===`tuple_with_rest`?t.additionalItems=u({},n.rest,i,a):n.type===`strict_tuple`&&(t.additionalItems=!1)}break;case`object`:case`object_with_rest`:case`loose_object`:case`strict_object`:for(let e in t.type=`object`,t.properties={},t.required=[],n.entries){let r=n.entries[e];t.properties[e]=u({},r,i,a),r.type!==`exact_optional`&&r.type!==`nullish`&&r.type!==`optional`&&t.required.push(e)}n.type===`object_with_rest`?t.additionalProperties=u({},n.rest,i,a):n.type===`strict_object`&&(t.additionalProperties=!1);break;case`record`:i?.target===`openapi-3.0`&&`pipe`in n.key&&(f=e(f,`The "record" schema with a schema for the key that contains a "pipe" cannot be converted to JSON Schema.`)),n.key.type!==`string`&&(f=e(f,`The "record" schema with the "${n.key.type}" schema for the key cannot be converted to JSON Schema.`)),t.type=`object`,i?.target!==`openapi-3.0`&&(t.propertyNames=u({},n.key,i,a)),t.additionalProperties=u({},n.value,i,a);break;case`any`:case`unknown`:break;case`never`:t.not={};break;case`nullable`:case`nullish`:if(i?.target===`openapi-3.0`){let e=u({},n.wrapped,i,a);Object.assign(t,e),t.nullable=!0}else t.anyOf=[u({},n.wrapped,i,a),{type:`null`}];n.default!==void 0&&(t.default=typeof n.default==`function`?n.default():n.default);break;case`exact_optional`:case`optional`:case`undefinedable`:t=u(t,n.wrapped,i,a),n.default!==void 0&&(t.default=typeof n.default==`function`?n.default():n.default);break;case`literal`:typeof n.literal!=`boolean`&&typeof n.literal!=`number`&&typeof n.literal!=`string`&&(f=e(f,`The value of the "literal" schema is not JSON compatible.`)),i?.target===`openapi-3.0`?t.enum=[n.literal]:t.const=n.literal;break;case`enum`:t.enum=n.options,n.options.every(e=>typeof e==`string`)?t.type=`string`:n.options.every(e=>typeof e==`number`)?t.type=`number`:i?.target!==`openapi-3.0`&&(t.type=[`string`,`number`]);break;case`picklist`:{let r=n.options.some(e=>typeof e!=`number`&&typeof e!=`string`);r&&(f=e(f,`An option of the "picklist" schema is not JSON compatible.`)),t.enum=n.options,n.options.every(e=>typeof e==`string`)?t.type=`string`:n.options.every(e=>typeof e==`number`)?t.type=`number`:!r&&i?.target!==`openapi-3.0`&&(t.type=[`string`,`number`]);break}case`union`:t.anyOf=n.options.map(e=>u({},e,i,a));break;case`variant`:t.oneOf=n.options.map(e=>u({},e,i,a));break;case`intersect`:t.allOf=n.options.map(e=>u({},e,i,a));break;case`lazy`:{let e=a.getterMap.get(n.getter);e||(e=n.getter(void 0),a.getterMap.set(n.getter,e));let r=a.referenceMap.get(e);if(r||(r=`${l++}`,a.referenceMap.set(e,r),a.definitions[r]=u({},e,i,a,!0)),t.$ref=c(r),i?.overrideRef){let n=i.overrideRef({...a,referenceId:r,valibotSchema:e,jsonSchema:t});n&&(t.$ref=n)}break}default:f=e(f,`The "${n.type}" schema cannot be converted to JSON Schema.`)}if(i?.overrideSchema){let e=i.overrideSchema({...a,referenceId:a.referenceMap.get(n),valibotSchema:n,jsonSchema:t,errors:f});if(e)return{...e}}if(f)for(let e of f)r(e,i);return t}let d;function f(e){d={...d??{},...e}}function p(){return d}function m(e,t){let n={definitions:{},referenceMap:new Map,getterMap:new Map},r=t?.definitions??p();if(r){for(let e in r)n.referenceMap.set(r[e],e);for(let e in r)n.definitions[e]=u({},r[e],t,n,!0)}let i=u({},e,t,n),a=t?.target??`draft-07`;return a===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:a===`draft-07`&&(i.$schema=`http://json-schema.org/draft-07/schema#`),n.referenceMap.size&&(i.$defs=n.definitions),i}function h(e,t){let n={definitions:{},referenceMap:new Map,getterMap:new Map};for(let t in e)n.referenceMap.set(e[t],t);for(let r in e)n.definitions[r]=u({},e[r],t,n,!0);return n.definitions}const g=[`draft-07`,`draft-2020-12`,`openapi-3.0`];function _(e){return{"~standard":{...e[`~standard`],jsonSchema:{input(t){if(g.includes(t.target))return m(e,{typeMode:`input`,target:t.target,...t.libraryOptions});throw Error(`Unsupported target: ${t.target}`)},output(t){if(g.includes(t.target))return m(e,{typeMode:`output`,target:t.target,...t.libraryOptions});throw Error(`Unsupported target: ${t.target}`)}}}}}export{f as addGlobalDefs,p as getGlobalDefs,m as toJsonSchema,h as toJsonSchemaDefs,_ as toStandardJsonSchema}; \ No newline at end of file diff --git a/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.mjs b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3689bc3100c67196586dff025cf27101a84125f3 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/dist/index.mjs @@ -0,0 +1,648 @@ +//#region src/utils/addError.ts +/** +* Adds an error message to the errors array. +* +* @param errors The array of error messages. +* @param message The error message to add. +* +* @returns The new errors. +*/ +function addError(errors, message) { + if (errors) { + errors.push(message); + return errors; + } + return [message]; +} + +//#endregion +//#region src/utils/escapeRegExp.ts +const ESCAPE_REGEX = /[.*+?^${}()|[\]\\]/g; +/** +* Escapes special regex characters in a string. +* +* @param string The string to escape. +* +* @returns The escaped string. +*/ +function escapeRegExp(string) { + return string.replace(ESCAPE_REGEX, "\\$&"); +} + +//#endregion +//#region src/utils/handleError.ts +/** +* Throws an error or logs a warning based on the configuration. +* +* @param message The message to throw or log. +* @param config The conversion configuration. +*/ +function handleError(message, config) { + switch (config?.errorMode) { + case "ignore": break; + case "warn": + console.warn(message); + break; + default: throw new Error(message); + } +} + +//#endregion +//#region src/utils/isJsonConstValue.ts +/** +* Whether a value is JSON compatible for a const keyword. +* +* @param value The value to check. +* +* @returns Whether the value is JSON compatible. +*/ +function isJsonConstValue(value) { + return typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) || typeof value === "string"; +} + +//#endregion +//#region src/utils/isJsonEnumValues.ts +/** +* Whether values are JSON compatible for an enum keyword. +* +* @param values The values to check. +* +* @returns Whether the values are JSON compatible. +*/ +function isJsonEnumValues(values) { + return values.every(isJsonConstValue); +} + +//#endregion +//#region src/converters/convertAction/convertAction.ts +/** +* Converts any supported Valibot action to the JSON Schema format. +* +* @param jsonSchema The JSON Schema object. +* @param valibotAction The Valibot action object. +* @param config The conversion configuration. +* +* @returns The converted JSON Schema. +*/ +function convertAction(jsonSchema, valibotAction, config) { + if (config?.ignoreActions?.includes(valibotAction.type)) return jsonSchema; + let errors; + switch (valibotAction.type) { + case "base64": + jsonSchema.contentEncoding = "base64"; + break; + case "bic": + case "cuid2": + case "decimal": + case "digits": + case "domain": + case "emoji": + case "hash": + case "hexadecimal": + case "hex_color": + case "isrc": + case "iso_time_second": + case "iso_week": + case "mac": + case "mac48": + case "mac64": + case "nanoid": + case "octal": + case "slug": + case "ulid": + if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`); + else jsonSchema.pattern = valibotAction.requirement.source; + break; + case "description": + jsonSchema.description = valibotAction.description; + break; + case "email": + case "rfc_email": + jsonSchema.format = "email"; + break; + case "ends_with": + if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`); + else jsonSchema.pattern = `${escapeRegExp(valibotAction.requirement)}$`; + break; + case "empty": + if (jsonSchema.type === "array") jsonSchema.maxItems = 0; + else { + if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`); + jsonSchema.maxLength = 0; + } + break; + case "entries": + jsonSchema.minProperties = valibotAction.requirement; + jsonSchema.maxProperties = valibotAction.requirement; + break; + case "examples": + if (Array.isArray(jsonSchema.examples)) jsonSchema.examples = [...jsonSchema.examples, ...valibotAction.examples]; + else jsonSchema.examples = valibotAction.examples; + break; + case "gt_value": + if (jsonSchema.type !== "number" && jsonSchema.type !== "integer") errors = addError(errors, `The "gt_value" action is not supported on type "${jsonSchema.type}".`); + if (config?.target === "openapi-3.0") { + errors = addError(errors, "The \"gt_value\" action is not supported for OpenAPI 3.0."); + break; + } + jsonSchema.exclusiveMinimum = valibotAction.requirement; + break; + case "includes": + if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`); + else jsonSchema.pattern = escapeRegExp(valibotAction.requirement); + break; + case "integer": + jsonSchema.type = "integer"; + break; + case "ipv4": + jsonSchema.format = "ipv4"; + break; + case "ipv6": + jsonSchema.format = "ipv6"; + break; + case "iso_date": + jsonSchema.format = "date"; + break; + case "iso_date_time": + case "iso_timestamp": + jsonSchema.format = "date-time"; + break; + case "iso_time": + jsonSchema.format = "time"; + break; + case "jws_compact": + if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`); + else jsonSchema.pattern = valibotAction.requirement.source; + break; + case "length": + if (jsonSchema.type === "array") { + jsonSchema.minItems = valibotAction.requirement; + jsonSchema.maxItems = valibotAction.requirement; + } else { + if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`); + jsonSchema.minLength = valibotAction.requirement; + jsonSchema.maxLength = valibotAction.requirement; + } + break; + case "lt_value": + if (jsonSchema.type !== "number" && jsonSchema.type !== "integer") errors = addError(errors, `The "lt_value" action is not supported on type "${jsonSchema.type}".`); + if (config?.target === "openapi-3.0") { + errors = addError(errors, "The \"lt_value\" action is not supported for OpenAPI 3.0."); + break; + } + jsonSchema.exclusiveMaximum = valibotAction.requirement; + break; + case "max_entries": + jsonSchema.maxProperties = valibotAction.requirement; + break; + case "max_length": + if (jsonSchema.type === "array") jsonSchema.maxItems = valibotAction.requirement; + else { + if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`); + jsonSchema.maxLength = valibotAction.requirement; + } + break; + case "max_value": + if (jsonSchema.type !== "number" && jsonSchema.type !== "integer") errors = addError(errors, `The "max_value" action is not supported on type "${jsonSchema.type}".`); + jsonSchema.maximum = valibotAction.requirement; + break; + case "metadata": + if (typeof valibotAction.metadata.title === "string") jsonSchema.title = valibotAction.metadata.title; + if (typeof valibotAction.metadata.description === "string") jsonSchema.description = valibotAction.metadata.description; + if (Array.isArray(valibotAction.metadata.examples)) if (Array.isArray(jsonSchema.examples)) jsonSchema.examples = [...jsonSchema.examples, ...valibotAction.metadata.examples]; + else jsonSchema.examples = valibotAction.metadata.examples; + break; + case "min_entries": + jsonSchema.minProperties = valibotAction.requirement; + break; + case "min_length": + if (jsonSchema.type === "array") jsonSchema.minItems = valibotAction.requirement; + else { + if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`); + jsonSchema.minLength = valibotAction.requirement; + } + break; + case "min_value": + if (jsonSchema.type !== "number" && jsonSchema.type !== "integer") errors = addError(errors, `The "min_value" action is not supported on type "${jsonSchema.type}".`); + jsonSchema.minimum = valibotAction.requirement; + break; + case "multiple_of": + jsonSchema.multipleOf = valibotAction.requirement; + break; + case "non_empty": + if (jsonSchema.type === "array") jsonSchema.minItems = 1; + else { + if (jsonSchema.type !== "string") errors = addError(errors, `The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`); + jsonSchema.minLength = 1; + } + break; + case "not_value": + if (!isJsonConstValue(valibotAction.requirement)) { + errors = addError(errors, "The requirement of the \"not_value\" action is not JSON compatible."); + break; + } + if (config?.target === "openapi-3.0") jsonSchema.not = { enum: [valibotAction.requirement] }; + else jsonSchema.not = { const: valibotAction.requirement }; + break; + case "not_values": + if (!isJsonEnumValues(valibotAction.requirement)) { + errors = addError(errors, "A requirement of the \"not_values\" action is not JSON compatible."); + break; + } + jsonSchema.not = { enum: valibotAction.requirement }; + break; + case "regex": + if (valibotAction.requirement.flags) errors = addError(errors, "RegExp flags are not supported by JSON Schema."); + if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`); + else jsonSchema.pattern = valibotAction.requirement.source; + break; + case "safe_integer": + jsonSchema.type = "integer"; + if (typeof jsonSchema.minimum !== "number" || jsonSchema.minimum < Number.MIN_SAFE_INTEGER) jsonSchema.minimum = Number.MIN_SAFE_INTEGER; + if (typeof jsonSchema.maximum !== "number" || jsonSchema.maximum > Number.MAX_SAFE_INTEGER) jsonSchema.maximum = Number.MAX_SAFE_INTEGER; + break; + case "starts_with": + if (jsonSchema.pattern) errors = addError(errors, `The "${valibotAction.type}" action is not supported in combination with another regex action.`); + else jsonSchema.pattern = `^${escapeRegExp(valibotAction.requirement)}`; + break; + case "title": + jsonSchema.title = valibotAction.title; + break; + case "url": + jsonSchema.format = "uri"; + break; + case "uuid": + jsonSchema.format = "uuid"; + break; + case "value": + if (!isJsonConstValue(valibotAction.requirement)) { + errors = addError(errors, "The requirement of the \"value\" action is not JSON compatible."); + break; + } + if (config?.target === "openapi-3.0") jsonSchema.enum = [valibotAction.requirement]; + else jsonSchema.const = valibotAction.requirement; + break; + case "values": + if (!isJsonEnumValues(valibotAction.requirement)) { + errors = addError(errors, "A requirement of the \"values\" action is not JSON compatible."); + break; + } + jsonSchema.enum = valibotAction.requirement; + break; + default: errors = addError(errors, `The "${valibotAction.type}" action cannot be converted to JSON Schema.`); + } + if (config?.overrideAction) { + const actionOverride = config.overrideAction({ + valibotAction, + jsonSchema, + errors + }); + if (actionOverride) return { ...actionOverride }; + } + if (errors) for (const message of errors) handleError(message, config); + return jsonSchema; +} + +//#endregion +//#region src/converters/convertSchema/convertSchema.ts +/** +* Flattens a Valibot pipe by recursively expanding nested pipes. +* +* @param pipe The pipeline to flatten. +* +* @returns A flat pipeline. +*/ +function flattenPipe(pipe) { + return pipe.flatMap((item) => "pipe" in item ? flattenPipe(item.pipe) : item); +} +/** +* Returns the JSON Pointer reference for a definition key. +* +* @param referenceId The unescaped definition key. +* +* @returns The encoded JSON Pointer fragment. +*/ +function getDefinitionRef(referenceId) { + return `#/$defs/${referenceId.replaceAll("~", "~0").replaceAll("/", "~1")}`; +} +let refCount = 0; +/** +* Converts any supported Valibot schema to the JSON Schema format. +* +* @param jsonSchema The JSON Schema object. +* @param valibotSchema The Valibot schema object. +* @param config The conversion configuration. +* @param context The conversion context. +* @param skipRef Whether to skip using a reference. +* +* @returns The converted JSON Schema. +*/ +function convertSchema(jsonSchema, valibotSchema, config, context, skipRef = false) { + if (!skipRef) { + const referenceId = context.referenceMap.get(valibotSchema); + if (referenceId) { + jsonSchema.$ref = getDefinitionRef(referenceId); + if (config?.overrideRef) { + const refOverride = config.overrideRef({ + ...context, + referenceId, + valibotSchema, + jsonSchema + }); + if (refOverride) jsonSchema.$ref = refOverride; + } + return jsonSchema; + } + } + if ("pipe" in valibotSchema) { + const flatPipe = flattenPipe(valibotSchema.pipe); + let startIndex = 0; + let stopIndex = flatPipe.length - 1; + if (config?.typeMode === "input") { + const inputStopIndex = flatPipe.slice(1).findIndex((item) => item.kind === "schema" || item.kind === "transformation" && (item.type === "find_item" || item.type === "parse_json" || item.type === "raw_transform" || item.type === "reduce_items" || item.type === "stringify_json" || item.type === "to_bigint" || item.type === "to_boolean" || item.type === "to_date" || item.type === "to_number" || item.type === "to_string" || item.type === "transform")); + if (inputStopIndex !== -1) stopIndex = inputStopIndex; + } else if (config?.typeMode === "output") { + const outputStartIndex = flatPipe.findLastIndex((item) => item.kind === "schema"); + if (outputStartIndex !== -1) startIndex = outputStartIndex; + } + for (let index = startIndex; index <= stopIndex; index++) { + const valibotPipeItem = flatPipe[index]; + if (valibotPipeItem.kind === "schema") { + if (index > startIndex) handleError("Set the \"typeMode\" config to \"input\" or \"output\" to convert pipelines with multiple schemas.", config); + jsonSchema = convertSchema(jsonSchema, valibotPipeItem, config, context, true); + } else jsonSchema = convertAction(jsonSchema, valibotPipeItem, config); + } + return jsonSchema; + } + let errors; + switch (valibotSchema.type) { + case "boolean": + jsonSchema.type = "boolean"; + break; + case "null": + if (config?.target === "openapi-3.0") jsonSchema.enum = [null]; + else jsonSchema.type = "null"; + break; + case "number": + jsonSchema.type = "number"; + break; + case "string": + jsonSchema.type = "string"; + break; + case "array": + jsonSchema.type = "array"; + jsonSchema.items = convertSchema({}, valibotSchema.item, config, context); + break; + case "tuple": + case "tuple_with_rest": + case "loose_tuple": + case "strict_tuple": + jsonSchema.type = "array"; + if (config?.target === "openapi-3.0") { + jsonSchema.items = { anyOf: [] }; + jsonSchema.minItems = valibotSchema.items.length; + for (const item of valibotSchema.items) jsonSchema.items.anyOf.push(convertSchema({}, item, config, context)); + if (valibotSchema.type === "tuple_with_rest") jsonSchema.items.anyOf.push(convertSchema({}, valibotSchema.rest, config, context)); + else if (valibotSchema.type === "strict_tuple" || valibotSchema.type === "tuple") jsonSchema.maxItems = valibotSchema.items.length; + } else if (config?.target === "draft-2020-12") { + jsonSchema.prefixItems = []; + jsonSchema.minItems = valibotSchema.items.length; + for (const item of valibotSchema.items) jsonSchema.prefixItems.push(convertSchema({}, item, config, context)); + if (valibotSchema.type === "tuple_with_rest") jsonSchema.items = convertSchema({}, valibotSchema.rest, config, context); + else if (valibotSchema.type === "strict_tuple") jsonSchema.items = false; + } else { + jsonSchema.items = []; + jsonSchema.minItems = valibotSchema.items.length; + for (const item of valibotSchema.items) jsonSchema.items.push(convertSchema({}, item, config, context)); + if (valibotSchema.type === "tuple_with_rest") jsonSchema.additionalItems = convertSchema({}, valibotSchema.rest, config, context); + else if (valibotSchema.type === "strict_tuple") jsonSchema.additionalItems = false; + } + break; + case "object": + case "object_with_rest": + case "loose_object": + case "strict_object": + jsonSchema.type = "object"; + jsonSchema.properties = {}; + jsonSchema.required = []; + for (const key in valibotSchema.entries) { + const entry = valibotSchema.entries[key]; + jsonSchema.properties[key] = convertSchema({}, entry, config, context); + if (entry.type !== "exact_optional" && entry.type !== "nullish" && entry.type !== "optional") jsonSchema.required.push(key); + } + if (valibotSchema.type === "object_with_rest") jsonSchema.additionalProperties = convertSchema({}, valibotSchema.rest, config, context); + else if (valibotSchema.type === "strict_object") jsonSchema.additionalProperties = false; + break; + case "record": + if (config?.target === "openapi-3.0" && "pipe" in valibotSchema.key) errors = addError(errors, "The \"record\" schema with a schema for the key that contains a \"pipe\" cannot be converted to JSON Schema."); + if (valibotSchema.key.type !== "string") errors = addError(errors, `The "record" schema with the "${valibotSchema.key.type}" schema for the key cannot be converted to JSON Schema.`); + jsonSchema.type = "object"; + if (config?.target !== "openapi-3.0") jsonSchema.propertyNames = convertSchema({}, valibotSchema.key, config, context); + jsonSchema.additionalProperties = convertSchema({}, valibotSchema.value, config, context); + break; + case "any": + case "unknown": break; + case "never": + jsonSchema.not = {}; + break; + case "nullable": + case "nullish": + if (config?.target === "openapi-3.0") { + const innerSchema = convertSchema({}, valibotSchema.wrapped, config, context); + Object.assign(jsonSchema, innerSchema); + jsonSchema.nullable = true; + } else jsonSchema.anyOf = [convertSchema({}, valibotSchema.wrapped, config, context), { type: "null" }]; + if (valibotSchema.default !== void 0) jsonSchema.default = typeof valibotSchema.default === "function" ? valibotSchema.default() : valibotSchema.default; + break; + case "exact_optional": + case "optional": + case "undefinedable": + jsonSchema = convertSchema(jsonSchema, valibotSchema.wrapped, config, context); + if (valibotSchema.default !== void 0) jsonSchema.default = typeof valibotSchema.default === "function" ? valibotSchema.default() : valibotSchema.default; + break; + case "literal": + if (typeof valibotSchema.literal !== "boolean" && typeof valibotSchema.literal !== "number" && typeof valibotSchema.literal !== "string") errors = addError(errors, "The value of the \"literal\" schema is not JSON compatible."); + if (config?.target === "openapi-3.0") jsonSchema.enum = [valibotSchema.literal]; + else jsonSchema.const = valibotSchema.literal; + break; + case "enum": + jsonSchema.enum = valibotSchema.options; + if (valibotSchema.options.every((option) => typeof option === "string")) jsonSchema.type = "string"; + else if (valibotSchema.options.every((option) => typeof option === "number")) jsonSchema.type = "number"; + else if (config?.target !== "openapi-3.0") jsonSchema.type = ["string", "number"]; + break; + case "picklist": { + const hasInvalidOption = valibotSchema.options.some((option) => typeof option !== "number" && typeof option !== "string"); + if (hasInvalidOption) errors = addError(errors, "An option of the \"picklist\" schema is not JSON compatible."); + jsonSchema.enum = valibotSchema.options; + if (valibotSchema.options.every((option) => typeof option === "string")) jsonSchema.type = "string"; + else if (valibotSchema.options.every((option) => typeof option === "number")) jsonSchema.type = "number"; + else if (!hasInvalidOption && config?.target !== "openapi-3.0") jsonSchema.type = ["string", "number"]; + break; + } + case "union": + jsonSchema.anyOf = valibotSchema.options.map((option) => convertSchema({}, option, config, context)); + break; + case "variant": + jsonSchema.oneOf = valibotSchema.options.map((option) => convertSchema({}, option, config, context)); + break; + case "intersect": + jsonSchema.allOf = valibotSchema.options.map((option) => convertSchema({}, option, config, context)); + break; + case "lazy": { + let wrappedValibotSchema = context.getterMap.get(valibotSchema.getter); + if (!wrappedValibotSchema) { + wrappedValibotSchema = valibotSchema.getter(void 0); + context.getterMap.set(valibotSchema.getter, wrappedValibotSchema); + } + let referenceId = context.referenceMap.get(wrappedValibotSchema); + if (!referenceId) { + referenceId = `${refCount++}`; + context.referenceMap.set(wrappedValibotSchema, referenceId); + context.definitions[referenceId] = convertSchema({}, wrappedValibotSchema, config, context, true); + } + jsonSchema.$ref = getDefinitionRef(referenceId); + if (config?.overrideRef) { + const refOverride = config.overrideRef({ + ...context, + referenceId, + valibotSchema: wrappedValibotSchema, + jsonSchema + }); + if (refOverride) jsonSchema.$ref = refOverride; + } + break; + } + default: errors = addError(errors, `The "${valibotSchema.type}" schema cannot be converted to JSON Schema.`); + } + if (config?.overrideSchema) { + const schemaOverride = config.overrideSchema({ + ...context, + referenceId: context.referenceMap.get(valibotSchema), + valibotSchema, + jsonSchema, + errors + }); + if (schemaOverride) return { ...schemaOverride }; + } + if (errors) for (const message of errors) handleError(message, config); + return jsonSchema; +} + +//#endregion +//#region src/storages/globalDefs/globalDefs.ts +let store; +/** +* Adds new definitions to the global schema definitions. +* +* @param definitions The schema definitions. +* +* @beta +*/ +function addGlobalDefs(definitions) { + store = { + ...store ?? {}, + ...definitions + }; +} +/** +* Returns the current global schema definitions. +* +* @returns The schema definitions. +* +* @beta +*/ +function getGlobalDefs() { + return store; +} + +//#endregion +//#region src/functions/toJsonSchema/toJsonSchema.ts +/** +* Converts a Valibot schema to the JSON Schema format. +* +* @param schema The Valibot schema object. +* @param config The JSON Schema configuration. +* +* @returns The converted JSON Schema. +*/ +function toJsonSchema(schema, config) { + const context = { + definitions: {}, + referenceMap: /* @__PURE__ */ new Map(), + getterMap: /* @__PURE__ */ new Map() + }; + const definitions = config?.definitions ?? getGlobalDefs(); + if (definitions) { + for (const key in definitions) context.referenceMap.set(definitions[key], key); + for (const key in definitions) context.definitions[key] = convertSchema({}, definitions[key], config, context, true); + } + const jsonSchema = convertSchema({}, schema, config, context); + const target = config?.target ?? "draft-07"; + if (target === "draft-2020-12") jsonSchema.$schema = "https://json-schema.org/draft/2020-12/schema"; + else if (target === "draft-07") jsonSchema.$schema = "http://json-schema.org/draft-07/schema#"; + if (context.referenceMap.size) jsonSchema.$defs = context.definitions; + return jsonSchema; +} + +//#endregion +//#region src/functions/toJsonSchemaDefs/toJsonSchemaDefs.ts +/** +* Converts Valibot schema definitions to JSON Schema definitions. +* +* @param definitions The Valibot schema definitions. +* @param config The JSON Schema configuration. +* +* @returns The converted JSON Schema definitions. +*/ +function toJsonSchemaDefs(definitions, config) { + const context = { + definitions: {}, + referenceMap: /* @__PURE__ */ new Map(), + getterMap: /* @__PURE__ */ new Map() + }; + for (const key in definitions) context.referenceMap.set(definitions[key], key); + for (const key in definitions) context.definitions[key] = convertSchema({}, definitions[key], config, context, true); + return context.definitions; +} + +//#endregion +//#region src/functions/toStandardJsonSchema/toStandardJsonSchema.ts +const SUPPORTED_TARGETS = [ + "draft-07", + "draft-2020-12", + "openapi-3.0" +]; +/** +* Converts a Valibot schema to the Standard JSON Schema format. +* +* @param schema The Valibot schema object. +* +* @returns The Standard JSON Schema. +*/ +function toStandardJsonSchema(schema) { + return { "~standard": { + ...schema["~standard"], + jsonSchema: { + input(options) { + if (SUPPORTED_TARGETS.includes(options.target)) return toJsonSchema(schema, { + typeMode: "input", + target: options.target, + ...options.libraryOptions + }); + throw new Error(`Unsupported target: ${options.target}`); + }, + output(options) { + if (SUPPORTED_TARGETS.includes(options.target)) return toJsonSchema(schema, { + typeMode: "output", + target: options.target, + ...options.libraryOptions + }); + throw new Error(`Unsupported target: ${options.target}`); + } + } + } }; +} + +//#endregion +export { addGlobalDefs, getGlobalDefs, toJsonSchema, toJsonSchemaDefs, toStandardJsonSchema }; \ No newline at end of file diff --git a/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/package.json b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9dfa5c3e5479ab808226b3a4fbfc03783dd353ab --- /dev/null +++ b/tools/ui/node_modules/@tmcp/adapter-valibot/node_modules/@valibot/to-json-schema/package.json @@ -0,0 +1,75 @@ +{ + "name": "@valibot/to-json-schema", + "description": "The official JSON schema converter for Valibot", + "version": "1.7.1", + "license": "MIT", + "author": "Fabian Hiller", + "homepage": "https://valibot.dev", + "contributors": [ + { + "name": "Guillaume Cornut" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/open-circle/valibot" + }, + "keywords": [ + "valibot", + "schema", + "converter", + "json-schema" + ], + "type": "module", + "main": "./dist/index.mjs", + "types": "./dist/index.d.mts", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + } + }, + "sideEffects": false, + "files": [ + "dist" + ], + "publishConfig": { + "access": "public" + }, + "scripts": { + "test": "vitest --typecheck", + "coverage": "vitest run --coverage --isolate", + "lint": "eslint \"src/**/*.ts*\" && tsc --noEmit && deno check ./src/index.ts", + "lint.fix": "eslint \"src/**/*.ts*\" --fix", + "format": "prettier --write ./src", + "format.check": "prettier --check ./src", + "build": "tsdown" + }, + "devDependencies": { + "@eslint/js": "^9.39.1", + "@types/node": "^24.10.1", + "@vitest/coverage-v8": "^4.1.8", + "eslint": "^9.39.1", + "eslint-import-resolver-typescript": "^4.4.4", + "eslint-plugin-import": "^2.32.0", + "eslint-plugin-jsdoc": "^61.4.0", + "eslint-plugin-security": "^3.0.1", + "globals": "^16.5.0", + "tsdown": "^0.16.6", + "typescript": "^5.9.3", + "typescript-eslint": "^8.47.0", + "valibot": "^1.4.0", + "vite": "^7.2.4", + "vite-tsconfig-paths": "^5.1.4", + "vitest": "4.1.8" + }, + "peerDependencies": { + "valibot": "^1.4.0" + } +} diff --git a/tools/ui/node_modules/@tmcp/adapter-valibot/package.json b/tools/ui/node_modules/@tmcp/adapter-valibot/package.json new file mode 100644 index 0000000000000000000000000000000000000000..86a675d49e711fd157dcdc18b856787eb4b4b472 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/adapter-valibot/package.json @@ -0,0 +1,48 @@ +{ + "name": "@tmcp/adapter-valibot", + "version": "0.1.6", + "license": "MIT", + "description": "Valibot adapter for TMCP JSON Schema conversion", + "type": "module", + "main": "src/index.js", + "types": "src/types/index.d.ts", + "exports": { + ".": { + "types": "./src/types/index.d.ts", + "default": "./src/index.js" + }, + "./package.json": "./package.json" + }, + "peerDependencies": { + "tmcp": "^1.17.0", + "valibot": "^1.1.0" + }, + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "@valibot/to-json-schema": "^1.3.0", + "valibot": "^1.1.0" + }, + "keywords": [ + "tmcp", + "valibot", + "jsonschema", + "adapter" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/paoloricciuti/tmcp.git", + "directory": "packages/adapter-valibot" + }, + "devDependencies": { + "dts-buddy": "^0.6.2", + "publint": "^0.3.12", + "tmcp": "^1.19.4" + }, + "publishConfig": { + "access": "public" + }, + "scripts": { + "generate:types": "dts-buddy && publint", + "prepublish": "pnpm generate:types" + } +} \ No newline at end of file diff --git a/tools/ui/node_modules/@tmcp/adapter-valibot/src/index.js b/tools/ui/node_modules/@tmcp/adapter-valibot/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c8449554c55aff899d580cf70c417a8da5f9dea6 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/adapter-valibot/src/index.js @@ -0,0 +1,45 @@ +/** + * @import { GenericSchema } from "valibot"; + */ + +import { JsonSchemaAdapter } from 'tmcp/adapter'; +import { toJsonSchema } from '@valibot/to-json-schema'; + +/** + * Atrocious hack to satisfy the current version of the protocol that for some reason + * requires `type: string` on enum fields despite JSON Schema spec not requiring it. + * + * TODO: Remove this once the protocol is fixed to align with JSON Schema spec. + * @param {ReturnType} json_schema + */ +function add_type_to_enums(json_schema) { + for (let key in json_schema) { + const property = json_schema[/** @type {keyof json_schema} */ (key)]; + if ( + property != null && + typeof property === 'object' && + !Array.isArray(property) + ) { + if ('enum' in property && !('type' in property)) { + property.type = 'string'; + } + add_type_to_enums(property); + } + } + return json_schema; +} + +/** + * Valibot adapter for converting Valibot schemas to JSON Schema format + * @augments {JsonSchemaAdapter} + */ +export class ValibotJsonSchemaAdapter extends JsonSchemaAdapter { + /** + * Converts a Valibot schema to JSON Schema format + * @param {GenericSchema} schema - The Valibot schema to convert + * @returns {Promise>} - The converted JSON Schema + */ + async toJsonSchema(schema) { + return add_type_to_enums(toJsonSchema(schema)); + } +} diff --git a/tools/ui/node_modules/@tmcp/adapter-valibot/src/types/index.d.ts b/tools/ui/node_modules/@tmcp/adapter-valibot/src/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4443e6842cd1553ff672f776d985c1db4537aff0 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/adapter-valibot/src/types/index.d.ts @@ -0,0 +1,22 @@ +declare module '@tmcp/adapter-valibot' { + import type { GenericSchema } from 'valibot'; + import type { JsonSchemaAdapter } from 'tmcp/adapter'; + import type { toJsonSchema } from '@valibot/to-json-schema'; + /** + * Valibot adapter for converting Valibot schemas to JSON Schema format + * + */ + export class ValibotJsonSchemaAdapter extends JsonSchemaAdapter { + constructor(); + /** + * Converts a Valibot schema to JSON Schema format + * @param schema - The Valibot schema to convert + * @returns - The converted JSON Schema + */ + toJsonSchema(schema: GenericSchema): Promise>; + } + + export {}; +} + +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/@tmcp/adapter-valibot/src/types/index.d.ts.map b/tools/ui/node_modules/@tmcp/adapter-valibot/src/types/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..f57742e4e422c8a85dce74bbde15f952e6f046ae --- /dev/null +++ b/tools/ui/node_modules/@tmcp/adapter-valibot/src/types/index.d.ts.map @@ -0,0 +1,15 @@ +{ + "version": 3, + "file": "index.d.ts", + "names": [ + "ValibotJsonSchemaAdapter" + ], + "sources": [ + "../index.js" + ], + "sourcesContent": [ + null + ], + "mappings": ";;;;;;;;cAmCaA,wBAAwBA", + "ignoreList": [] +} \ No newline at end of file diff --git a/tools/ui/node_modules/@tmcp/adapter-valibot/tsconfig.json b/tools/ui/node_modules/@tmcp/adapter-valibot/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..0f9183e95b0bdff9f1bed5919ace4e7a5b5e5249 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/adapter-valibot/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "esnext", + "module": "nodenext", + "moduleResolution": "nodenext", + "allowJs": true, + "checkJs": true, + "declaration": true, + "emitDeclarationOnly": false, + "strict": true, + "noEmit": true, + "skipLibCheck": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules"] +} diff --git a/tools/ui/node_modules/@tmcp/session-manager/CHANGELOG.md b/tools/ui/node_modules/@tmcp/session-manager/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..5ca169f7c8657b10c2517956bfe0513eaaba8cd1 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/session-manager/CHANGELOG.md @@ -0,0 +1,49 @@ +# @tmcp/session-manager + +## 0.2.2 + +### Patch Changes + +- 77be8a1: chore: add license + +## 0.2.1 + +### Patch Changes + +- 5613d43: fix: handle `resources/unsubscribe` +- Updated dependencies [5613d43] + - tmcp@1.16.3 + +## 0.2.0 + +### Minor Changes + +- 8a04ee2: breaking: move sessions out of core into the transports and allow for persistent mcp state + + This release moves the session management out of the core package into the SSE and HTTP transport separately. + While technically a breaking change if you update both `tmcp` and your transport (`@tmcp/transport-http`, + `@tmcp/transport-sse`, or `@tmcp/transport-stdio`), you will not face a breaking change unless you were using a + session manager. + + If you were testing your `McpServer` instance manually you might need to update them to pass the `sessionInfo` + in the context parameter (only if you were reading them in the tool/resource/prompt). + + Sorry for the "breaking" but this was a necessary step to unlock persistent state. 🧡 + +### Patch Changes + +- Updated dependencies [8a04ee2] +- Updated dependencies [a9254cb] + - tmcp@1.16.0 + +## 0.1.2 + +### Patch Changes + +- c0f7d7f: fix: try catch closing controller in case it's already closed + +## 0.1.1 + +### Patch Changes + +- 957805b: fix: await session manager calls diff --git a/tools/ui/node_modules/@tmcp/session-manager/LICENSE b/tools/ui/node_modules/@tmcp/session-manager/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1e85c344f0ce6621b49293c01b4fab313bdce1c0 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/session-manager/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Paolo Ricciuti + +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. diff --git a/tools/ui/node_modules/@tmcp/session-manager/README.md b/tools/ui/node_modules/@tmcp/session-manager/README.md new file mode 100644 index 0000000000000000000000000000000000000000..12b35fe60b61df6ba59d772f66b96a3d12c405ed --- /dev/null +++ b/tools/ui/node_modules/@tmcp/session-manager/README.md @@ -0,0 +1,173 @@ +# @tmcp/session-manager + +Session management for TMCP (TypeScript Model Context Protocol) transport implementations. This package provides the base classes and in-memory implementations for both streaming session coordination and session metadata persistence. + +## Installation + +```bash +pnpm add @tmcp/session-manager +``` + +## Overview + +Session management is split into two concerns: + +- **Stream session managers** handle the storage of long-lived streaming connections (SSE/HTTP) and the fan-out of notifications back to the right session. +- **Info session managers** persist metadata that MCP transports need across requests, such as client capabilities, client info, requested log level, and resource subscriptions. + +Together they manage: + +- **Session Creation**: Establishing new client sessions with stream controllers +- **Session Deletion**: Cleaning up disconnected sessions and metadata +- **Session Queries**: Checking whether a given session is still attached +- **Message Delivery**: Sending messages to specific sessions or everyone +- **Client Metadata**: Persisting capabilities, `clientInfo`, and log level between requests +- **Resource Subscriptions**: Tracking which sessions subscribed to which URIs + +## Usage + +### In-Memory Session Managers (Default) + +The package ships with `InMemoryStreamSessionManager` and `InMemoryInfoSessionManager`. Together they are suitable for single-server deployments or tests: + +```javascript +import { + InMemoryStreamSessionManager, + InMemoryInfoSessionManager, +} from '@tmcp/session-manager'; + +const sessionManagers = { + streams: new InMemoryStreamSessionManager(), + info: new InMemoryInfoSessionManager(), +}; +``` + +### Custom Session Managers + +You can implement your own managers by extending the base classes that ship with this package. + +#### Stream session manager + +```javascript +import { StreamSessionManager } from '@tmcp/session-manager'; + +class CustomStreamSessionManager extends StreamSessionManager { + create(id, controller) { + // Persist the ReadableStream controller for later notifications + } + + delete(id) { + // Clean up the controller and any associated timers + } + + async has(id) { + // Return whether a controller for the session exists + } + + send(sessions, data) { + // Fan out the payload to the targeted sessions (or everyone if sessions is undefined) + } +} +``` + +#### Info session manager + +```javascript +import { InfoSessionManager } from '@tmcp/session-manager'; + +class CustomInfoSessionManager extends InfoSessionManager { + async getClientInfo(id) { + // Return the last clientInfo payload for the session + } + + setClientInfo(id, info) { + // Persist clientInfo for later requests + } + + async getClientCapabilities(id) { + // Retrieve cached client capabilities + } + + setClientCapabilities(id, capabilities) { + // Persist the negotiated capabilities + } + + async getLogLevel(id) { + // Return the log level requested by the client + } + + setLogLevel(id, level) { + // Store the latest log level + } + + async getSubscriptions(uri) { + // Return all session ids subscribed to the URI + } + + addSubscription(id, uri) { + // Track that the session subscribed to the URI + } + + delete(id) { + // Remove all metadata for the session (client info, capabilities, subscriptions, etc.) + } +} +``` + +## API + +### `StreamSessionManager` (Abstract Base Class) + +Responsible for creating and managing streaming controllers. + +- `create(id, controller)` – register a session and associate its stream controller +- `delete(id)` – remove the controller and clean up resources +- `has(id)` – resolve to `true` when a controller for the session exists +- `send(sessions, data)` – push a payload to selected sessions (or everyone when `sessions` is `undefined`) + +### `InfoSessionManager` (Abstract Base Class) + +Stores session metadata that needs to survive across HTTP requests or reconnects. + +- `getClientInfo(id)` / `setClientInfo(id, info)` +- `getClientCapabilities(id)` / `setClientCapabilities(id, capabilities)` +- `getLogLevel(id)` / `setLogLevel(id, level)` +- `getSubscriptions(uri)` – return all session IDs that subscribed to a resource +- `addSubscription(id, uri)` – record a new resource subscription +- `delete(id)` – remove all metadata for a session when it disconnects + +### `InMemoryStreamSessionManager` & `InMemoryInfoSessionManager` + +Concrete in-memory implementations that cover both responsibilities. Combine them when configuring a transport: + +```javascript +import { HttpTransport } from '@tmcp/transport-http'; +import { SseTransport } from '@tmcp/transport-sse'; +import { + InMemoryStreamSessionManager, + InMemoryInfoSessionManager, +} from '@tmcp/session-manager'; + +const sessionManagers = { + streams: new InMemoryStreamSessionManager(), + info: new InMemoryInfoSessionManager(), +}; + +const httpTransport = new HttpTransport(server, { + sessionManager: sessionManagers, +}); +const sseTransport = new SseTransport(server, { + sessionManager: sessionManagers, +}); +``` + +## Related Packages + +- [`@tmcp/session-manager-redis`](../session-manager-redis) - Redis-based session manager for multi-server deployments +- [`@tmcp/transport-http`](../transport-http) - HTTP transport using session managers +- [`@tmcp/transport-sse`](../transport-sse) - SSE transport using session managers +- [`tmcp`](../tmcp) - Core TMCP server implementation + +## License + +MIT diff --git a/tools/ui/node_modules/@tmcp/session-manager/package.json b/tools/ui/node_modules/@tmcp/session-manager/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bf46c7acb4416c229f8302203e8c84ad66519f68 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/session-manager/package.json @@ -0,0 +1,43 @@ +{ + "name": "@tmcp/session-manager", + "version": "0.2.2", + "license": "MIT", + "description": "", + "main": "src/index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/paoloricciuti/tmcp.git", + "directory": "packages/session-manager" + }, + "keywords": [ + "tmcp", + "http", + "transport", + "session", + "manager" + ], + "types": "./src/types/index.d.ts", + "exports": { + ".": { + "types": "./src/types/index.d.ts", + "import": "./src/index.js" + } + }, + "type": "module", + "peerDependencies": { + "tmcp": "^1.16.3" + }, + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "dts-buddy": "^0.6.2", + "publint": "^0.3.12", + "tmcp": "^1.19.4", + "@tmcp/internal-ts-helpers": "^1.0.0" + }, + "scripts": { + "generate:types": "dts-buddy && node scripts/abstractify.js && publint", + "prepublish": "pnpm generate:types" + } +} \ No newline at end of file diff --git a/tools/ui/node_modules/@tmcp/session-manager/scripts/abstractify.js b/tools/ui/node_modules/@tmcp/session-manager/scripts/abstractify.js new file mode 100644 index 0000000000000000000000000000000000000000..96b41dc3c64d38dc2f068ffd8d026e2a9f986870 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/session-manager/scripts/abstractify.js @@ -0,0 +1,3 @@ +import { abstractify } from '@tmcp/internal-ts-helpers'; + +abstractify(); diff --git a/tools/ui/node_modules/@tmcp/session-manager/src/index.js b/tools/ui/node_modules/@tmcp/session-manager/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..adfd3f77988c74a42692a7f7066962ac1f2ef89d --- /dev/null +++ b/tools/ui/node_modules/@tmcp/session-manager/src/index.js @@ -0,0 +1,309 @@ +/* eslint-disable no-unused-vars */ + +/** + * @import { Context } from "tmcp"; + */ + +/** + * @abstract + */ +export class StreamSessionManager { + /** + * @abstract + * @param {string} id + * @param {ReadableStreamDefaultController} controller + * @returns {void | Promise} + */ + create(id, controller) { + throw new Error('Method not implemented.'); + } + + /** + * @abstract + * @param {string} id + * @returns {void | Promise} + */ + delete(id) { + throw new Error('Method not implemented.'); + } + + /** + * @abstract + * @param {string} id + * @returns {boolean | Promise} + */ + has(id) { + throw new Error('Method not implemented.'); + } + + /** + * @abstract + * @param {string[] | undefined} sessions + * @param {string} data + * @returns {void | Promise} + */ + send(sessions, data) { + throw new Error('Method not implemented.'); + } +} + +export class InMemoryStreamSessionManager extends StreamSessionManager { + /** + * @type {Map} + */ + #sessions = new Map(); + #text_encoder = new TextEncoder(); + + /** + * @param {string} id + * @param {ReadableStreamDefaultController} controller + */ + create(id, controller) { + this.#sessions.set(id, controller); + } + + /** + * @param {string} id + */ + delete(id) { + const controller = this.#sessions.get(id); + if (controller) { + this.#sessions.delete(id); + try { + controller.close(); + } catch { + // could error if the controller is already closed + } + } + } + + /** + * @param {string} id + * @returns {Promise} + */ + async has(id) { + return this.#sessions.has(id); + } + + /** + * @param {string[] | undefined} sessions + * @param {string} data + */ + send(sessions, data) { + for (const [id, controller] of this.#sessions.entries()) { + if (sessions == null || sessions.includes(id)) { + controller.enqueue(this.#text_encoder.encode(data)); + } + } + } +} + +/** + * @abstract + */ +export class InfoSessionManager { + /** + * @abstract + * @param {string} id + * @returns {Promise["clientInfo"]>} + */ + getClientInfo(id) { + throw new Error('Method not implemented.'); + } + + /** + * @abstract + * @param {string} id + * @param {NonNullable["clientInfo"]} client_info + */ + setClientInfo(id, client_info) { + throw new Error('Method not implemented.'); + } + + /** + * @abstract + * @param {string} id + * @returns {Promise["clientCapabilities"]>} + */ + getClientCapabilities(id) { + throw new Error('Method not implemented.'); + } + + /** + * @abstract + * @param {string} id + * @param {NonNullable["clientCapabilities"]} client_capabilities + */ + setClientCapabilities(id, client_capabilities) { + throw new Error('Method not implemented.'); + } + + /** + * @abstract + * @param {string} id + * @returns {Promise["logLevel"]>} + */ + getLogLevel(id) { + throw new Error('Method not implemented.'); + } + + /** + * @abstract + * @param {string} id + * @param {NonNullable["logLevel"]} log_level + */ + setLogLevel(id, log_level) { + throw new Error('Method not implemented.'); + } + + /** + * @abstract + * @param {string} uri + * @returns {Promise} + */ + getSubscriptions(uri) { + throw new Error('Method not implemented.'); + } + + /** + * @abstract + * @param {string} id + * @param {string} uri + */ + addSubscription(id, uri) { + throw new Error('Method not implemented.'); + } + + /** + * @abstract + * @param {string} id + * @param {string} uri + */ + removeSubscription(id, uri) { + throw new Error('Method not implemented.'); + } + + /** + * @abstract + * @param {string} id + */ + delete(id) { + throw new Error('Method not implemented.'); + } +} + +export class InMemoryInfoSessionManager extends InfoSessionManager { + /** + * @type {Map["clientInfo"]>} + */ + #client_info = new Map(); + /** + * @type {Map["clientCapabilities"]>} + */ + #client_capabilities = new Map(); + /** + * @type {Map["logLevel"]>} + */ + #log_level = new Map(); + /** + * @type {Map>} + */ + #subscriptions = new Map(); + + /** + * @param {string} session + * @param {string} name + * @returns {Promise} + */ + async #invariant(session, name) { + throw new Error(`${name} not found for session ${session}`); + } + + /** + * @type {InfoSessionManager["getClientInfo"]} + */ + getClientInfo(id) { + return Promise.resolve( + this.#client_info.get(id) ?? this.#invariant(id, 'Client info'), + ); + } + + /** + * @type {InfoSessionManager["setClientInfo"]} + */ + setClientInfo(id, client_info) { + this.#client_info.set(id, client_info); + } + + /** + * @type {InfoSessionManager["getClientCapabilities"]} + */ + getClientCapabilities(id) { + return Promise.resolve( + this.#client_capabilities.get(id) ?? + this.#invariant(id, 'Client capabilities'), + ); + } + + /** + * @type {InfoSessionManager["setClientCapabilities"]} + */ + setClientCapabilities(id, client_capabilities) { + this.#client_capabilities.set(id, client_capabilities); + } + + /** + * @type {InfoSessionManager["getLogLevel"]} + */ + getLogLevel(id) { + return Promise.resolve( + this.#log_level.get(id) ?? this.#invariant(id, 'Log Level'), + ); + } + + /** + * @type {InfoSessionManager["setLogLevel"]} + */ + setLogLevel(id, log_level) { + this.#log_level.set(id, log_level); + } + + /** + * @type {InfoSessionManager["getSubscriptions"]} + */ + getSubscriptions(uri) { + return Promise.resolve([...(this.#subscriptions.get(uri) ?? [])]); + } + + /** + * @type {InfoSessionManager["addSubscription"]} + */ + addSubscription(id, uri) { + let subscriptions = this.#subscriptions.get(uri); + if (!subscriptions) { + subscriptions = new Set(); + this.#subscriptions.set(uri, subscriptions); + } + subscriptions.add(id); + } + + /** + * @type {InfoSessionManager["removeSubscription"]} + */ + removeSubscription(id, uri) { + let subscriptions = this.#subscriptions.get(uri); + if (subscriptions) { + subscriptions.delete(id); + } + } + + /** + * @type {InfoSessionManager["delete"]} + */ + delete(id) { + this.#subscriptions.delete(id); + this.#log_level.delete(id); + this.#client_capabilities.delete(id); + this.#client_info.delete(id); + } +} diff --git a/tools/ui/node_modules/@tmcp/session-manager/src/types/index.d.ts b/tools/ui/node_modules/@tmcp/session-manager/src/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..28fc3121bdd7c27f673aa41b1516cc42c983ad47 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/session-manager/src/types/index.d.ts @@ -0,0 +1,84 @@ +declare module '@tmcp/session-manager' { + import type { Context } from 'tmcp'; + /** + * @import { Context } from "tmcp"; + */ + /** + * @abstract + */ + export abstract class StreamSessionManager { + /** + * @abstract + * */ + abstract create(id: string, controller: ReadableStreamDefaultController): void | Promise; + /** + * @abstract + * */ + abstract delete(id: string): void | Promise; + /** + * @abstract + * */ + abstract has(id: string): boolean | Promise; + /** + * @abstract + * */ + abstract send(sessions: string[] | undefined, data: string): void | Promise; + } + export class InMemoryStreamSessionManager extends StreamSessionManager { + create(id: string, controller: ReadableStreamDefaultController): void; + delete(id: string): void; + has(id: string): Promise; + send(sessions: string[] | undefined, data: string): void; + #private; + } + /** + * @abstract + */ + export abstract class InfoSessionManager { + /** + * @abstract + * */ + abstract getClientInfo(id: string): Promise["clientInfo"]>; + /** + * @abstract + * */ + abstract setClientInfo(id: string, client_info: NonNullable["clientInfo"]): void; + /** + * @abstract + * */ + abstract getClientCapabilities(id: string): Promise["clientCapabilities"]>; + /** + * @abstract + * */ + abstract setClientCapabilities(id: string, client_capabilities: NonNullable["clientCapabilities"]): void; + /** + * @abstract + * */ + abstract getLogLevel(id: string): Promise["logLevel"]>; + /** + * @abstract + * */ + abstract setLogLevel(id: string, log_level: NonNullable["logLevel"]): void; + /** + * @abstract + * */ + abstract getSubscriptions(uri: string): Promise; + /** + * @abstract + * */ + abstract addSubscription(id: string, uri: string): void; + /** + * @abstract + * */ + abstract removeSubscription(id: string, uri: string): void; + /** + * @abstract + * */ + abstract delete(id: string): void; + } + export class InMemoryInfoSessionManager extends InfoSessionManager { + #private; + } + export {}; +} +//# sourceMappingURL=index.d.ts.map diff --git a/tools/ui/node_modules/@tmcp/session-manager/src/types/index.d.ts.map b/tools/ui/node_modules/@tmcp/session-manager/src/types/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..8b489c8a8043b04ada0f45aa5fb621edf80d7b2b --- /dev/null +++ b/tools/ui/node_modules/@tmcp/session-manager/src/types/index.d.ts.map @@ -0,0 +1,18 @@ +{ + "version": 3, + "file": "index.d.ts", + "names": [ + "StreamSessionManager", + "InMemoryStreamSessionManager", + "InfoSessionManager", + "InMemoryInfoSessionManager" + ], + "sources": [ + "../index.js" + ], + "sourcesContent": [ + null + ], + "mappings": ";;;;;;;;cASaA,oBAAoBA;;;;;;;;;;;;;;;;;;cAwCpBC,4BAA4BA;;;;;;;;;;;;;;cAsD5BC,kBAAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA2FlBC,0BAA0BA", + "ignoreList": [] +} \ No newline at end of file diff --git a/tools/ui/node_modules/@tmcp/session-manager/tsconfig.json b/tools/ui/node_modules/@tmcp/session-manager/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..0f9183e95b0bdff9f1bed5919ace4e7a5b5e5249 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/session-manager/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "esnext", + "module": "nodenext", + "moduleResolution": "nodenext", + "allowJs": true, + "checkJs": true, + "declaration": true, + "emitDeclarationOnly": false, + "strict": true, + "noEmit": true, + "skipLibCheck": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules"] +} diff --git a/tools/ui/node_modules/@tmcp/transport-http/LICENSE b/tools/ui/node_modules/@tmcp/transport-http/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1e85c344f0ce6621b49293c01b4fab313bdce1c0 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/transport-http/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Paolo Ricciuti + +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. diff --git a/tools/ui/node_modules/@tmcp/transport-http/README.md b/tools/ui/node_modules/@tmcp/transport-http/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a2d425be1eada90a223eab789982cf25c70243f8 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/transport-http/README.md @@ -0,0 +1,439 @@ +# @tmcp/transport-http + +An HTTP transport implementation for TMCP (TypeScript Model Context Protocol) servers. This package provides HTTP Streaming based communication for MCP servers over HTTP, enabling web-based clients to interact with your MCP server through standard HTTP requests. + +## Installation + +```bash +pnpm add @tmcp/transport-http tmcp +``` + +## Usage + +### Basic Setup + +```javascript +import { McpServer } from 'tmcp'; +import { HttpTransport } from '@tmcp/transport-http'; + +// Create your MCP server +const server = new McpServer( + { + name: 'my-http-server', + version: '1.0.0', + description: 'My HTTP MCP server', + }, + { + adapter: new YourSchemaAdapter(), + capabilities: { + tools: { listChanged: true }, + prompts: { listChanged: true }, + resources: { listChanged: true }, + }, + }, +); + +// Add your tools, prompts, and resources +server.tool( + { + name: 'example_tool', + description: 'An example tool', + }, + async () => { + return { + content: [{ type: 'text', text: 'Hello from HTTP!' }], + }; + }, +); + +// Create the HTTP transport (defaults to '/mcp' path) +const transport = new HttpTransport(server); + +// Use with your preferred HTTP server +// Example with Node.js built-in server + @remix-run/ +import * as http from 'node:http'; +import { createRequestListener } from '@remix-run/node-fetch-server'; + +let httpServer = http.createServer(createRequestListener((request)=>{ + const response = await transport.respond(request); + if(response){ + return response; + } + return new Response(null, { status: 404 }); +})); + + +httpServer.listen(3000, () => { + console.log('MCP HTTP server listening on port 3000'); +}); +``` + +### With Custom Configuration + +```javascript +const transport = new HttpTransport(server, { + // Custom MCP endpoint path (default: '/mcp', use null to respond on every path) + path: '/api/mcp', + // Custom session ID generation + getSessionId: () => { + return `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; + }, +}); + +> [!NOTE] +> When the transport runs in development mode and you omit the `path` option, a warning is emitted. Future releases will treat an `undefined` path as "respond on every path", so set the property explicitly (for example `path: '/mcp'` or `path: null`) to lock in the behavior you want today. +``` + +### With Custom Context + +You can pass custom context data to your MCP server for each request. This is useful for authentication, user information, database connections, etc. + +```javascript +// Define your custom context type +interface MyContext { + userId: string; + permissions: string[]; + database: DatabaseConnection; +} + +// Create server with custom context +const server = new McpServer(serverInfo, options).withContext(); + +server.tool( + { + name: 'get-user-profile', + description: 'Get the current user profile', + }, + async () => { + // Access custom context in your handler + const { userId, database } = server.ctx.custom!; + const profile = await database.users.findById(userId); + + return { + content: [ + { type: 'text', text: `User profile: ${JSON.stringify(profile)}` } + ], + }; + }, +); + +// Create transport (it will be typed to accept your custom context) +const transport = new HttpTransport(server); + +// then in the handler +const response = await transport.respond(req, { + userId, + permissions, + database: req.locals.db, +}); +``` + +### Session Management + +The HTTP transport supports custom session managers for different deployment scenarios: + +#### In-Memory Sessions (Default) + +```javascript +import { + InMemoryStreamSessionManager, + InMemoryInfoSessionManager, +} from '@tmcp/session-manager'; + +const transport = new HttpTransport(server, { + sessionManager: { + streams: new InMemoryStreamSessionManager(), + info: new InMemoryInfoSessionManager(), + }, +}); +``` + +#### Redis Sessions (Multi-Server/Serverless) + +For deployments across multiple servers or serverless environments where sessions need to be shared: + +```javascript +import { + RedisStreamSessionManager, + RedisInfoSessionManager, +} from '@tmcp/session-manager-redis'; + +const transport = new HttpTransport(server, { + sessionManager: { + streams: new RedisStreamSessionManager('redis://localhost:6379'), + info: new RedisInfoSessionManager('redis://localhost:6379'), + }, +}); +``` + +**When to use Redis sessions:** + +- **Multi-server deployments**: When your application runs on multiple servers and clients might connect to different instances +- **Serverless deployments**: When your transport is deployed on serverless platforms where instances are ephemeral (attention, serverless environment generally kills SSE request after a not-so-long amount of time, this means notification from the server will not reach the client after the shutdown) +- **Load balancing**: When using load balancers that might route requests to different server instances + +## Features + +- **🌐 HTTP/SSE Communication**: Uses Server-Sent Events for real-time bidirectional communication +- **🔄 Session Management**: Maintains client sessions with automatic session ID generation +- **📡 Streaming Responses**: Supports streaming responses through SSE +- **🛤️ Configurable Path**: Customizable MCP endpoint path with automatic filtering (set `path` to `null` to respond everywhere) +- **🔧 Framework Agnostic**: Works with any HTTP server framework (Fastify, Bun, Deno, etc.) +- **⚡ Real-time Updates**: Server can push notifications and updates to connected clients +- **🛡️ Error Handling**: Graceful error handling for malformed requests +- **🔀 Multiple HTTP Methods**: Supports GET (notifications), POST (messages), and DELETE (disconnect) +- **🧠 Session Metadata**: Automatically persists client capabilities, info, and log levels and exposes them via `server.ctx.sessionInfo` + +## API + +### `HttpTransport` + +#### Constructor + +```typescript +new HttpTransport(server: McpServer, options?: HttpTransportOptions) +``` + +Creates a new HTTP transport instance. + +**Parameters:** + +- `server` - A TMCP server instance to handle incoming requests +- `options` - Optional configuration for the transport + +**Options:** + +```typescript +interface HttpTransportOptions { + getSessionId: () => string; // Custom session ID generator + path?: string | null; // MCP endpoint path (default: '/mcp', null responds on every path) + oauth?: OAuth; // an oauth provider generated from @tmcp/auth + sessionManager?: { + streams?: StreamSessionManager; + info?: InfoSessionManager; + }; // Provide custom managers; defaults to in-memory implementations + disableSse?: boolean; // Disable SSE stream endpoint (GET returns 405) +} +``` + +If you omit `sessionManager` the transport creates `InMemoryStreamSessionManager` and `InMemoryInfoSessionManager` instances for you. You can override either field independently (for example, Redis streams with in-memory metadata during development). + +### Disabling SSE Streams + +If your deployment doesn't support long-lived SSE connections (e.g., some serverless environments), you can disable the GET endpoint: + +```javascript +const transport = new HttpTransport(server, { + disableSse: true, +}); +``` + +When `disableSse` is `true`, GET requests to the MCP endpoint will return a `405 Method Not Allowed` response. Clients can still communicate via POST requests, but won't receive server-initiated notifications. + +#### Methods + +##### `respond(request: Request, customContext?: T): Promise` + +Processes an HTTP request and returns a Response with Server-Sent Events, or null if the request path doesn't match the configured MCP path. + +**Parameters:** + +- `request` - A Web API Request object containing the JSON-RPC message +- `customContext` - Optional custom context data to pass to the MCP server for this request + +**Returns:** + +- A Response object with SSE stream for ongoing communication, or null if the request path doesn't match the MCP endpoint + +**HTTP Methods:** + +- **POST**: Processes MCP messages and returns short-lived event stream responses +- **GET**: Establishes long-lived connections for server notifications +- **DELETE**: Disconnects sessions and cleans up resources + +## Protocol Details + +### HTTP Methods + +The transport supports three HTTP methods: + +#### POST - Message Processing + +Clients send JSON-RPC messages via HTTP POST requests: + +```http +POST /mcp HTTP/1.1 +Content-Type: application/json +mcp-session-id: optional-session-id + +{ + "jsonrpc": "2.0", + "id": 1, + "method": "tools/list", + "params": {} +} +``` + +Response: Short-lived event stream that closes after sending the response: + +```http +HTTP/1.1 200 OK +Content-Type: text/event-stream +Cache-Control: no-cache +mcp-session-id: generated-or-provided-session-id + +data: {"jsonrpc":"2.0","id":1,"result":{"tools":[...]}} + +``` + +#### GET - Notification Stream + +Establishes long-lived connections for server notifications: + +```http +GET /mcp HTTP/1.1 +mcp-session-id: optional-session-id +``` + +Response: Long-lived event stream for server notifications: + +```http +HTTP/1.1 200 OK +Content-Type: text/event-stream +Cache-Control: no-cache +Connection: keep-alive +mcp-session-id: generated-or-provided-session-id + +data: {"jsonrpc":"2.0","method":"notifications/initialized","params":{}} + +``` + +#### DELETE - Session Disconnect + +Disconnects a session and cleans up resources: + +```http +DELETE /mcp HTTP/1.1 +mcp-session-id: session-to-disconnect +``` + +Response: + +```http +HTTP/1.1 204 No Content +mcp-session-id: session-to-disconnect +``` + +### Session Management + +- **Session ID Header**: `mcp-session-id` +- **Automatic Generation**: If no session ID is provided, one is generated automatically +- **Session Persistence**: Sessions persist across multiple requests until the client disconnects +- **Server Notifications**: Server can send notifications to all active sessions + +## Framework Examples + +### Bun + +```javascript +import { McpServer } from 'tmcp'; +import { HttpTransport } from '@tmcp/transport-http'; + +const server = new McpServer(/* ... */); +const transport = new HttpTransport(server); + +Bun.serve({ + port: 3000, + async fetch(req) { + const response = await transport.respond(req); + if (response === null) { + return new Response('Not Found', { status: 404 }); + } + return response; + }, +}); +``` + +### Deno + +```javascript +import { McpServer } from 'tmcp'; +import { HttpTransport } from '@tmcp/transport-http'; + +const server = new McpServer(/* ... */); +const transport = new HttpTransport(server); + +Deno.serve({ port: 3000 }, async (req) => { + const response = await transport.respond(req); + if (response === null) { + return new Response('Not Found', { status: 404 }); + } + return response; +}); +``` + +### `srvx` + +If you want the same experience across Deno, Bun, and Node.js, you can use [srvx](https://srvx.h3.dev/). + +```js +import { McpServer } from 'tmcp'; +import { HttpTransport } from '@tmcp/transport-http'; +import { serve } from 'srvx'; + +const server = new McpServer(/* ... */); +const transport = new HttpTransport(server); + +serve({ + async fetch(req) { + const response = await transport.respond(req); + if (response === null) { + return new Response('Not Found', { status: 404 }); + } + return response; + }, +}); +``` + +## Error Handling + +The transport includes comprehensive error handling: + +- **Malformed JSON**: Invalid JSON requests return appropriate error responses +- **Session Management**: Automatic cleanup of disconnected sessions +- **Server Errors**: Server processing errors are propagated to clients + +## Development + +```bash +# Install dependencies +pnpm install + +# Generate TypeScript declarations +pnpm generate:types + +# Lint the code +pnpm lint +``` + +## Requirements + +- Node.js 16+ (for native ES modules and Web API support) +- A TMCP server instance +- An HTTP server framework or runtime +- A schema adapter (Zod, Valibot, etc.) + +## Related Packages + +- [`tmcp`](../tmcp) - Core TMCP server implementation +- [`@tmcp/transport-stdio`](../transport-stdio) - Standard I/O transport +- [`@tmcp/adapter-zod`](../adapter-zod) - Zod schema adapter +- [`@tmcp/adapter-valibot`](../adapter-valibot) - Valibot schema adapter + +## Acknowledgments + +Huge thanks to Sean O'Bannon that provided us with the `@tmcp` scope on npm. + +## License + +MIT diff --git a/tools/ui/node_modules/@tmcp/transport-http/package.json b/tools/ui/node_modules/@tmcp/transport-http/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c21dde8137af94da806300df32c477b6e8c9584b --- /dev/null +++ b/tools/ui/node_modules/@tmcp/transport-http/package.json @@ -0,0 +1,62 @@ +{ + "name": "@tmcp/transport-http", + "version": "0.8.6", + "license": "MIT", + "description": "Transport for TMCP using HTTP", + "type": "module", + "main": "src/index.js", + "types": "src/types/index.d.ts", + "exports": { + ".": { + "types": "./src/types/index.d.ts", + "default": "./src/index.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "src/**/*" + ], + "peerDependencies": { + "tmcp": "^1.18.0", + "@tmcp/auth": "^0.3.3 || ^0.4.0" + }, + "peerDependenciesMeta": { + "@tmcp/auth": { + "optional": true + } + }, + "keywords": [ + "tmcp", + "http", + "transport" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/paoloricciuti/tmcp.git", + "directory": "packages/transport-http" + }, + "dependencies": { + "esm-env": "^1.2.2", + "@tmcp/session-manager": "^0.2.2" + }, + "devDependencies": { + "@modelcontextprotocol/sdk": "^1.17.1", + "@remix-run/node-fetch-server": "^0.13.0", + "@types/node": "^24.0.15", + "dts-buddy": "^0.6.2", + "publint": "^0.3.12", + "valibot": "^1.1.0", + "vitest": "^4.0.0", + "@tmcp/adapter-valibot": "^0.1.6", + "@tmcp/auth": "^0.4.1", + "tmcp": "^1.19.4" + }, + "publishConfig": { + "access": "public" + }, + "scripts": { + "generate:types": "dts-buddy && publint", + "prepublish": "pnpm generate:types", + "test": "vitest --run" + } +} \ No newline at end of file diff --git a/tools/ui/node_modules/@tmcp/transport-http/src/index.js b/tools/ui/node_modules/@tmcp/transport-http/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1a60d0ccfced7410095e43c602cc75e31c42cc50 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/transport-http/src/index.js @@ -0,0 +1,601 @@ +/** + * @import { AuthInfo, McpServer } from "tmcp"; + * @import { OAuth } from "@tmcp/auth"; + * @import { StreamSessionManager, InfoSessionManager } from "@tmcp/session-manager"; + * @import { OptionalizeSessionManager } from "./type-utils.js" + */ + +/** + * @typedef {{ + * origin?: string | string[] | boolean + * methods?: string[] + * allowedHeaders?: string[] + * exposedHeaders?: string[] + * credentials?: boolean + * maxAge?: number + * }} CorsConfig + */ + +/** + * @typedef {{ + * getSessionId?: () => string + * path?: string | null + * oauth?: OAuth<"built"> + * cors?: CorsConfig | boolean, + * sessionManager?: { streams?: StreamSessionManager, info?: OptionalizeSessionManager } + * disableSse?: boolean + * }} HttpTransportOptions + */ + +import { AsyncLocalStorage } from 'node:async_hooks'; +import { + InMemoryStreamSessionManager, + InMemoryInfoSessionManager, +} from '@tmcp/session-manager'; +import { DEV } from 'esm-env'; + +/** + * @template {Record | undefined} [TCustom=undefined] + */ +export class HttpTransport { + /** + * @typedef {NonNullable["sessionManager"]>>} SessionManager + */ + + /** + * @type {McpServer} + */ + #server; + + /** + * @type {Required> & { cors?: CorsConfig | boolean, sessionManager: SessionManager, disableSse?: boolean }} + */ + #options; + + /** + * @type {string | null} + */ + #path; + + /** + * @type {AsyncLocalStorage} + */ + #controller_storage = new AsyncLocalStorage(); + + /** + * @type {AsyncLocalStorage} + */ + #session_id_storage = new AsyncLocalStorage(); + + /** + * @type {OAuth<"built"> | undefined} + */ + #oauth; + + #text_encoder = new TextEncoder(); + + /** + * + * @param {McpServer} server + * @param {HttpTransportOptions} [options] + */ + constructor(server, options) { + this.#server = server; + const { + getSessionId = () => crypto.randomUUID(), + path = '/mcp', + oauth, + cors, + disableSse, + sessionManager: _sessionManager = { + streams: new InMemoryStreamSessionManager(), + info: new InMemoryInfoSessionManager(), + }, + } = options ?? { + getSessionId: () => crypto.randomUUID(), + }; + + /** + * @type {SessionManager} + */ + const sessionManager = { + streams: + _sessionManager.streams ?? new InMemoryStreamSessionManager(), + info: _sessionManager.info ?? new InMemoryInfoSessionManager(), + }; + + if (options?.path === undefined && DEV) { + // TODO: remove on 1.0.0 release + console.warn( + "[tmcp][transport-http] `options.path` is undefined, in future versions passing `undefined` will default to respond on all paths. To keep the current behavior, explicitly set `path` to '/mcp' or your desired path.", + ); + } + + if (oauth) { + this.#oauth = oauth; + } + + this.#options = { + getSessionId, + path, + cors, + sessionManager, + disableSse, + }; + this.#path = path; + + this.#server.on('initialize', ({ capabilities, clientInfo }) => { + const sessionId = this.#session_id_storage.getStore(); + if (!sessionId) return; + this.#options.sessionManager.info.setClientCapabilities( + sessionId, + capabilities, + ); + this.#options.sessionManager.info.setClientInfo( + sessionId, + clientInfo, + ); + }); + + this.#server.on('subscription', async ({ uri, action }) => { + const sessionId = this.#session_id_storage.getStore(); + if (!sessionId) return; + if (action === 'remove') { + this.#options.sessionManager.info.removeSubscription?.( + sessionId, + uri, + ); + } else { + this.#options.sessionManager.info.addSubscription( + sessionId, + uri, + ); + } + }); + + this.#server.on('loglevelchange', ({ level }) => { + const sessionId = this.#session_id_storage.getStore(); + if (!sessionId) return; + this.#options.sessionManager.info.setLogLevel(sessionId, level); + }); + + this.#server.on('broadcast', async ({ request }) => { + let sessions = undefined; + if (request.method === 'notifications/resources/updated') { + sessions = + await this.#options.sessionManager.info.getSubscriptions( + request.params.uri, + ); + } + await this.#options.sessionManager.streams.send( + sessions, + 'event: message\ndata: ' + JSON.stringify(request) + '\n\n', + ); + }); + + this.#server.on('send', async ({ request }) => { + // use the current controller if the request has an id (it means it's a request and not a notification) + const controller = this.#controller_storage.getStore(); + if (!controller) return; + + controller.enqueue( + this.#text_encoder.encode( + 'event: message\ndata: ' + JSON.stringify(request) + '\n\n', + ), + ); + }); + } + + /** + * Applies CORS headers to a response based on the configuration + * @param {Response} response - The response to modify + * @param {Request} request - The original request + */ + #apply_cors_headers(response, request) { + const cors_config = this.#options.cors; + if (!cors_config) { + return; + } + + // Handle boolean true (allow all origins) + if (cors_config === true) { + response.headers.set('Access-Control-Allow-Origin', '*'); + response.headers.set( + 'Access-Control-Allow-Methods', + 'GET, POST, DELETE, OPTIONS', + ); + response.headers.set('Access-Control-Allow-Headers', '*'); + return; + } + + // Handle detailed configuration + const config = /** @type {CorsConfig} */ (cors_config); + const origin = request.headers.get('origin'); + + // Handle origin + if (config.origin !== undefined) { + if (config.origin === true || config.origin === '*') { + response.headers.set('Access-Control-Allow-Origin', '*'); + } else if (typeof config.origin === 'string') { + if (origin === config.origin) { + response.headers.set( + 'Access-Control-Allow-Origin', + config.origin, + ); + } + } else if (Array.isArray(config.origin)) { + if (origin && config.origin.includes(origin)) { + response.headers.set('Access-Control-Allow-Origin', origin); + } + } + } + + // Handle other CORS headers with defaults + const methods = config.methods ?? ['GET', 'POST', 'DELETE', 'OPTIONS']; + response.headers.set( + 'Access-Control-Allow-Methods', + methods.join(', '), + ); + + const allowed_headers = config.allowedHeaders ?? '*'; + if (Array.isArray(allowed_headers)) { + response.headers.set( + 'Access-Control-Allow-Headers', + allowed_headers.join(', '), + ); + } else { + response.headers.set( + 'Access-Control-Allow-Headers', + allowed_headers, + ); + } + + if (config.exposedHeaders) { + response.headers.set( + 'Access-Control-Expose-Headers', + config.exposedHeaders.join(', '), + ); + } + + if (config.credentials) { + response.headers.set('Access-Control-Allow-Credentials', 'true'); + } + + if (config.maxAge !== undefined) { + response.headers.set( + 'Access-Control-Max-Age', + config.maxAge.toString(), + ); + } + } + + /** + * @param {string} session_id + */ + async #handle_delete(session_id) { + await this.#options.sessionManager.streams.delete(session_id); + await this.#options.sessionManager.info.delete(session_id); + return new Response(null, { + status: 200, + headers: { + 'mcp-session-id': session_id, + }, + }); + } + + /** + * + * @param {string} session_id + * @returns + */ + async #handle_get(session_id) { + if (this.#options.disableSse) { + return new Response(null, { + status: 405, + headers: { + Allow: 'POST, DELETE, OPTIONS', + }, + }); + } + + const sessions = this.#options.sessionManager; + const text_encoder = this.#text_encoder; + // If session already exists, return error + const existing_session = await sessions.streams.has(session_id); + if (existing_session) { + return new Response( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: + 'Conflict: Only one SSE stream is allowed per session', + }, + id: null, + }), + { + headers: { + 'Content-Type': 'application/json', + 'mcp-session-id': session_id, + }, + status: 409, + }, + ); + } + + // Create new long-lived stream for notifications + const stream = new ReadableStream({ + async start(controller) { + await sessions.streams.create(session_id, controller); + // send a comment to flush the headers immediately + controller.enqueue(text_encoder.encode(': connected\n\n')); + }, + async cancel() { + await sessions.streams.delete(session_id); + }, + }); + + return new Response(stream, { + headers: { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive', + 'mcp-session-id': session_id, + }, + status: 200, + }); + } + + /** + * + * @param {string} session_id + * @param {Request} request + * @param {AuthInfo | null} auth_info + * @param {TCustom} [ctx] + */ + async #handle_post(session_id, request, auth_info, ctx) { + // Check Content-Type header + const content_type = request.headers.get('content-type'); + if (!content_type || !content_type.includes('application/json')) { + return new Response( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32600, + message: 'Invalid Request', + data: 'Content-Type must be application/json', + }, + }), + { + status: 415, + headers: { + 'Content-Type': 'application/json', + 'mcp-session-id': session_id, + }, + }, + ); + } + + try { + const body = await request.clone().json(); + + /** + * @type {ReadableStreamDefaultController | undefined} + */ + let controller; + + // Create a short-lived stream that closes after sending the response + const stream = new ReadableStream({ + start(_controller) { + controller = _controller; + }, + }); + + const session_id_storage = this.#session_id_storage; + + const messages = Array.isArray(body) ? body : [body]; + + const handle = async () => { + const init_message = messages.find( + (/** @type {any} */ m) => m.method === 'initialize', + ); + + const client_capabilities = init_message + ? init_message.params?.capabilities + : await this.#options.sessionManager.info + .getClientCapabilities(session_id) + .catch(() => undefined); + const client_info = init_message + ? init_message.params?.clientInfo + : await this.#options.sessionManager.info + .getClientInfo(session_id) + .catch(() => undefined); + const log_level = init_message + ? undefined + : await this.#options.sessionManager.info + .getLogLevel(session_id) + .catch(() => undefined); + + const response = await this.#controller_storage.run( + controller, + () => + session_id_storage.run(session_id, () => + this.#server.receive(body, { + sessionId: session_id, + auth: auth_info ?? undefined, + sessionInfo: { + clientCapabilities: client_capabilities, + clientInfo: client_info, + logLevel: log_level, + }, + custom: ctx, + }), + ), + ); + + controller?.enqueue( + this.#text_encoder.encode( + 'event: message\ndata: ' + + JSON.stringify(response) + + '\n\n', + ), + ); + controller?.close(); + }; + + handle(); + + const has_request = messages.some((message) => message.id != null); + + // Determine status code based on response type + // 202 Accepted for notifications/responses, 200 OK for standard requests + const status = !has_request ? 202 : 200; + + return new Response(has_request ? stream : null, { + headers: has_request + ? { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + connection: 'keep-alive', + 'mcp-session-id': session_id, + } + : undefined, + status, + }); + } catch (error) { + // Handle JSON parsing errors + return new Response( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32700, + message: 'Parse error', + data: /** @type {Error} */ (error).message, + }, + }), + { + status: 400, + headers: { + 'Content-Type': 'application/json', + 'mcp-session-id': session_id, + }, + }, + ); + } + } + + /** + * + * @param {string} method + * @returns + */ + #handle_default(method) { + return new Response( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32601, + message: 'Method not found', + data: `HTTP method ${method} not supported`, + }, + }), + { + status: 405, + headers: { + 'Content-Type': 'application/json', + Allow: 'GET, POST, DELETE, OPTIONS', + }, + }, + ); + } + + /** + * + * @param {Request} request + * @param {TCustom} [ctx] + * @returns {Promise} + */ + async respond(request, ctx) { + const url = new URL(request.url); + + /** + * @type {AuthInfo | null} + */ + let auth_info = null; + + // Check if OAuth helper should handle this request + if (this.#oauth) { + try { + const response = await this.#oauth.respond(request); + if (response) { + return response; + } + } catch (error) { + return new Response( + JSON.stringify({ + error: 'server_error', + error_description: /** @type {Error} */ (error).message, + }), + { + status: 500, + headers: { 'Content-Type': 'application/json' }, + }, + ); + } + auth_info = await this.#oauth.verify(request); + } + + // Check if the request path matches the configured MCP path + if (url.pathname !== this.#path && this.#path !== null) { + return null; + } + + const method = request.method; + const session_id = + request.headers.get('mcp-session-id') || + this.#options.getSessionId(); + + /** + * @type {Response | null} + */ + let response = null; + + // Handle OPTIONS request - preflight CORS + if (method === 'OPTIONS') { + response = new Response(null, { + status: 204, + headers: { + 'Content-Type': 'application/json', + }, + }); + } + // Handle DELETE request - disconnect session + else if (method === 'DELETE') { + response = await this.#handle_delete(session_id); + } + // Handle GET request - establish long-lived connection for notifications + else if (method === 'GET') { + response = await this.#handle_get(session_id); + } + // Handle POST request - process message and respond through event stream + else if (method === 'POST') { + response = await this.#handle_post( + session_id, + request, + auth_info, + ctx, + ); + } + // Method not supported + else { + response = this.#handle_default(method); + } + + // Apply CORS headers if we have a response + if (response) { + this.#apply_cors_headers(response, request); + } + + return response; + } +} diff --git a/tools/ui/node_modules/@tmcp/transport-http/src/type-utils.d.ts b/tools/ui/node_modules/@tmcp/transport-http/src/type-utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7e053f28bda5f75042700291bbb3430b9d204dba --- /dev/null +++ b/tools/ui/node_modules/@tmcp/transport-http/src/type-utils.d.ts @@ -0,0 +1,6 @@ + +import { InfoSessionManager } from "@tmcp/session-manager"; + +type ToOmit = 'removeSubscription'; + +export type OptionalizeSessionManager = Omit & Partial>; \ No newline at end of file diff --git a/tools/ui/node_modules/@tmcp/transport-http/src/types/index.d.ts b/tools/ui/node_modules/@tmcp/transport-http/src/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7c276a4e728efee08d49c79c434800a43cb4cd74 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/transport-http/src/types/index.d.ts @@ -0,0 +1,38 @@ +declare module '@tmcp/transport-http' { + import type { McpServer } from 'tmcp'; + import type { OAuth } from '@tmcp/auth'; + import type { StreamSessionManager, InfoSessionManager } from '@tmcp/session-manager'; + export class HttpTransport | undefined = undefined> { + + constructor(server: McpServer, options?: HttpTransportOptions); + + respond(request: Request, ctx?: TCustom): Promise; + #private; + } + export type CorsConfig = { + origin?: string | string[] | boolean; + methods?: string[]; + allowedHeaders?: string[]; + exposedHeaders?: string[]; + credentials?: boolean; + maxAge?: number; + }; + export type HttpTransportOptions = { + getSessionId?: () => string; + path?: string | null; + oauth?: OAuth<"built">; + cors?: CorsConfig | boolean; + sessionManager?: { + streams?: StreamSessionManager; + info?: OptionalizeSessionManager; + }; + disableSse?: boolean; + }; + type ToOmit = 'removeSubscription'; + + type OptionalizeSessionManager = Omit & Partial>; + + export {}; +} + +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/@tmcp/transport-http/src/types/index.d.ts.map b/tools/ui/node_modules/@tmcp/transport-http/src/types/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..00945cb41cddb53ccabb52fa077f085032136656 --- /dev/null +++ b/tools/ui/node_modules/@tmcp/transport-http/src/types/index.d.ts.map @@ -0,0 +1,19 @@ +{ + "version": 3, + "file": "index.d.ts", + "names": [ + "HttpTransport", + "ToOmit", + "OptionalizeSessionManager" + ], + "sources": [ + "../index.js", + "../type-utils.d.ts" + ], + "sourcesContent": [ + null, + null + ], + "mappings": ";;;;cAuCaA,aAAaA;;;;;;;;;;;;;;;;;;;;;;;;;;MCpCrBC,MAAMA;;MAECC,yBAAyBA", + "ignoreList": [] +} \ No newline at end of file diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/.travis.yml b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..4237da797598136a3028737aa9869acfb0a7c371 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/.travis.yml @@ -0,0 +1,8 @@ +sudo: required + +services: + - docker + +script: + - docker build -t omt . + - docker run --rm -v `pwd`:/usr/src omt diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/CONTRIBUTING b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/CONTRIBUTING new file mode 100644 index 0000000000000000000000000000000000000000..f9a2f286364582b5733e60a756ec184d145bc8db --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/CONTRIBUTING @@ -0,0 +1,27 @@ +Want to contribute? Great! First, read this page (including the small print at the end). + +### Before you contribute +Before we can use your code, you must sign the +[Google Individual Contributor License Agreement] +(https://cla.developers.google.com/about/google-individual) +(CLA), which you can do online. The CLA is necessary mainly because you own the +copyright to your changes, even after your contribution becomes part of our +codebase, so we need your permission to use and distribute your code. We also +need to be sure of various other things—for instance that you'll tell us if you +know that your code infringes on other people's patents. You don't have to sign +the CLA until after you've submitted your code for review and a member has +approved it, but you must do it before we can put your code into our codebase. +Before you start working on a larger contribution, you should get in touch with +us first through the issue tracker with your idea so that we can help out and +possibly guide you. Coordinating up front makes it much easier to avoid +frustration later on. + +### Code reviews +All submissions, including submissions by project members, require review. We +use Github pull requests for this purpose. + +### The small print +Contributions made by corporations are covered by a different agreement than +the one above, the +[Software Grant and Corporate Contributor License Agreement] +(https://cla.developers.google.com/about/google-corporate). diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/CONTRIBUTORS b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/CONTRIBUTORS new file mode 100644 index 0000000000000000000000000000000000000000..754070defe62cc7d57ff9e5c34279a61bc824348 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/CONTRIBUTORS @@ -0,0 +1,11 @@ +# People who have agreed to one of the CLAs and can contribute patches. +# The AUTHORS file lists the copyright holders; this file +# lists people. For example, Google employees are listed here +# but not in AUTHORS, because Google holds the copyright. +# +# https://developers.google.com/open-source/cla/individual +# https://developers.google.com/open-source/cla/corporate +# +# Names should be added to this file as: +# Name +Surma diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/LICENSE b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5475cb8490d9f88049ba31348e211b7149cbe698 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/README.md b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7df893291c9b45a80c32f5bca837687ca9b57d2c --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/README.md @@ -0,0 +1,97 @@ +# rollup-plugin-off-main-thread + +Use Rollup with workers and ES6 modules _today_. + +``` +$ npm install --save @trickfilm400/rollup-plugin-off-main-thread +``` + +Workers are JavaScript’s version of threads. [Workers are important to use][when workers] as the main thread is already overloaded, especially on slower or older devices. + +This plugin takes care of shimming module support in workers and allows you to use `new Worker()`. + +OMT is the result of merging loadz0r and workz0r. + +## Usage + +I set up [a gist] to show a full setup with OMT. + +### Config + +```js +// rollup.config.js +import OMT from "@trickfilm400/rollup-plugin-off-main-thread"; + +export default { + input: ["src/main.js"], + output: { + dir: "dist", + // You _must_ use either “amd” or “esm” as your format. + // But note that only very few browsers have native support for + // modules in workers. + format: "amd" + }, + plugins: [OMT()] +}; +``` + +### Auto bundling + +In your project's code use a module-relative path via `new URL` to include a Worker: + +```js +const worker = new Worker(new URL("worker.js", import.meta.url), { + type: "module" +}); +``` + +This will just work. + +If required, the plugin also supports plain literal paths: + +```js +const worker = new Worker("./worker.js", { type: "module" }); +``` + +However, those are less portable: in Rollup they would result in module-relative +path, but if used directly in the browser, they'll be relative to the document +URL instead. + +Hence, they're deprecated and `new URL` pattern is encouraged instead for portability. + +### Importing workers as URLs + +If your worker constructor doesn't match `workerRegexp` (see options below), you might find it easier to import the worker as a URL. In your project's code: + +```js +import workerURL from "omt:./worker.js"; +import paintWorkletURL from "omt:./paint-worklet.js"; + +const worker = new Worker(workerURL, { name: "main-worker" }); +CSS.paintWorklet.addModule(paintWorkletURL); +``` + +`./worker.js` and `./paint-worklet.js` will be added to the output as chunks. + +## Options + +```js +{ + // ... + plugins: [OMT(options)]; +} +``` + +- `loader`: A string containing the EJS template for the amd loader. If `undefined`, OMT will use `loader.ejs`. +- `useEval`: Use `fetch()` + `eval()` to load dependencies instead of ` diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/amd-function-name/config.json b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/amd-function-name/config.json new file mode 100644 index 0000000000000000000000000000000000000000..8026f554b87b103e3642f4561633723accc0d392 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/amd-function-name/config.json @@ -0,0 +1,3 @@ +{ + "amdFunctionName": "foo" +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/amd-function-name/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/amd-function-name/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..a2991987b8314c8b050fe3be28836856be460216 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/amd-function-name/entry.js @@ -0,0 +1,22 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import("./a.js").then(m => { + if (m.default() != 4) { + return; + } + if (!self.foo) { + return; + } + window.parent.postMessage("a", "*"); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/build/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/build/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..26a4a5c2557c6d994796ab33d1a46b93f8b1686f --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/build/entry.js @@ -0,0 +1,90 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['module', 'require'], (function (module, require) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + const w = new Worker(new URL("worker-CtBAebZB.js", module.uri)); + w.addEventListener("message", ev => { + window.parent.postMessage(ev.data, "*"); + }); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/build/runner.html b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/build/runner.html new file mode 100644 index 0000000000000000000000000000000000000000..e03fb21d61b5110b6f5de9ecd90b27eb839d9936 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/build/runner.html @@ -0,0 +1,15 @@ + + + + diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/build/worker-2a7f7c23.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/build/worker-2a7f7c23.js new file mode 100644 index 0000000000000000000000000000000000000000..1278273bd039eaea67e1a7cc8d1ee38f1fab3f8c --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/build/worker-2a7f7c23.js @@ -0,0 +1,91 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + var url = "assets/my-asset-620b911b.bin"; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + fetch(url) + .then(resp => resp.text()) + .then(text => postMessage(text)); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/build/worker-5cc2068a.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/build/worker-5cc2068a.js new file mode 100644 index 0000000000000000000000000000000000000000..2705d867ee107f9df376e33cf94946e959043ca1 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/build/worker-5cc2068a.js @@ -0,0 +1,92 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + var url = "assets/my-asset-8db90352.bin"; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + fetch(url) + .then(resp => resp.text()) + .then(text => postMessage(text)); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/build/worker-CtBAebZB.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/build/worker-CtBAebZB.js new file mode 100644 index 0000000000000000000000000000000000000000..36dca46a8a6d7c8f68030cafc605cf2a21ff062e --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/build/worker-CtBAebZB.js @@ -0,0 +1,92 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + var url = "assets/my-asset-C4yNwep_.bin"; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + fetch(url) + .then(resp => resp.text()) + .then(text => postMessage(text)); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..665d17fa1eb732733dedd218aae9b909db4c496a --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/entry.js @@ -0,0 +1,17 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const w = new Worker("./worker.js"); +w.addEventListener("message", ev => { + window.parent.postMessage(ev.data, "*"); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/rollup.config.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/rollup.config.js new file mode 100644 index 0000000000000000000000000000000000000000..70a90d180747ee5cfaf46319634b4e1cb90663ce --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/rollup.config.js @@ -0,0 +1,25 @@ +const MARKER = "my-special-import"; +module.exports = (config, outputOptions, omt) => { + config.plugins = [ + omt(), + { + resolveId(id) { + if (id !== MARKER) { + return; + } + return id; + }, + load(id) { + if (id !== MARKER) { + return; + } + const referenceId = this.emitFile({ + type: "asset", + name: "my-asset.bin", + source: "assetcontent" + }); + return `export default import.meta.ROLLUP_FILE_URL_${referenceId}`; + } + } + ]; +}; diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/worker.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/worker.js new file mode 100644 index 0000000000000000000000000000000000000000..5bbeac4034d0e1af010f4df92a511b2162937078 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/assets-in-worker/worker.js @@ -0,0 +1,18 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import url from "my-special-import"; + +fetch(url) + .then(resp => resp.text()) + .then(text => postMessage(text)); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/a.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/a.js new file mode 100644 index 0000000000000000000000000000000000000000..c6083fc3075ba76e23aad9adf6a7acdebd7b510b --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/a.js @@ -0,0 +1,16 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default function() { + window.parent.postMessage("a", "*"); +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/build/a-Dqjf2iqw.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/build/a-Dqjf2iqw.js new file mode 100644 index 0000000000000000000000000000000000000000..99dc761a47a54f93fee62235626f5f4056fc19ae --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/build/a-Dqjf2iqw.js @@ -0,0 +1,22 @@ +define(['exports'], (function (exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + window.parent.postMessage("a", "*"); + } + + exports.default = a; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/build/a-b9a1bf8d.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/build/a-b9a1bf8d.js new file mode 100644 index 0000000000000000000000000000000000000000..99dc761a47a54f93fee62235626f5f4056fc19ae --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/build/a-b9a1bf8d.js @@ -0,0 +1,22 @@ +define(['exports'], (function (exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + window.parent.postMessage("a", "*"); + } + + exports.default = a; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/build/a-f1483003.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/build/a-f1483003.js new file mode 100644 index 0000000000000000000000000000000000000000..8cdde70d56a45139743ac8304b12c24dbd9e2590 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/build/a-f1483003.js @@ -0,0 +1,22 @@ +define(['exports'], (function (exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + window.parent.postMessage("a", "*"); + } + + exports["default"] = a; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/build/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/build/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..7c8c1340849c111514dafdc65bdf061f5567f2fd --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/build/entry.js @@ -0,0 +1,87 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + require('./a-Dqjf2iqw').then(m => m.default()); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/build/runner.html b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/build/runner.html new file mode 100644 index 0000000000000000000000000000000000000000..e03fb21d61b5110b6f5de9ecd90b27eb839d9936 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/build/runner.html @@ -0,0 +1,15 @@ + + + + diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..8ca29f20b94daa15f540033bb5c72efd709b5b4e --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/dynamic-import/entry.js @@ -0,0 +1,14 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import("./a.js").then(m => m.default()); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/empty.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/empty.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/a.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/a.js new file mode 100644 index 0000000000000000000000000000000000000000..d4ab4f73e0efe6a51105f2aa352c83a001613bb9 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/a.js @@ -0,0 +1,12 @@ +let worker; + +if (self.document) { + worker = new Worker(import.meta.url); +} +if (self.postMessage) { + setTimeout(() => { + postMessage("a"); + }, 500); +} + +export { worker }; diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/a-23c670a1.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/a-23c670a1.js new file mode 100644 index 0000000000000000000000000000000000000000..e2f85d8722d940a1a56618c14bde50130ea50d2c --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/a-23c670a1.js @@ -0,0 +1,83 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['module', 'require', 'exports'], (function (module, require, exports) { 'use strict'; + + exports.worker = void 0; + + if (self.document) { + exports.worker = new Worker(new URL("a-23c670a1.js", module.uri)); + } + if (self.postMessage) { + setTimeout(() => { + postMessage("a"); + }, 500); + } + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/a-9c89b629.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/a-9c89b629.js new file mode 100644 index 0000000000000000000000000000000000000000..af5d03507f80b86963181ed63cbe080d98ba7e82 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/a-9c89b629.js @@ -0,0 +1,85 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['module', 'require', 'exports'], (function (module, require, exports) { 'use strict'; + + exports.worker = void 0; + + if (self.document) { + exports.worker = new Worker(new URL("a-9c89b629.js", module.uri)); + } + if (self.postMessage) { + setTimeout(() => { + postMessage("a"); + }, 500); + } + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/a-CrtsJ3Po.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/a-CrtsJ3Po.js new file mode 100644 index 0000000000000000000000000000000000000000..47f33b99f17a0d107ae262e7939544d6cb087a7e --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/a-CrtsJ3Po.js @@ -0,0 +1,83 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['module', 'require', 'exports'], (function (module, require, exports) { 'use strict'; + + exports.worker = void 0; + + if (self.document) { + exports.worker = new Worker(new URL("a-CrtsJ3Po.js", module.uri)); + } + if (self.postMessage) { + setTimeout(() => { + postMessage("a"); + }, 500); + } + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/a-e0498c05.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/a-e0498c05.js new file mode 100644 index 0000000000000000000000000000000000000000..9632a278a33697ee771383294aba5dc3627b47d6 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/a-e0498c05.js @@ -0,0 +1,83 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['module', 'require', 'exports'], function (module, require, exports) { 'use strict'; + + if (self.document) { + exports.worker = new Worker(new URL("a-e0498c05.js", module.uri)); + } + if (self.postMessage) { + setTimeout(() => { + postMessage("a"); + }, 500); + } + + Object.defineProperty(exports, '__esModule', { value: true }); + +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..55e548a5a149175d5f56beb569697dd19fe3cb9c --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/entry.js @@ -0,0 +1,94 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['./a-CrtsJ3Po'], (function (a) { 'use strict'; + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + if (a.worker) { + a.worker.addEventListener("message", ev => { + window.parent.postMessage(ev.data, "*"); + }); + } + // This should not get bundled into the worker module + if (self.postMessage) { + postMessage("xxx"); + } + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/runner.html b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/runner.html new file mode 100644 index 0000000000000000000000000000000000000000..e2bb221b4ae99dfed4622e906969c24197f1ed04 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/build/runner.html @@ -0,0 +1,15 @@ + + + + diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..eb6b774250a8d0766fd2a51b1345fa7091b218e3 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta-worker/entry.js @@ -0,0 +1,22 @@ +/** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { worker } from "./a.js"; +if (worker) { + worker.addEventListener("message", ev => { + window.parent.postMessage(ev.data, "*"); + }); +} +// This should not get bundled into the worker module +if (self.postMessage) { + postMessage("xxx"); +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/a.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/a.js new file mode 100644 index 0000000000000000000000000000000000000000..eba4ebca2e6dd3b165cc21db2a74d3fc089cd695 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/a.js @@ -0,0 +1,16 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default function() { + window.parent.postMessage(import.meta.url, "*"); +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/build/a-115d949a.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/build/a-115d949a.js new file mode 100644 index 0000000000000000000000000000000000000000..2fe82a47892ae11762e2315238fb175e0399c321 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/build/a-115d949a.js @@ -0,0 +1,22 @@ +define(['module', 'exports'], (function (module, exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + window.parent.postMessage(module.uri, "*"); + } + + exports.default = a; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/build/a-550898d2.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/build/a-550898d2.js new file mode 100644 index 0000000000000000000000000000000000000000..a109f1cfe3845a6002026f8c96262c3ae97016d3 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/build/a-550898d2.js @@ -0,0 +1,22 @@ +define(['module', 'exports'], (function (module, exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + window.parent.postMessage(module.uri, "*"); + } + + exports["default"] = a; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/build/a-BFYklafB.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/build/a-BFYklafB.js new file mode 100644 index 0000000000000000000000000000000000000000..2fe82a47892ae11762e2315238fb175e0399c321 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/build/a-BFYklafB.js @@ -0,0 +1,22 @@ +define(['module', 'exports'], (function (module, exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + window.parent.postMessage(module.uri, "*"); + } + + exports.default = a; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/build/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/build/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..b5ceead1ae8f519db84d090ca3c8f7a4447552e3 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/build/entry.js @@ -0,0 +1,87 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + require('./a-BFYklafB').then(m => m.default()); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/build/runner.html b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/build/runner.html new file mode 100644 index 0000000000000000000000000000000000000000..e03fb21d61b5110b6f5de9ecd90b27eb839d9936 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/build/runner.html @@ -0,0 +1,15 @@ + + + + diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..8ca29f20b94daa15f540033bb5c72efd709b5b4e --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-meta/entry.js @@ -0,0 +1,14 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import("./a.js").then(m => m.default()); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/a.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/a.js new file mode 100644 index 0000000000000000000000000000000000000000..bc95f7b5cabb1d991fdfac55f1f31f7c3bc9d11f --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/a.js @@ -0,0 +1,16 @@ +/** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default function() { + self.postMessage("a"); +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/b.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/b.js new file mode 100644 index 0000000000000000000000000000000000000000..91a3897d120c3e6ddd89775d8e47f4ced5eb246a --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/b.js @@ -0,0 +1,16 @@ +/** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default function() { + return 1; +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/b-725e92c1.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/b-725e92c1.js new file mode 100644 index 0000000000000000000000000000000000000000..fd7c39de6b4ef5701c5bd06e51f2fbac6d910aac --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/b-725e92c1.js @@ -0,0 +1,5 @@ +define([],(function () { 'use strict'; + + + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/b-74a80c25.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/b-74a80c25.js new file mode 100644 index 0000000000000000000000000000000000000000..cca06cf522ebab232386b5c50debe0a5c9eee004 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/b-74a80c25.js @@ -0,0 +1,22 @@ +define(['exports'], (function (exports) { 'use strict'; + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function b() { + return 1; + } + + exports["default"] = b; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..7741df25dbea5e9b9a40b18b2e9d5c9bc54c3235 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/entry.js @@ -0,0 +1,95 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + var workerURL = "worker-Bq6uP7t8.js"; + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + // Set this, so it can be picked up in the test. + self.workerURL = workerURL; + + const w = new Worker(workerURL); + w.addEventListener("message", ev => { + window.parent.postMessage(ev.data, "*"); + }); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/runner.html b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/runner.html new file mode 100644 index 0000000000000000000000000000000000000000..e2bb221b4ae99dfed4622e906969c24197f1ed04 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/runner.html @@ -0,0 +1,15 @@ + + + + diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/worker-Bq6uP7t8.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/worker-Bq6uP7t8.js new file mode 100644 index 0000000000000000000000000000000000000000..8c14f594333916e7f916401066312c1cc8d72ba5 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/worker-Bq6uP7t8.js @@ -0,0 +1,123 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define([],(function () { 'use strict'; + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + self.postMessage("a"); + } + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + a(); + Promise.resolve().then(function () { return b; }); + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + var b = /*#__PURE__*/Object.freeze({ + __proto__: null + }); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/worker-e37d535c.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/worker-e37d535c.js new file mode 100644 index 0000000000000000000000000000000000000000..f674af72818e04a020cad3c66bb062d99572281b --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/worker-e37d535c.js @@ -0,0 +1,105 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + self.postMessage("a"); + } + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + a(); + require('./b-74a80c25'); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/worker-ef1d7c89.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/worker-ef1d7c89.js new file mode 100644 index 0000000000000000000000000000000000000000..3fde8c47498d45fed8ccdb6290815003aac410a7 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/build/worker-ef1d7c89.js @@ -0,0 +1,106 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + self.postMessage("a"); + } + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + a(); + require('./b-725e92c1'); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/config.json b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/config.json new file mode 100644 index 0000000000000000000000000000000000000000..b166bf06af7e0878222be7189b72fb49ce1ab99d --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/config.json @@ -0,0 +1,3 @@ +{ + "urlLoaderScheme": "fancy-custom-scheme" +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..ba84280506cbfdc0a7ea5f7ae57896e3ca837f8f --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/entry.js @@ -0,0 +1,21 @@ +/** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import workerURL from "fancy-custom-scheme:./worker.js"; + +// Set this, so it can be picked up in the test. +self.workerURL = workerURL; + +const w = new Worker(workerURL); +w.addEventListener("message", ev => { + window.parent.postMessage(ev.data, "*"); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/worker.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/worker.js new file mode 100644 index 0000000000000000000000000000000000000000..33604ae290f22925b28a200779dc94c11a408e3b --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url-custom-scheme/worker.js @@ -0,0 +1,17 @@ +/** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import a from "./a.js"; + +a(); +import("./b.js"); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/a.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/a.js new file mode 100644 index 0000000000000000000000000000000000000000..bc95f7b5cabb1d991fdfac55f1f31f7c3bc9d11f --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/a.js @@ -0,0 +1,16 @@ +/** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default function() { + self.postMessage("a"); +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/b.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/b.js new file mode 100644 index 0000000000000000000000000000000000000000..91a3897d120c3e6ddd89775d8e47f4ced5eb246a --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/b.js @@ -0,0 +1,16 @@ +/** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default function() { + return 1; +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/b-64a9d830.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/b-64a9d830.js new file mode 100644 index 0000000000000000000000000000000000000000..cca06cf522ebab232386b5c50debe0a5c9eee004 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/b-64a9d830.js @@ -0,0 +1,22 @@ +define(['exports'], (function (exports) { 'use strict'; + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function b() { + return 1; + } + + exports["default"] = b; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/b-725e92c1.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/b-725e92c1.js new file mode 100644 index 0000000000000000000000000000000000000000..fd7c39de6b4ef5701c5bd06e51f2fbac6d910aac --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/b-725e92c1.js @@ -0,0 +1,5 @@ +define([],(function () { 'use strict'; + + + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..7741df25dbea5e9b9a40b18b2e9d5c9bc54c3235 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/entry.js @@ -0,0 +1,95 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + var workerURL = "worker-Bq6uP7t8.js"; + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + // Set this, so it can be picked up in the test. + self.workerURL = workerURL; + + const w = new Worker(workerURL); + w.addEventListener("message", ev => { + window.parent.postMessage(ev.data, "*"); + }); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/runner.html b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/runner.html new file mode 100644 index 0000000000000000000000000000000000000000..e2bb221b4ae99dfed4622e906969c24197f1ed04 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/runner.html @@ -0,0 +1,15 @@ + + + + diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/worker-Bq6uP7t8.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/worker-Bq6uP7t8.js new file mode 100644 index 0000000000000000000000000000000000000000..8c14f594333916e7f916401066312c1cc8d72ba5 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/worker-Bq6uP7t8.js @@ -0,0 +1,123 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define([],(function () { 'use strict'; + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + self.postMessage("a"); + } + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + a(); + Promise.resolve().then(function () { return b; }); + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + var b = /*#__PURE__*/Object.freeze({ + __proto__: null + }); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/worker-ef1d7c89.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/worker-ef1d7c89.js new file mode 100644 index 0000000000000000000000000000000000000000..3fde8c47498d45fed8ccdb6290815003aac410a7 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/worker-ef1d7c89.js @@ -0,0 +1,106 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + self.postMessage("a"); + } + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + a(); + require('./b-725e92c1'); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/worker-f5690442.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/worker-f5690442.js new file mode 100644 index 0000000000000000000000000000000000000000..74cf68f02de08a254492b29cbc893c4311edffe4 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/build/worker-f5690442.js @@ -0,0 +1,105 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + self.postMessage("a"); + } + + /** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + a(); + require('./b-64a9d830'); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..a18aac324e2b4ebd851043b0649bd40cbfc45d61 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/entry.js @@ -0,0 +1,21 @@ +/** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import workerURL from "omt:./worker.js"; + +// Set this, so it can be picked up in the test. +self.workerURL = workerURL; + +const w = new Worker(workerURL); +w.addEventListener("message", ev => { + window.parent.postMessage(ev.data, "*"); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/worker.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/worker.js new file mode 100644 index 0000000000000000000000000000000000000000..33604ae290f22925b28a200779dc94c11a408e3b --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/import-worker-url/worker.js @@ -0,0 +1,17 @@ +/** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import a from "./a.js"; + +a(); +import("./b.js"); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/a.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/a.js new file mode 100644 index 0000000000000000000000000000000000000000..de48511d69fb5beb0d7475e9cf4b189ead36b446 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/a.js @@ -0,0 +1,20 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default async function(f) { + self.postMessage(f()); +} + +export function someValue() { + return self.String("a"); +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/b.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/b.js new file mode 100644 index 0000000000000000000000000000000000000000..b79b30433c444c5b872589a01ba18dca463358b6 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/b.js @@ -0,0 +1,20 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Import for side-effects (of which there are none) +// to make sure that a.js gets its own chunk. +import {someValue} from "./a.js"; + +export default function() { + return someValue(); +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/b-8d8ba280.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/b-8d8ba280.js new file mode 100644 index 0000000000000000000000000000000000000000..4e10bcfbb0fce874d2f9a96efe1c9419c475cbda --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/b-8d8ba280.js @@ -0,0 +1,20 @@ +import { s as someValue } from './worker-50885fe8.js'; + +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function b() { + return someValue(); +} + +export { b as default }; diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/b-ZxqdL95j.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/b-ZxqdL95j.js new file mode 100644 index 0000000000000000000000000000000000000000..5398935b96b9ba571584f52e69038357c03f258f --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/b-ZxqdL95j.js @@ -0,0 +1,21 @@ +import { s as someValue } from './worker-DWbjHYfx.js'; + +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +function b() { + return someValue(); +} + +export { b as default }; diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/b-f6cfc895.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/b-f6cfc895.js new file mode 100644 index 0000000000000000000000000000000000000000..b061c1959b0881d13778be66393e8236c28c736a --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/b-f6cfc895.js @@ -0,0 +1,21 @@ +import { s as someValue } from './worker-9fb0618d.js'; + +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +function b() { + return someValue(); +} + +export { b as default }; diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..8dfe6f180cafe7634b0b402794b0698f8a777037 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/entry.js @@ -0,0 +1,17 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const w = new Worker(new URL("worker-DWbjHYfx.js", import.meta.url), { type: "module" }); +w.addEventListener("message", ev => { + window.parent.postMessage(ev.data, "*"); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/runner.html b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/runner.html new file mode 100644 index 0000000000000000000000000000000000000000..e84f4ed174d7789c8592f6f086368fd39bc15531 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/runner.html @@ -0,0 +1,15 @@ + + + + diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/worker-41a1c649.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/worker-41a1c649.js new file mode 100644 index 0000000000000000000000000000000000000000..74e3f6ad3d1a4d1a8b7dc0c614d10045159557f4 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/worker-41a1c649.js @@ -0,0 +1 @@ +import './worker-50885fe8.js'; diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/worker-50885fe8.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/worker-50885fe8.js new file mode 100644 index 0000000000000000000000000000000000000000..2d2d144f4389a290a079e4b576b0d5e8f1676f90 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/worker-50885fe8.js @@ -0,0 +1,38 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +async function a(f) { + self.postMessage(f()); +} + +function someValue() { + return self.String("a"); +} + +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import('./b-8d8ba280.js').then(({default: f}) => { + a(f); +}); + +export { someValue as s }; diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/worker-9fb0618d.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/worker-9fb0618d.js new file mode 100644 index 0000000000000000000000000000000000000000..a52b095d783b8dc6f286785137a1551422a6ef5a --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/worker-9fb0618d.js @@ -0,0 +1,39 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +async function a(f) { + self.postMessage(f()); +} + +function someValue() { + return self.String("a"); +} + +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import('./b-f6cfc895.js').then(({default: f}) => { + a(f); +}); + +export { someValue as s }; diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/worker-DWbjHYfx.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/worker-DWbjHYfx.js new file mode 100644 index 0000000000000000000000000000000000000000..2e9f6a8927132b644802800dba199db358bbd2d2 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/build/worker-DWbjHYfx.js @@ -0,0 +1,39 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +async function a(f) { + self.postMessage(f()); +} + +function someValue() { + return self.String("a"); +} + +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import('./b-ZxqdL95j.js').then(({default: f}) => { + a(f); +}); + +export { someValue as s }; diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..66a8c29e1ce4c4f2aaee2a19b3bb6fbcc9f3d01d --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/entry.js @@ -0,0 +1,17 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const w = new Worker("./worker.js", { type: "module" }); +w.addEventListener("message", ev => { + window.parent.postMessage(ev.data, "*"); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/rollup.config.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/rollup.config.js new file mode 100644 index 0000000000000000000000000000000000000000..9ae8e5a4d988cca624d8e3f5571156d4f3249c69 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/rollup.config.js @@ -0,0 +1,4 @@ +module.exports = (config, outputOptions, omt) => { + outputOptions.format = "esm"; + config.plugins = [omt()]; +}; diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/worker.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/worker.js new file mode 100644 index 0000000000000000000000000000000000000000..d4ed3bc1f9e8974749928f4d9d6ec555af4f9ab3 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/module-worker/worker.js @@ -0,0 +1,17 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import a from "./a.js"; +import("./b.js").then(({default: f}) => { + a(f); +}) diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/a.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/a.js new file mode 100644 index 0000000000000000000000000000000000000000..66d34f7b82f4dc99e3c1f04c873e4a3e843ad027 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/a.js @@ -0,0 +1,16 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default function() { + self.postMessage("a"); +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/b.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/b.js new file mode 100644 index 0000000000000000000000000000000000000000..0386421bc33c93e762b7e9ea1ffa70679b2691f0 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/b.js @@ -0,0 +1,16 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default function() { + self.postMessage("b"); +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/b-Dok_VKGN.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/b-Dok_VKGN.js new file mode 100644 index 0000000000000000000000000000000000000000..d19a1798ece60758e277aab301f6a97d542572cd --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/b-Dok_VKGN.js @@ -0,0 +1,22 @@ +define(['exports'], (function (exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function b() { + self.postMessage("b"); + } + + exports.default = b; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/b-e9bb9f94.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/b-e9bb9f94.js new file mode 100644 index 0000000000000000000000000000000000000000..d19a1798ece60758e277aab301f6a97d542572cd --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/b-e9bb9f94.js @@ -0,0 +1,22 @@ +define(['exports'], (function (exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function b() { + self.postMessage("b"); + } + + exports.default = b; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/b-f31d0f9f.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/b-f31d0f9f.js new file mode 100644 index 0000000000000000000000000000000000000000..7465bed7cbdeb5872f646a89abf7582d28b5ded8 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/b-f31d0f9f.js @@ -0,0 +1,22 @@ +define(['exports'], (function (exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function b() { + self.postMessage("b"); + } + + exports["default"] = b; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..5a2c0aa33b8ae162fea2aa16980a44781900b9d9 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/entry.js @@ -0,0 +1,107 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['module', 'require'], (function (module, require) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + async function run() { + await new Promise(resolve => { + const w = new Worker(new URL("worker_a-DtsyxKtN.js", module.uri)); + w.addEventListener("message", ev => { + if (ev.data === "a") { + resolve(); + } + }); + }); + await new Promise(resolve => { + const w = new Worker(new URL("worker_b-CG60Lcld.js", module.uri)); + w.addEventListener("message", ev => { + if (ev.data === "b") { + resolve(); + } + }); + }); + window.parent.postMessage("a", "*"); + } + + run(); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/runner.html b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/runner.html new file mode 100644 index 0000000000000000000000000000000000000000..e03fb21d61b5110b6f5de9ecd90b27eb839d9936 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/runner.html @@ -0,0 +1,15 @@ + + + + diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_a-25924b0d.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_a-25924b0d.js new file mode 100644 index 0000000000000000000000000000000000000000..01edb4189e77e7924dd4f65fb66f9249402f0416 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_a-25924b0d.js @@ -0,0 +1,105 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define([],(function () { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + self.postMessage("a"); + } + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + a(); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_a-DtsyxKtN.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_a-DtsyxKtN.js new file mode 100644 index 0000000000000000000000000000000000000000..01edb4189e77e7924dd4f65fb66f9249402f0416 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_a-DtsyxKtN.js @@ -0,0 +1,105 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define([],(function () { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + self.postMessage("a"); + } + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + a(); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_a-b8e0ca8d.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_a-b8e0ca8d.js new file mode 100644 index 0000000000000000000000000000000000000000..9aaac01462bfa3f29484da9cf1afaaa90a7e9c0f --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_a-b8e0ca8d.js @@ -0,0 +1,104 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define([],(function () { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + self.postMessage("a"); + } + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + a(); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_b-477edb2c.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_b-477edb2c.js new file mode 100644 index 0000000000000000000000000000000000000000..d6f9f44c1f6f37faf5fd56c14672297547bc172e --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_b-477edb2c.js @@ -0,0 +1,91 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + async function run() { + const { default: b } = await require('./b-f31d0f9f'); + b(); + } + run(); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_b-60981e1f.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_b-60981e1f.js new file mode 100644 index 0000000000000000000000000000000000000000..9ea8c6ec58339f8da46d4f2bd3585d028802e599 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_b-60981e1f.js @@ -0,0 +1,91 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + async function run() { + const { default: b } = await require('./b-e9bb9f94'); + b(); + } + run(); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_b-CG60Lcld.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_b-CG60Lcld.js new file mode 100644 index 0000000000000000000000000000000000000000..4230978047e65ebafbf4ade7254afb54b7aa3dd3 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/build/worker_b-CG60Lcld.js @@ -0,0 +1,91 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + async function run() { + const { default: b } = await require('./b-Dok_VKGN'); + b(); + } + run(); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..f5d3a46914b22ef42eedf938e1000046735de2fb --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/entry.js @@ -0,0 +1,34 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +async function run() { + await new Promise(resolve => { + const w = new Worker("./worker_a.js"); + w.addEventListener("message", ev => { + if (ev.data === "a") { + resolve(); + } + }); + }); + await new Promise(resolve => { + const w = new Worker("./worker_b.js"); + w.addEventListener("message", ev => { + if (ev.data === "b") { + resolve(); + } + }); + }); + window.parent.postMessage("a", "*"); +} + +run(); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/worker_a.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/worker_a.js new file mode 100644 index 0000000000000000000000000000000000000000..24da4763ae35134c95c9e6c201df3a308e0bf526 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/worker_a.js @@ -0,0 +1,16 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import a from "./a.js"; + +a(); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/worker_b.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/worker_b.js new file mode 100644 index 0000000000000000000000000000000000000000..bce80e092033f697b046998a499cf3ad8f3432d8 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/more-workers/worker_b.js @@ -0,0 +1,18 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +async function run() { + const { default: b } = await import("./b.js"); + b(); +} +run(); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/a.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/a.js new file mode 100644 index 0000000000000000000000000000000000000000..c6083fc3075ba76e23aad9adf6a7acdebd7b510b --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/a.js @@ -0,0 +1,16 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default function() { + window.parent.postMessage("a", "*"); +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/build/a-1fb502b9.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/build/a-1fb502b9.js new file mode 100644 index 0000000000000000000000000000000000000000..8cdde70d56a45139743ac8304b12c24dbd9e2590 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/build/a-1fb502b9.js @@ -0,0 +1,22 @@ +define(['exports'], (function (exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + window.parent.postMessage("a", "*"); + } + + exports["default"] = a; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/build/a-Dqjf2iqw.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/build/a-Dqjf2iqw.js new file mode 100644 index 0000000000000000000000000000000000000000..99dc761a47a54f93fee62235626f5f4056fc19ae --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/build/a-Dqjf2iqw.js @@ -0,0 +1,22 @@ +define(['exports'], (function (exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + window.parent.postMessage("a", "*"); + } + + exports.default = a; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/build/a-b9a1bf8d.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/build/a-b9a1bf8d.js new file mode 100644 index 0000000000000000000000000000000000000000..99dc761a47a54f93fee62235626f5f4056fc19ae --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/build/a-b9a1bf8d.js @@ -0,0 +1,22 @@ +define(['exports'], (function (exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function a() { + window.parent.postMessage("a", "*"); + } + + exports.default = a; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/build/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/build/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..7c8c1340849c111514dafdc65bdf061f5567f2fd --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/build/entry.js @@ -0,0 +1,87 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + require('./a-Dqjf2iqw').then(m => m.default()); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/build/runner.html b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/build/runner.html new file mode 100644 index 0000000000000000000000000000000000000000..e03fb21d61b5110b6f5de9ecd90b27eb839d9936 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/build/runner.html @@ -0,0 +1,15 @@ + + + + diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/config.json b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/config.json new file mode 100644 index 0000000000000000000000000000000000000000..25353637e92a1d0c955952e238b777c6ff1df267 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/config.json @@ -0,0 +1,3 @@ +{ + "publicPath": "/base/tests/fixtures/public-path/build" +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..8ca29f20b94daa15f540033bb5c72efd709b5b4e --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/public-path/entry.js @@ -0,0 +1,14 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import("./a.js").then(m => m.default()); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/simple-bundle/a.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/simple-bundle/a.js new file mode 100644 index 0000000000000000000000000000000000000000..c6083fc3075ba76e23aad9adf6a7acdebd7b510b --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/simple-bundle/a.js @@ -0,0 +1,16 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default function() { + window.parent.postMessage("a", "*"); +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/simple-bundle/build/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/simple-bundle/build/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..35f1690e5782a0908e4795f251a65a040ad885d2 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/simple-bundle/build/entry.js @@ -0,0 +1,105 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define([],(function () { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function A() { + window.parent.postMessage("a", "*"); + } + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + A(); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/simple-bundle/build/runner.html b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/simple-bundle/build/runner.html new file mode 100644 index 0000000000000000000000000000000000000000..e03fb21d61b5110b6f5de9ecd90b27eb839d9936 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/simple-bundle/build/runner.html @@ -0,0 +1,15 @@ + + + + diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/simple-bundle/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/simple-bundle/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..376e10aa2176b4fac5395740e21855b3821141c5 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/simple-bundle/entry.js @@ -0,0 +1,16 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import A from "./a.js"; + +A(); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/single-default/a.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/single-default/a.js new file mode 100644 index 0000000000000000000000000000000000000000..d23b6a0731d9a3c04b1f87c296db5eaa2eaf5d71 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/single-default/a.js @@ -0,0 +1,14 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default 4; diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/single-default/build/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/single-default/build/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..4b4dfe8322005d60fec2b4c738841fde42309b25 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/single-default/build/entry.js @@ -0,0 +1,103 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define([],(function () { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + var A = 4; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + window.parent.postMessage(A, "*"); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/single-default/build/runner.html b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/single-default/build/runner.html new file mode 100644 index 0000000000000000000000000000000000000000..e03fb21d61b5110b6f5de9ecd90b27eb839d9936 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/single-default/build/runner.html @@ -0,0 +1,15 @@ + + + + diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/single-default/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/single-default/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..da66239b0d0f9b3657cf6749eb855360d91343be --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/single-default/entry.js @@ -0,0 +1,16 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import A from "./a.js"; + +window.parent.postMessage(A, "*"); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/a.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/a.js new file mode 100644 index 0000000000000000000000000000000000000000..5e2bcc975ed0df6cb6e967bcf9ec51836e429646 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/a.js @@ -0,0 +1,17 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default async function() { + const { default: f } = await import("./b.js"); + self.postMessage(f()); +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/b.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/b.js new file mode 100644 index 0000000000000000000000000000000000000000..f13897af7e113daa0dfaf5155cb1bf35da3b54ab --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/b.js @@ -0,0 +1,16 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default function() { + return "a"; +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/b-258f8a6b.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/b-258f8a6b.js new file mode 100644 index 0000000000000000000000000000000000000000..ac180186db35badd9344f97c6cd4bf57e20e6785 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/b-258f8a6b.js @@ -0,0 +1,22 @@ +define(['exports'], (function (exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function b() { + return "a"; + } + + exports.default = b; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/b-8c5ed926.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/b-8c5ed926.js new file mode 100644 index 0000000000000000000000000000000000000000..39b652228be0826c65da4d80f7f8af6a1dddb5ab --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/b-8c5ed926.js @@ -0,0 +1,22 @@ +define(['exports'], (function (exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function b() { + return "a"; + } + + exports["default"] = b; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/b-CNJP1XvI.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/b-CNJP1XvI.js new file mode 100644 index 0000000000000000000000000000000000000000..ac180186db35badd9344f97c6cd4bf57e20e6785 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/b-CNJP1XvI.js @@ -0,0 +1,22 @@ +define(['exports'], (function (exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function b() { + return "a"; + } + + exports.default = b; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..cbf2b4f9c1db4313c0a74a0a6217377a70889207 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/entry.js @@ -0,0 +1,91 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['module', 'require'], (function (module, require) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + // The type module should get removed for AMD format! + const w = new Worker(new URL("worker-S2Vh56Q-.js", module.uri)); + w.addEventListener("message", ev => { + window.parent.postMessage(ev.data, "*"); + }); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/runner.html b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/runner.html new file mode 100644 index 0000000000000000000000000000000000000000..e03fb21d61b5110b6f5de9ecd90b27eb839d9936 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/runner.html @@ -0,0 +1,15 @@ + + + + diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/worker-9a661671.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/worker-9a661671.js new file mode 100644 index 0000000000000000000000000000000000000000..41f73e513580c899ab21b72126b2b20300510922 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/worker-9a661671.js @@ -0,0 +1,105 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + async function a() { + const { default: f } = await require('./b-8c5ed926'); + self.postMessage(f()); + } + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + a(); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/worker-S2Vh56Q-.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/worker-S2Vh56Q-.js new file mode 100644 index 0000000000000000000000000000000000000000..bcbc3bce277ba517550cc9ab6182c665edf25085 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/worker-S2Vh56Q-.js @@ -0,0 +1,106 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + async function a() { + const { default: f } = await require('./b-CNJP1XvI'); + self.postMessage(f()); + } + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + a(); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/worker-e833ae5d.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/worker-e833ae5d.js new file mode 100644 index 0000000000000000000000000000000000000000..739f9bc44ff2b3c867ca70b5579bc189e678101e --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/build/worker-e833ae5d.js @@ -0,0 +1,106 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + async function a() { + const { default: f } = await require('./b-258f8a6b'); + self.postMessage(f()); + } + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + a(); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..f58c32547e07c58188191f3c92597f0b5642c978 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/entry.js @@ -0,0 +1,20 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// The type module should get removed for AMD format! +const w = new Worker(new URL("worker.js", import.meta.url), { + type: "module" +}); +w.addEventListener("message", ev => { + window.parent.postMessage(ev.data, "*"); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/worker.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/worker.js new file mode 100644 index 0000000000000000000000000000000000000000..24da4763ae35134c95c9e6c201df3a308e0bf526 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/url-import-meta-worker/worker.js @@ -0,0 +1,16 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import a from "./a.js"; + +a(); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/a.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/a.js new file mode 100644 index 0000000000000000000000000000000000000000..5e2bcc975ed0df6cb6e967bcf9ec51836e429646 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/a.js @@ -0,0 +1,17 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default async function() { + const { default: f } = await import("./b.js"); + self.postMessage(f()); +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/b.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/b.js new file mode 100644 index 0000000000000000000000000000000000000000..f13897af7e113daa0dfaf5155cb1bf35da3b54ab --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/b.js @@ -0,0 +1,16 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default function() { + return "a"; +} diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/b-258f8a6b.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/b-258f8a6b.js new file mode 100644 index 0000000000000000000000000000000000000000..ac180186db35badd9344f97c6cd4bf57e20e6785 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/b-258f8a6b.js @@ -0,0 +1,22 @@ +define(['exports'], (function (exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function b() { + return "a"; + } + + exports.default = b; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/b-CNJP1XvI.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/b-CNJP1XvI.js new file mode 100644 index 0000000000000000000000000000000000000000..ac180186db35badd9344f97c6cd4bf57e20e6785 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/b-CNJP1XvI.js @@ -0,0 +1,22 @@ +define(['exports'], (function (exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function b() { + return "a"; + } + + exports.default = b; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/b-a9f43d76.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/b-a9f43d76.js new file mode 100644 index 0000000000000000000000000000000000000000..39b652228be0826c65da4d80f7f8af6a1dddb5ab --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/b-a9f43d76.js @@ -0,0 +1,22 @@ +define(['exports'], (function (exports) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + function b() { + return "a"; + } + + exports["default"] = b; + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..cbf2b4f9c1db4313c0a74a0a6217377a70889207 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/entry.js @@ -0,0 +1,91 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['module', 'require'], (function (module, require) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + // The type module should get removed for AMD format! + const w = new Worker(new URL("worker-S2Vh56Q-.js", module.uri)); + w.addEventListener("message", ev => { + window.parent.postMessage(ev.data, "*"); + }); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/runner.html b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/runner.html new file mode 100644 index 0000000000000000000000000000000000000000..e03fb21d61b5110b6f5de9ecd90b27eb839d9936 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/runner.html @@ -0,0 +1,15 @@ + + + + diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/worker-S2Vh56Q-.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/worker-S2Vh56Q-.js new file mode 100644 index 0000000000000000000000000000000000000000..bcbc3bce277ba517550cc9ab6182c665edf25085 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/worker-S2Vh56Q-.js @@ -0,0 +1,106 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + async function a() { + const { default: f } = await require('./b-CNJP1XvI'); + self.postMessage(f()); + } + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + a(); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/worker-b4897a54.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/worker-b4897a54.js new file mode 100644 index 0000000000000000000000000000000000000000..67c44a2ef20261a7ae8fb9df2941a21931e6943f --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/worker-b4897a54.js @@ -0,0 +1,105 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + async function a() { + const { default: f } = await require('./b-a9f43d76'); + self.postMessage(f()); + } + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + a(); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/worker-e833ae5d.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/worker-e833ae5d.js new file mode 100644 index 0000000000000000000000000000000000000000..739f9bc44ff2b3c867ca70b5579bc189e678101e --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/build/worker-e833ae5d.js @@ -0,0 +1,106 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// If the loader is already loaded, just stop. +if (!self.define) { + let registry = {}; + + // Used for `eval` and `importScripts` where we can't get script URL by other means. + // In both cases, it's safe to use a global var because those functions are synchronous. + let nextDefineUri; + + const singleRequire = (uri, parentUri) => { + uri = new URL(uri + ".js", parentUri).href; + return registry[uri] || ( + + new Promise(resolve => { + if ("document" in self) { + const script = document.createElement("script"); + script.src = uri; + script.onload = resolve; + document.head.appendChild(script); + } else { + nextDefineUri = uri; + importScripts(uri); + resolve(); + } + }) + + .then(() => { + let promise = registry[uri]; + if (!promise) { + throw new Error(`Module ${uri} didn’t register its module`); + } + return promise; + }) + ); + }; + + self.define = (depsNames, factory) => { + const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href; + if (registry[uri]) { + // Module is already loading or loaded. + return; + } + let exports = {}; + const require = depUri => singleRequire(depUri, uri); + const specialDeps = { + module: { uri }, + exports, + require + }; + registry[uri] = Promise.all(depsNames.map( + depName => specialDeps[depName] || require(depName) + )).then(deps => { + factory(...deps); + return exports; + }); + }; +} +define(['require'], (function (require) { 'use strict'; + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + async function a() { + const { default: f } = await require('./b-258f8a6b'); + self.postMessage(f()); + } + + /** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + a(); + +})); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/entry.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..3598368665f732f2ddec4690e64845adb7d0036b --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/entry.js @@ -0,0 +1,18 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// The type module should get removed for AMD format! +const w = new Worker("./worker.js", { type: "module" }); +w.addEventListener("message", ev => { + window.parent.postMessage(ev.data, "*"); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/worker.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/worker.js new file mode 100644 index 0000000000000000000000000000000000000000..24da4763ae35134c95c9e6c201df3a308e0bf526 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/fixtures/worker/worker.js @@ -0,0 +1,16 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import a from "./a.js"; + +a(); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/import-meta-worker.test.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/import-meta-worker.test.js new file mode 100644 index 0000000000000000000000000000000000000000..80574616182afb413c94ded583079aae9d3959c2 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/import-meta-worker.test.js @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +describe("omt: use import.meta.url in Worker constructor", function() { + const runner = "/base/tests/fixtures/import-meta-worker/build/runner.html"; + + beforeEach(function() { + this.ifr = document.createElement("iframe"); + document.body.append(this.ifr); + }); + + afterEach(function() { + this.ifr.remove(); + }); + + it("loads itself as a module", function(done) { + window.addEventListener("message", function l(ev) { + if (ev.data === "a") { + window.removeEventListener("message", l); + done(); + } else { + done(`Unexpected message! ${ev.data}`); + } + }); + this.ifr.src = runner; + }); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/import-meta.test.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/import-meta.test.js new file mode 100644 index 0000000000000000000000000000000000000000..33006631b981302309acae97c8eebbc6de86f920 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/import-meta.test.js @@ -0,0 +1,33 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +describe("import.meta", function() { + beforeEach(function() { + this.ifr = document.createElement("iframe"); + document.body.append(this.ifr); + }); + + afterEach(function() { + this.ifr.remove(); + }); + + it("loads transpiled modules", function(done) { + window.addEventListener("message", function l(ev) { + if (/^https?:\/\/.+\.js$/.test(ev.data)) { + window.removeEventListener("message", l); + done(); + } + }); + this.ifr.src = "/base/tests/fixtures/import-meta/build/runner.html"; + }); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/import-worker-url-custom-scheme.test.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/import-worker-url-custom-scheme.test.js new file mode 100644 index 0000000000000000000000000000000000000000..c5374df3f5e2cb249ae15a0b583b32d7333ad71f --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/import-worker-url-custom-scheme.test.js @@ -0,0 +1,42 @@ +/** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +describe("omt: URL import with custom scheme", function() { + const runner = + "/base/tests/fixtures/import-worker-url-custom-scheme/build/runner.html"; + + beforeEach(function() { + this.ifr = document.createElement("iframe"); + document.body.append(this.ifr); + }); + + afterEach(function() { + this.ifr.remove(); + }); + + it("imports as string", async function() { + this.ifr.src = runner; + await new Promise(resolve => this.ifr.addEventListener("load", resolve)); + assert.typeOf(this.ifr.contentWindow.workerURL, "string"); + }); + + it("loads transpiled modules", function(done) { + window.addEventListener("message", function l(ev) { + if (ev.data === "a") { + window.removeEventListener("message", l); + done(); + } + }); + this.ifr.src = runner; + }); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/import-worker-url.test.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/import-worker-url.test.js new file mode 100644 index 0000000000000000000000000000000000000000..8483ae6ec87ba56b2c85aca326d386708e424869 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/import-worker-url.test.js @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +describe("omt: URL import", function() { + const runner = "/base/tests/fixtures/import-worker-url/build/runner.html"; + + beforeEach(function() { + this.ifr = document.createElement("iframe"); + document.body.append(this.ifr); + }); + + afterEach(function() { + this.ifr.remove(); + }); + + it("imports as string", async function() { + this.ifr.src = runner; + await new Promise(resolve => this.ifr.addEventListener("load", resolve)); + assert.typeOf(this.ifr.contentWindow.workerURL, "string"); + }); + + it("loads transpiled modules", function(done) { + window.addEventListener("message", function l(ev) { + if (ev.data === "a") { + window.removeEventListener("message", l); + done(); + } + }); + this.ifr.src = runner; + }); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/module-worker.test.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/module-worker.test.js new file mode 100644 index 0000000000000000000000000000000000000000..396754b0ecba2fa6c9fbe681ddb276237e0b7b22 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/module-worker.test.js @@ -0,0 +1,47 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +describe("Module Worker", function() { + const blob = new Blob([""], { type: "text/javascript" }); + const url = URL.createObjectURL(blob); + let supportsModuleWorker = false; + const options = { + get type() { + supportsModuleWorker = true; + } + }; + new Worker(url, options).terminate(); + URL.revokeObjectURL(url); + + beforeEach(function() { + if (!supportsModuleWorker) { + return this.skip(); + } + this.ifr = document.createElement("iframe"); + document.body.append(this.ifr); + }); + + afterEach(function() { + this.ifr.remove(); + }); + + it("work", function(done) { + window.addEventListener("message", function l(ev) { + if (ev.data === "a") { + window.removeEventListener("message", l); + done(); + } + }); + this.ifr.src = "/base/tests/fixtures/module-worker/build/runner.html"; + }); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/more-workers.test.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/more-workers.test.js new file mode 100644 index 0000000000000000000000000000000000000000..96f2faa8677bf5fbdc47efcbb523ca9a4d9cf2f8 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/more-workers.test.js @@ -0,0 +1,33 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +describe("Worker", function() { + beforeEach(function() { + this.ifr = document.createElement("iframe"); + document.body.append(this.ifr); + }); + + afterEach(function() { + this.ifr.remove(); + }); + + it("can load multiple workers", function(done) { + window.addEventListener("message", function l(ev) { + if (ev.data === "a") { + window.removeEventListener("message", l); + done(); + } + }); + this.ifr.src = "/base/tests/fixtures/more-workers/build/runner.html"; + }); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/public-path.test.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/public-path.test.js new file mode 100644 index 0000000000000000000000000000000000000000..01a6b346b55df7946d483d16065d786e50824062 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/public-path.test.js @@ -0,0 +1,33 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +describe("Public Path", function() { + beforeEach(function() { + this.ifr = document.createElement("iframe"); + document.body.append(this.ifr); + }); + + afterEach(function() { + this.ifr.remove(); + }); + + it("loads transpiled modules", function(done) { + window.addEventListener("message", function l(ev) { + if (ev.data === "a") { + window.removeEventListener("message", l); + done(); + } + }); + this.ifr.src = "/base/tests/fixtures/public-path/build/runner.html"; + }); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/simple-bundle.test.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/simple-bundle.test.js new file mode 100644 index 0000000000000000000000000000000000000000..96f599d2251e09e0f86ac706d2d7907dcda87653 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/simple-bundle.test.js @@ -0,0 +1,33 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +describe("Simple bundle", function() { + beforeEach(function() { + this.ifr = document.createElement("iframe"); + document.body.append(this.ifr); + }); + + afterEach(function() { + this.ifr.remove(); + }); + + it("loads transpiled modules", function(done) { + window.addEventListener("message", function l(ev) { + if (ev.data === "a") { + window.removeEventListener("message", l); + done(); + } + }); + this.ifr.src = "/base/tests/fixtures/simple-bundle/build/runner.html"; + }); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/single-default.test.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/single-default.test.js new file mode 100644 index 0000000000000000000000000000000000000000..25f1f5924df93cfafbb2296d521c068b5ca9731c --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/single-default.test.js @@ -0,0 +1,33 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +describe("Single default const export", function() { + beforeEach(function() { + this.ifr = document.createElement("iframe"); + document.body.append(this.ifr); + }); + + afterEach(function() { + this.ifr.remove(); + }); + + it("loads transpiled modules", function(done) { + window.addEventListener("message", function l(ev) { + if (ev.data === 4) { + window.removeEventListener("message", l); + done(); + } + }); + this.ifr.src = "/base/tests/fixtures/single-default/build/runner.html"; + }); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/url-import-meta-worker.test.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/url-import-meta-worker.test.js new file mode 100644 index 0000000000000000000000000000000000000000..ed474dc0035516204f3b24fc2d2d311d9e951dc8 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/url-import-meta-worker.test.js @@ -0,0 +1,34 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +describe("Worker", function() { + beforeEach(function() { + this.ifr = document.createElement("iframe"); + document.body.append(this.ifr); + }); + + afterEach(function() { + this.ifr.remove(); + }); + + it("loads module-relative worker paths", function(done) { + window.addEventListener("message", function l(ev) { + if (ev.data === "a") { + window.removeEventListener("message", l); + done(); + } + }); + this.ifr.src = + "/base/tests/fixtures/url-import-meta-worker/build/runner.html"; + }); +}); diff --git a/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/worker.test.js b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/worker.test.js new file mode 100644 index 0000000000000000000000000000000000000000..5e1c5b089fff4bfb48b0f65f0191f0f381e0c424 --- /dev/null +++ b/tools/ui/node_modules/@trickfilm400/rollup-plugin-off-main-thread/tests/worker.test.js @@ -0,0 +1,33 @@ +/** + * Copyright 2018 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +describe("Worker", function() { + beforeEach(function() { + this.ifr = document.createElement("iframe"); + document.body.append(this.ifr); + }); + + afterEach(function() { + this.ifr.remove(); + }); + + it("loads transpiled modules", function(done) { + window.addEventListener("message", function l(ev) { + if (ev.data === "a") { + window.removeEventListener("message", l); + done(); + } + }); + this.ifr.src = "/base/tests/fixtures/worker/build/runner.html"; + }); +}); diff --git a/tools/ui/node_modules/@types/aria-query/LICENSE b/tools/ui/node_modules/@types/aria-query/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/aria-query/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/aria-query/README.md b/tools/ui/node_modules/@types/aria-query/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4f98f5eb2ec25ede456d74bf21f2f225249ffe82 --- /dev/null +++ b/tools/ui/node_modules/@types/aria-query/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/aria-query` + +# Summary +This package contains type definitions for aria-query (https://github.com/A11yance/aria-query#readme). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/aria-query. + +### Additional Details + * Last updated: Mon, 06 Nov 2023 22:41:04 GMT + * Dependencies: none + +# Credits +These definitions were written by [Sebastian Silbermann](https://github.com/eps1lon). diff --git a/tools/ui/node_modules/@types/aria-query/index.d.ts b/tools/ui/node_modules/@types/aria-query/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bde27e5260befe11f6e12abbbd6ada3f57f1abb4 --- /dev/null +++ b/tools/ui/node_modules/@types/aria-query/index.d.ts @@ -0,0 +1,343 @@ +// Disable automatic exports. +export {}; + +interface MapLike { + entries: () => Array<[Key, Value]>; + get: (key: Key) => Value | undefined; + has: (key: Key) => boolean; + keys: () => Key[]; + values: () => Value[]; +} + +// index.js +export type ARIARoleDefinitionKey = ARIAAbstractRole | ARIARole | ARIADPubRole; + +export const aria: MapLike; +export interface DOMDefinition { + reserved?: boolean | undefined; + interactive?: boolean | undefined; +} +export const dom: MapLike; +export const elementRoles: MapLike>; +export const roles: MapLike; +export const roleElements: MapLike>; + +// types +export type ARIAAbstractRole = + | "command" + | "composite" + | "input" + | "landmark" + | "range" + | "roletype" + | "section" + | "sectionhead" + | "select" + | "structure" + | "widget" + | "window"; + +export type ARIAWidgetRole = + | "button" + | "checkbox" + | "gridcell" + | "link" + | "menuitem" + | "menuitemcheckbox" + | "menuitemradio" + | "option" + | "progressbar" + | "radio" + | "scrollbar" + | "searchbox" + | "slider" + | "spinbutton" + | "switch" + | "tab" + | "tabpanel" + | "textbox" + | "treeitem"; + +export type ARIACompositeWidgetRole = + | "combobox" + | "grid" + | "listbox" + | "menu" + | "menubar" + | "radiogroup" + | "tablist" + | "tree" + | "treegrid"; + +export type ARIADocumentStructureRole = + | "application" + | "article" + | "blockquote" + | "caption" + | "cell" + | "columnheader" + | "definition" + | "deletion" + | "directory" + | "document" + | "emphasis" + | "feed" + | "figure" + | "generic" + | "group" + | "heading" + | "img" + | "insertion" + | "list" + | "listitem" + | "math" + | "meter" + | "none" + | "note" + | "paragraph" + | "presentation" + | "row" + | "rowgroup" + | "rowheader" + | "separator" + | "strong" + | "subscript" + | "superscript" + | "table" + | "term" + | "time" + | "toolbar" + | "tooltip"; + +export type ARIALandmarkRole = + | "banner" + | "complementary" + | "contentinfo" + | "form" + | "main" + | "navigation" + | "region" + | "search"; + +export type ARIALiveRegionRole = "alert" | "log" | "marquee" | "status" | "timer"; + +export type ARIAWindowRole = "alertdialog" | "dialog"; + +export type ARIAUncategorizedRole = "code"; + +export type ARIADPubRole = + | "doc-abstract" + | "doc-acknowledgments" + | "doc-afterword" + | "doc-appendix" + | "doc-backlink" + | "doc-biblioentry" + | "doc-bibliography" + | "doc-biblioref" + | "doc-chapter" + | "doc-colophon" + | "doc-conclusion" + | "doc-cover" + | "doc-credit" + | "doc-credits" + | "doc-dedication" + | "doc-endnote" + | "doc-endnotes" + | "doc-epigraph" + | "doc-epilogue" + | "doc-errata" + | "doc-example" + | "doc-footnote" + | "doc-foreword" + | "doc-glossary" + | "doc-glossref" + | "doc-index" + | "doc-introduction" + | "doc-noteref" + | "doc-notice" + | "doc-pagebreak" + | "doc-pagelist" + | "doc-part" + | "doc-preface" + | "doc-prologue" + | "doc-pullquote" + | "doc-qna" + | "doc-subtitle" + | "doc-tip" + | "doc-toc"; + +export type ARIARole = + | ARIAWidgetRole + | ARIACompositeWidgetRole + | ARIADocumentStructureRole + | ARIALandmarkRole + | ARIALiveRegionRole + | ARIAWindowRole + | ARIAUncategorizedRole; + +export interface ARIARoleDefinition { + /* Abstract roles may not be used in HTML. */ + abstract: boolean; + /* The concepts in related domains that inform behavior mappings. */ + baseConcepts: ARIARoleRelation[]; + /* Child presentational roles strip child nodes of roles and flatten the + * content to text. */ + childrenPresentational: boolean; + /* aria-* properties and states disallowed on this role. */ + prohibitedProps: ARIAPropertyMap; + /* aria-* properties and states allowed on this role. */ + props: ARIAPropertyMap; + /* The concepts in related domains that inform behavior mappings. */ + relatedConcepts: ARIARoleRelation[]; + /* aria-* properties and states required on this role. */ + requiredProps: ARIAPropertyMap; + /* An array or super class "stacks." Each stack contains a LIFO list of + * strings correspond to a super class in the inheritance chain of this + * role. Roles may have more than one inheritance chain, which is why + * this property is an array of arrays and not a single array. */ + superClass: Array>; +} + +export type ARIAState = + | "aria-busy" + | "aria-checked" + | "aria-disabled" + | "aria-expanded" + | "aria-grabbed" + | "aria-hidden" + | "aria-invalid" + | "aria-pressed" + | "aria-selected"; + +export type ARIAProperty = + | "aria-activedescendant" + | "aria-atomic" + | "aria-autocomplete" + | "aria-colcount" + | "aria-colindex" + | "aria-colspan" + | "aria-controls" + | "aria-current" + | "aria-describedby" + | "aria-details" + | "aria-dropeffect" + | "aria-errormessage" + | "aria-flowto" + | "aria-haspopup" + | "aria-keyshortcuts" + | "aria-label" + | "aria-labelledby" + | "aria-level" + | "aria-live" + | "aria-modal" + | "aria-multiline" + | "aria-multiselectable" + | "aria-orientation" + | "aria-owns" + | "aria-placeholder" + | "aria-posinset" + | "aria-readonly" + | "aria-relevant" + | "aria-required" + | "aria-roledescription" + | "aria-rowcount" + | "aria-rowindex" + | "aria-rowspan" + | "aria-setsize" + | "aria-sort" + | "aria-valuemax" + | "aria-valuemin" + | "aria-valuenow" + | "aria-valuetext" + | ARIAState; + +export interface ARIAPropertyMap { + "aria-busy"?: unknown | undefined; + "aria-checked"?: unknown | undefined; + "aria-disabled"?: unknown | undefined; + "aria-expanded"?: unknown | undefined; + "aria-grabbed"?: unknown | undefined; + "aria-hidden"?: unknown | undefined; + "aria-invalid"?: unknown | undefined; + "aria-pressed"?: unknown | undefined; + "aria-selected"?: unknown | undefined; + "aria-activedescendant"?: unknown | undefined; + "aria-atomic"?: unknown | undefined; + "aria-autocomplete"?: unknown | undefined; + "aria-colcount"?: unknown | undefined; + "aria-colindex"?: unknown | undefined; + "aria-colspan"?: unknown | undefined; + "aria-controls"?: unknown | undefined; + "aria-current"?: ARIAPropertyCurrent | null | undefined; + "aria-describedat"?: unknown | undefined; + "aria-describedby"?: unknown | undefined; + "aria-details"?: unknown | undefined; + "aria-dropeffect"?: unknown | undefined; + "aria-errormessage"?: unknown | undefined; + "aria-flowto"?: unknown | undefined; + "aria-haspopup"?: unknown | undefined; + "aria-keyshortcuts"?: unknown | undefined; + "aria-label"?: unknown | undefined; + "aria-labelledby"?: unknown | undefined; + "aria-level"?: unknown | undefined; + "aria-live"?: unknown | undefined; + "aria-modal"?: unknown | undefined; + "aria-multiline"?: unknown | undefined; + "aria-multiselectable"?: unknown | undefined; + "aria-orientation"?: unknown | undefined; + "aria-owns"?: unknown | undefined; + "aria-placeholder"?: unknown | undefined; + "aria-posinset"?: unknown | undefined; + "aria-readonly"?: unknown | undefined; + "aria-relevant"?: unknown | undefined; + "aria-required"?: unknown | undefined; + "aria-roledescription"?: unknown | undefined; + "aria-rowcount"?: unknown | undefined; + "aria-rowindex"?: unknown | undefined; + "aria-rowspan"?: unknown | undefined; + "aria-setsize"?: unknown | undefined; + "aria-sort"?: unknown | undefined; + "aria-valuemax"?: unknown | undefined; + "aria-valuemin"?: unknown | undefined; + "aria-valuenow"?: unknown | undefined; + "aria-valuetext"?: unknown | undefined; +} + +export interface ARIAPropertyDefinition { + type: "string" | "id" | "idlist" | "integer" | "number" | "boolean" | "token" | "tokenlist" | "tristate"; + values?: Array | undefined; + allowundefined?: boolean | undefined; +} + +export type ARIAPropertyCurrent = "page" | "step" | "location" | "date" | "time" | "true" | "false" | true | false; + +export interface ARIARoleRelation { + module?: string | undefined; + concept?: ARIARoleRelationConcept | undefined; +} + +/* The concept in a related domain that informs behavior mappings. + * Related domains include: HTML, "Device Independence Delivery Unit", XForms, + * and ARIA to name a few. */ +export interface ARIARoleRelationConcept { + name: string; + attributes?: ARIARoleRelationConceptAttribute[] | undefined; + // These constraints are drawn from the mapping between ARIA and HTML: + // https://www.w3.org/TR/html-aria + constraints?: + | Array< + | "direct descendant of document" + | "direct descendant of ol, ul or menu" + | "direct descendant of details element with the open attribute defined" + | "descendant of table" + > + | undefined; +} + +export interface ARIARoleRelationConceptAttribute { + name: string; + value?: string | number | undefined; + // These constraints are drawn from the mapping between ARIA and HTML: + // https://www.w3.org/TR/html-aria + constraints?: Array<"unset" | ">1"> | undefined; +} diff --git a/tools/ui/node_modules/@types/aria-query/package.json b/tools/ui/node_modules/@types/aria-query/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b277291d44f4fe4590878d7b56d79215d99c7cc8 --- /dev/null +++ b/tools/ui/node_modules/@types/aria-query/package.json @@ -0,0 +1,25 @@ +{ + "name": "@types/aria-query", + "version": "5.0.4", + "description": "TypeScript definitions for aria-query", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/aria-query", + "license": "MIT", + "contributors": [ + { + "name": "Sebastian Silbermann", + "githubUsername": "eps1lon", + "url": "https://github.com/eps1lon" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/aria-query" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "df81e762ea003d46edaa1ce65e6e72487611400664e3105baa1610186c630902", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/chai/LICENSE b/tools/ui/node_modules/@types/chai/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/chai/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/chai/README.md b/tools/ui/node_modules/@types/chai/README.md new file mode 100644 index 0000000000000000000000000000000000000000..27c1356787f5bcbfe717ff68f4432722535f25ee --- /dev/null +++ b/tools/ui/node_modules/@types/chai/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/chai` + +# Summary +This package contains type definitions for chai (http://chaijs.com/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/chai. + +### Additional Details + * Last updated: Mon, 20 Oct 2025 23:32:35 GMT + * Dependencies: [@types/deep-eql](https://npmjs.com/package/@types/deep-eql), [assertion-error](https://npmjs.com/package/assertion-error) + +# Credits +These definitions were written by [Bart van der Schoor](https://github.com/Bartvds), [Andrew Brown](https://github.com/AGBrown), [Olivier Chevet](https://github.com/olivr70), [Matt Wistrand](https://github.com/mwistrand), [Shaun Luttin](https://github.com/shaunluttin), [Satana Charuwichitratana](https://github.com/micksatana), [Erik Schierboom](https://github.com/ErikSchierboom), [Bogdan Paranytsia](https://github.com/bparan), [CXuesong](https://github.com/CXuesong), and [Joey Kilpatrick](https://github.com/joeykilpatrick). diff --git a/tools/ui/node_modules/@types/chai/index.d.ts b/tools/ui/node_modules/@types/chai/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4fed6b906ef0d56b429ccaa9e2804915175e6f7e --- /dev/null +++ b/tools/ui/node_modules/@types/chai/index.d.ts @@ -0,0 +1,2145 @@ +import deepEqual = require("deep-eql"); +import { AssertionError as ImportedAssertionError } from "assertion-error"; + +declare global { + namespace Chai { + export type Message = string | (() => string); + export type ObjectProperty = string | symbol | number; + + export interface PathInfo { + parent: object; + name: string; + value?: any; + exists: boolean; + } + + export interface Constructor { + new(...args: any[]): T; + } + + export interface ErrorConstructor { + new(...args: any[]): Error; + } + + export interface ChaiUtils { + addChainableMethod( + // object to define the method on, e.g. chai.Assertion.prototype + ctx: object, + // method name + name: string, + // method itself; any arguments + method: (...args: any[]) => void, + // called when property is accessed + chainingBehavior?: () => void, + ): void; + overwriteChainableMethod( + ctx: object, + name: string, + method: (...args: any[]) => void, + chainingBehavior?: () => void, + ): void; + addLengthGuard( + fn: Function, + assertionName: string, + isChainable: boolean, + ): void; + addMethod(ctx: object, name: string, method: Function): void; + addProperty(ctx: object, name: string, getter: () => any): void; + overwriteMethod(ctx: object, name: string, method: Function): void; + overwriteProperty(ctx: object, name: string, getter: (this: AssertionStatic, _super: any) => any): void; + compareByInspect(a: object, b: object): -1 | 1; + expectTypes(obj: object, types: string[]): void; + flag(obj: object, key: string, value?: any): any; + getActual(obj: object, args: AssertionArgs): any; + getProperties(obj: object): string[]; + getEnumerableProperties(obj: object): string[]; + getOwnEnumerablePropertySymbols(obj: object): symbol[]; + getOwnEnumerableProperties(obj: object): Array; + getMessage(errorLike: Error | string): string; + getMessage(obj: any, args: AssertionArgs): string; + inspect(obj: any, showHidden?: boolean, depth?: number, colors?: boolean): string; + isProxyEnabled(): boolean; + objDisplay(obj: object): void; + proxify(obj: object, nonChainableMethodName: string): object; + test(obj: object, args: AssertionArgs): boolean; + transferFlags(assertion: Assertion, obj: object, includeAll?: boolean): void; + compatibleInstance(thrown: Error, errorLike: Error | ErrorConstructor): boolean; + compatibleConstructor(thrown: Error, errorLike: Error | ErrorConstructor): boolean; + compatibleMessage(thrown: Error, errMatcher: string | RegExp): boolean; + getConstructorName(constructorFn: Function): string; + getFuncName(constructorFn: Function): string | null; + + // Reexports from pathval: + hasProperty(obj: object | undefined | null, name: ObjectProperty): boolean; + getPathInfo(obj: object, path: string): PathInfo; + getPathValue(obj: object, path: string): object | undefined; + + eql: typeof deepEqual; + } + + export type ChaiPlugin = (chai: ChaiStatic, utils: ChaiUtils) => void; + + export interface ChaiStatic { + expect: ExpectStatic; + should(): Should; + /** + * Provides a way to extend the internals of Chai + */ + use(fn: ChaiPlugin): ChaiStatic; + util: ChaiUtils; + assert: AssertStatic; + config: Config; + Assertion: AssertionStatic; + AssertionError: typeof AssertionError; + version: string; + } + + export interface ExpectStatic { + (val: any, message?: string): Assertion; + fail(message?: string): never; + fail(actual: any, expected: any, message?: string, operator?: Operator): never; + } + + export interface AssertStatic extends Assert { + } + + // chai.Assertion.prototype.assert arguments + export type AssertionArgs = [ + any, // expression to be tested + Message, // message or function that returns message to display if expression fails + Message, // negatedMessage or function that returns negatedMessage to display if expression fails + any?, // expected value + any?, // actual value + boolean?, // showDiff, when set to `true`, assert will display a diff in addition to the message if expression fails + ]; + + export interface AssertionPrototype { + assert(...args: AssertionArgs): void; + _obj: any; + } + + export interface AssertionStatic extends AssertionPrototype { + prototype: AssertionPrototype; + + new(target: any, message?: string, ssfi?: Function, lockSsfi?: boolean): Assertion; + + // Deprecated properties: + includeStack: boolean; + showDiff: boolean; + + // Partials of functions on ChaiUtils: + addProperty(name: string, getter: (this: AssertionStatic) => any): void; + addMethod(name: string, method: (this: AssertionStatic, ...args: any[]) => any): void; + addChainableMethod( + name: string, + method: (this: AssertionStatic, ...args: any[]) => void, + chainingBehavior?: () => void, + ): void; + overwriteProperty(name: string, getter: (this: AssertionStatic, _super: any) => any): void; + overwriteMethod(name: string, method: (this: AssertionStatic, ...args: any[]) => any): void; + overwriteChainableMethod( + name: string, + method: (this: AssertionStatic, ...args: any[]) => void, + chainingBehavior?: () => void, + ): void; + } + + export type Operator = string; // "==" | "===" | ">" | ">=" | "<" | "<=" | "!=" | "!=="; + + export type OperatorComparable = boolean | null | number | string | undefined | Date; + + export interface ShouldAssertion { + equal(value1: any, value2: any, message?: string): void; + Throw: ShouldThrow; + throw: ShouldThrow; + exist(value: any, message?: string): void; + } + + export interface Should extends ShouldAssertion { + not: ShouldAssertion; + fail(message?: string): never; + fail(actual: any, expected: any, message?: string, operator?: Operator): never; + } + + export interface ShouldThrow { + (actual: Function, expected?: string | RegExp, message?: string): void; + (actual: Function, constructor: Error | Function, expected?: string | RegExp, message?: string): void; + } + + export interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + not: Assertion; + deep: Deep; + ordered: Ordered; + nested: Nested; + own: Own; + any: KeyFilter; + all: KeyFilter; + a: Assertion; + an: Assertion; + include: Include; + includes: Include; + contain: Include; + contains: Include; + ok: Assertion; + true: Assertion; + false: Assertion; + null: Assertion; + undefined: Assertion; + NaN: Assertion; + exist: Assertion; + empty: Assertion; + arguments: Assertion; + Arguments: Assertion; + finite: Assertion; + equal: Equal; + equals: Equal; + eq: Equal; + eql: Equal; + eqls: Equal; + containSubset: ContainSubset; + property: Property; + ownProperty: Property; + haveOwnProperty: Property; + ownPropertyDescriptor: OwnPropertyDescriptor; + haveOwnPropertyDescriptor: OwnPropertyDescriptor; + length: Length; + lengthOf: Length; + match: Match; + matches: Match; + string(string: string, message?: string): Assertion; + keys: Keys; + key(string: string): Assertion; + throw: Throw; + throws: Throw; + Throw: Throw; + respondTo: RespondTo; + respondsTo: RespondTo; + itself: Assertion; + satisfy: Satisfy; + satisfies: Satisfy; + closeTo: CloseTo; + approximately: CloseTo; + members: Members; + increase: PropertyChange; + increases: PropertyChange; + decrease: PropertyChange; + decreases: PropertyChange; + change: PropertyChange; + changes: PropertyChange; + extensible: Assertion; + sealed: Assertion; + frozen: Assertion; + oneOf: OneOf; + } + + export interface LanguageChains { + to: Assertion; + be: Assertion; + been: Assertion; + is: Assertion; + that: Assertion; + which: Assertion; + and: Assertion; + has: Assertion; + have: Assertion; + with: Assertion; + at: Assertion; + of: Assertion; + same: Assertion; + but: Assertion; + does: Assertion; + } + + export interface NumericComparison { + above: NumberComparer; + gt: NumberComparer; + greaterThan: NumberComparer; + least: NumberComparer; + gte: NumberComparer; + greaterThanOrEqual: NumberComparer; + below: NumberComparer; + lt: NumberComparer; + lessThan: NumberComparer; + most: NumberComparer; + lte: NumberComparer; + lessThanOrEqual: NumberComparer; + within(start: number, finish: number, message?: string): Assertion; + within(start: Date, finish: Date, message?: string): Assertion; + } + + export interface NumberComparer { + (value: number | Date, message?: string): Assertion; + } + + export interface TypeComparison { + (type: string, message?: string): Assertion; + instanceof: InstanceOf; + instanceOf: InstanceOf; + } + + export interface InstanceOf { + (constructor: any, message?: string): Assertion; + } + + export interface CloseTo { + (expected: number, delta: number, message?: string): Assertion; + } + + export interface Nested { + include: Include; + includes: Include; + contain: Include; + contains: Include; + property: Property; + members: Members; + } + + export interface Own { + include: Include; + includes: Include; + contain: Include; + contains: Include; + property: Property; + } + + export interface Deep extends KeyFilter { + be: Assertion; + equal: Equal; + equals: Equal; + eq: Equal; + include: Include; + includes: Include; + contain: Include; + contains: Include; + property: Property; + ordered: Ordered; + nested: Nested; + oneOf: OneOf; + own: Own; + } + + export interface Ordered { + members: Members; + } + + export interface KeyFilter { + keys: Keys; + members: Members; + } + + export interface Equal { + (value: any, message?: string): Assertion; + } + + export interface ContainSubset { + (expected: any): Assertion; + } + + export interface Property { + (name: string | symbol, value: any, message?: string): Assertion; + (name: string | symbol, message?: string): Assertion; + } + + export interface OwnPropertyDescriptor { + (name: string | symbol, descriptor: PropertyDescriptor, message?: string): Assertion; + (name: string | symbol, message?: string): Assertion; + } + + export interface Length extends LanguageChains, NumericComparison { + (length: number, message?: string): Assertion; + } + + export interface Include { + (value: any, message?: string): Assertion; + keys: Keys; + deep: Deep; + ordered: Ordered; + members: Members; + any: KeyFilter; + all: KeyFilter; + oneOf: OneOf; + } + + export interface OneOf { + (list: readonly unknown[], message?: string): Assertion; + } + + export interface Match { + (regexp: RegExp, message?: string): Assertion; + } + + export interface Keys { + (...keys: string[]): Assertion; + (keys: readonly any[] | Object): Assertion; + } + + export interface Throw { + (expected?: string | RegExp, message?: string): Assertion; + (constructor: Error | Function, expected?: string | RegExp, message?: string): Assertion; + } + + export interface RespondTo { + (method: string, message?: string): Assertion; + } + + export interface Satisfy { + (matcher: Function, message?: string): Assertion; + } + + export interface Members { + (set: readonly any[], message?: string): Assertion; + } + + export interface PropertyChange { + (object: Object, property?: string, message?: string): DeltaAssertion; + } + + export interface DeltaAssertion extends Assertion { + by(delta: number, msg?: string): Assertion; + } + + export interface Assert { + /** + * @param expression Expression to test for truthiness. + * @param message Message to display on error. + */ + (expression: any, message?: string): asserts expression; + + /** + * Throws a failure. + * + * @param message Message to display on error. + * @remarks Node.js assert module-compatible. + */ + fail(message?: string): never; + + /** + * Throws a failure. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + * @param operator Comparison operator, if not strict equality. + * @remarks Node.js assert module-compatible. + */ + fail(actual: T, expected: T, message?: string, operator?: Operator): never; + + /** + * Asserts that object is truthy. + * + * @param object Object to test. + * @param message Message to display on error. + */ + isOk(value: unknown, message?: string): asserts value; + + /** + * Asserts that object is truthy. + * + * @param object Object to test. + * @param message Message to display on error. + */ + ok(value: unknown, message?: string): asserts value; + + /** + * Asserts that object is falsy. + * + * T Type of object. + * @param object Object to test. + * @param message Message to display on error. + */ + isNotOk(value: T, message?: string): void; + + /** + * Asserts that object is falsy. + * + * T Type of object. + * @param object Object to test. + * @param message Message to display on error. + */ + notOk(value: T, message?: string): void; + + /** + * Asserts non-strict equality (==) of actual and expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + equal(actual: T, expected: T, message?: string): void; + + /** + * Asserts non-strict inequality (!=) of actual and expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + notEqual(actual: T, expected: T, message?: string): void; + + /** + * Asserts strict equality (===) of actual and expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + strictEqual(actual: T, expected: T, message?: string): void; + + /** + * Asserts strict inequality (!==) of actual and expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + notStrictEqual(actual: T, expected: T, message?: string): void; + + /** + * Asserts that actual is deeply equal to expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + deepEqual(actual: T, expected: T, message?: string): void; + + /** + * Asserts that actual is not deeply equal to expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + notDeepEqual(actual: T, expected: T, message?: string): void; + + /** + * Alias to deepEqual + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + deepStrictEqual(actual: T, expected: T, message?: string): void; + + /** + * Partially matches actual and expected. + * + * @param actual Actual value. + * @param expected Potential subset of the value. + * @param message Message to display on error. + */ + containSubset(val: any, exp: any, msg?: string): void; + + /** + * Partially matches actual and expected. + * + * @param actual Actual value. + * @param expected Potential subset of the value. + * @param message Message to display on error. + */ + containsSubset(val: any, exp: any, msg?: string): void; + + /** + * No partial match between actual and expected exists. + * + * @param actual Actual value. + * @param expected Potential subset of the value. + * @param message Message to display on error. + */ + doesNotContainSubset(val: any, exp: any, msg?: string): void; + + /** + * Asserts valueToCheck is strictly greater than (>) valueToBeAbove. + * + * @param valueToCheck Actual value. + * @param valueToBeAbove Minimum Potential expected value. + * @param message Message to display on error. + */ + isAbove(valueToCheck: number, valueToBeAbove: number, message?: string): void; + + /** + * Asserts valueToCheck is greater than or equal to (>=) valueToBeAtLeast. + * + * @param valueToCheck Actual value. + * @param valueToBeAtLeast Minimum Potential expected value. + * @param message Message to display on error. + */ + isAtLeast(valueToCheck: number, valueToBeAtLeast: number, message?: string): void; + + /** + * Asserts valueToCheck is strictly less than (<) valueToBeBelow. + * + * @param valueToCheck Actual value. + * @param valueToBeBelow Minimum Potential expected value. + * @param message Message to display on error. + */ + isBelow(valueToCheck: number, valueToBeBelow: number, message?: string): void; + + /** + * Asserts valueToCheck is less than or equal to (<=) valueToBeAtMost. + * + * @param valueToCheck Actual value. + * @param valueToBeAtMost Minimum Potential expected value. + * @param message Message to display on error. + */ + isAtMost(valueToCheck: number, valueToBeAtMost: number, message?: string): void; + + /** + * Asserts that value is true. + * + * @param value Actual value. + * @param message Message to display on error. + */ + isTrue(value: unknown, message?: string): asserts value is true; + + /** + * Asserts that value is false. + * + * @param value Actual value. + * @param message Message to display on error. + */ + isFalse(value: unknown, message?: string): asserts value is false; + + /** + * Asserts that value is not true. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotTrue(value: T, message?: string): asserts value is Exclude; + + /** + * Asserts that value is not false. + * + * @param value Actual value. + * @param message Message to display on error. + */ + isNotFalse(value: T, message?: string): asserts value is Exclude; + + /** + * Asserts that value is null. + * + * @param value Actual value. + * @param message Message to display on error. + */ + isNull(value: unknown, message?: string): asserts value is null; + + /** + * Asserts that value is not null. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotNull(value: T, message?: string): asserts value is Exclude; + + /** + * Asserts that value is NaN. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNaN(value: T, message?: string): void; + + /** + * Asserts that value is not NaN. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotNaN(value: T, message?: string): void; + + /** + * Asserts that the target is neither null nor undefined. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + exists(value: T, message?: string): asserts value is NonNullable; + + /** + * Asserts that the target is either null or undefined. + * + * @param value Actual value. + * @param message Message to display on error. + */ + notExists(value: unknown, message?: string): asserts value is + | null + | undefined; + + /** + * Asserts that value is undefined. + * + * @param value Actual value. + * @param message Message to display on error. + */ + isUndefined(value: unknown, message?: string): asserts value is undefined; + + /** + * Asserts that value is not undefined. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isDefined(value: T, message?: string): asserts value is Exclude; + + /** + * Asserts that value is a function. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isFunction(value: T, message?: string): void; + + /** + * Asserts that value is not a function. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotFunction(value: T, message?: string): void; + + /** + * Asserts that value is an object of type 'Object' + * (as revealed by Object.prototype.toString). + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + * @remarks The assertion does not match subclassed objects. + */ + isObject(value: T, message?: string): void; + + /** + * Asserts that value is not an object of type 'Object' + * (as revealed by Object.prototype.toString). + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotObject(value: T, message?: string): void; + + /** + * Asserts that value is an array. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isArray(value: T, message?: string): void; + + /** + * Asserts that value is not an array. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotArray(value: T, message?: string): void; + + /** + * Asserts that value is a string. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isString(value: T, message?: string): void; + + /** + * Asserts that value is not a string. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotString(value: T, message?: string): void; + + /** + * Asserts that value is a number. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNumber(value: T, message?: string): void; + + /** + * Asserts that value is not a number. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotNumber(value: T, message?: string): void; + + /** + * Asserts that value is a finite number. + * Unlike `.isNumber`, this will fail for `NaN` and `Infinity`. + * + * T Type of value + * @param value Actual value + * @param message Message to display on error. + */ + isFinite(value: T, message?: string): void; + + /** + * Asserts that value is a boolean. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isBoolean(value: T, message?: string): void; + + /** + * Asserts that value is not a boolean. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotBoolean(value: T, message?: string): void; + + /** + * Asserts that value's type is name, as determined by Object.prototype.toString. + * + * T Type of value. + * @param value Actual value. + * @param name Potential expected type name of value. + * @param message Message to display on error. + */ + typeOf(value: T, name: string, message?: string): void; + + /** + * Asserts that value's type is not name, as determined by Object.prototype.toString. + * + * T Type of value. + * @param value Actual value. + * @param name Potential expected type name of value. + * @param message Message to display on error. + */ + notTypeOf(value: T, name: string, message?: string): void; + + /** + * Asserts that value is an instance of constructor. + * + * T Expected type of value. + * @param value Actual value. + * @param constructor Potential expected contructor of value. + * @param message Message to display on error. + */ + instanceOf( + value: unknown, + constructor: Constructor, + message?: string, + ): asserts value is T; + + /** + * Asserts that value is not an instance of constructor. + * + * T Type of value. + * U Type that value shouldn't be an instance of. + * @param value Actual value. + * @param constructor Potential expected contructor of value. + * @param message Message to display on error. + */ + notInstanceOf(value: T, type: Constructor, message?: string): asserts value is Exclude; + + /** + * Asserts that haystack includes needle. + * + * @param haystack Container string. + * @param needle Potential substring of haystack. + * @param message Message to display on error. + */ + include(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack includes needle. + * + * T Type of values in haystack. + * @param haystack Container array, set or map. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + include( + haystack: readonly T[] | ReadonlySet | ReadonlyMap, + needle: T, + message?: string, + ): void; + + /** + * Asserts that haystack includes needle. + * + * T Type of values in haystack. + * @param haystack WeakSet container. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + include(haystack: WeakSet, needle: T, message?: string): void; + + /** + * Asserts that haystack includes needle. + * + * T Type of haystack. + * @param haystack Object. + * @param needle Potential subset of the haystack's properties. + * @param message Message to display on error. + */ + include(haystack: T, needle: Partial, message?: string): void; + + /** + * Asserts that haystack does not include needle. + * + * @param haystack Container string. + * @param needle Potential substring of haystack. + * @param message Message to display on error. + */ + notInclude(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack does not include needle. + * + * T Type of values in haystack. + * @param haystack Container array, set or map. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + notInclude( + haystack: readonly T[] | ReadonlySet | ReadonlyMap, + needle: T, + message?: string, + ): void; + + /** + * Asserts that haystack does not include needle. + * + * T Type of values in haystack. + * @param haystack WeakSet container. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + notInclude(haystack: WeakSet, needle: T, message?: string): void; + + /** + * Asserts that haystack does not include needle. + * + * T Type of haystack. + * @param haystack Object. + * @param needle Potential subset of the haystack's properties. + * @param message Message to display on error. + */ + notInclude(haystack: T, needle: Partial, message?: string): void; + + /** + * Asserts that haystack includes needle. Deep equality is used. + * + * @param haystack Container string. + * @param needle Potential substring of haystack. + * @param message Message to display on error. + * + * @deprecated Does not have any effect on string. Use {@link Assert#include} instead. + */ + deepInclude(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack includes needle. Deep equality is used. + * + * T Type of values in haystack. + * @param haystack Container array, set or map. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + deepInclude( + haystack: readonly T[] | ReadonlySet | ReadonlyMap, + needle: T, + message?: string, + ): void; + + /** + * Asserts that haystack includes needle. Deep equality is used. + * + * T Type of haystack. + * @param haystack Object. + * @param needle Potential subset of the haystack's properties. + * @param message Message to display on error. + */ + deepInclude(haystack: T, needle: T extends WeakSet ? never : Partial, message?: string): void; + + /** + * Asserts that haystack does not include needle. Deep equality is used. + * + * @param haystack Container string. + * @param needle Potential substring of haystack. + * @param message Message to display on error. + * + * @deprecated Does not have any effect on string. Use {@link Assert#notInclude} instead. + */ + notDeepInclude(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack does not include needle. Deep equality is used. + * + * T Type of values in haystack. + * @param haystack Container array, set or map. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + notDeepInclude( + haystack: readonly T[] | ReadonlySet | ReadonlyMap, + needle: T, + message?: string, + ): void; + + /** + * Asserts that haystack does not include needle. Deep equality is used. + * + * T Type of haystack. + * @param haystack Object. + * @param needle Potential subset of the haystack's properties. + * @param message Message to display on error. + */ + notDeepInclude(haystack: T, needle: T extends WeakSet ? never : Partial, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + nestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ does not include ‘needle’. Can be used to assert the absence of a subset of properties in an object. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while checking for deep equality + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + deepNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ does not include ‘needle’. Can be used to assert the absence of a subset of properties in an object while checking for deep equality. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notDeepNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while ignoring inherited properties. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + ownInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the absence of a subset of properties in an object while ignoring inherited properties. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notOwnInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while ignoring inherited properties and checking for deep + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + deepOwnInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the absence of a subset of properties in an object while ignoring inherited properties and checking for deep equality. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notDeepOwnInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that value matches the regular expression regexp. + * + * @param value Actual value. + * @param regexp Potential match of value. + * @param message Message to display on error. + */ + match(value: string, regexp: RegExp, message?: string): void; + + /** + * Asserts that value does not match the regular expression regexp. + * + * @param value Actual value. + * @param regexp Potential match of value. + * @param message Message to display on error. + */ + notMatch(expected: any, regexp: RegExp, message?: string): void; + + /** + * Asserts that object has a property named by property. + * + * T Type of object. + * @param object Container object. + * @param property Potential contained property of object. + * @param message Message to display on error. + */ + property(object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that object does not have a property named by property. + * + * T Type of object. + * @param object Container object. + * @param property Potential contained property of object. + * @param message Message to display on error. + */ + notProperty(object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that object has a property named by property, which can be a string + * using dot- and bracket-notation for deep reference. + * + * T Type of object. + * @param object Container object. + * @param property Potential contained property of object. + * @param message Message to display on error. + */ + deepProperty(object: T, property: string, message?: string): void; + + /** + * Asserts that object does not have a property named by property, which can be a + * string using dot- and bracket-notation for deep reference. + * + * T Type of object. + * @param object Container object. + * @param property Potential contained property of object. + * @param message Message to display on error. + */ + notDeepProperty(object: T, property: string, message?: string): void; + + /** + * Asserts that object has a property named by property with value given by value. + * + * T Type of object. + * V Type of value. + * @param object Container object. + * @param property Potential contained property of object. + * @param value Potential expected property value. + * @param message Message to display on error. + */ + propertyVal(object: T, property: string, /* keyof T */ value: V, message?: string): void; + + /** + * Asserts that object has a property named by property with value given by value. + * + * T Type of object. + * V Type of value. + * @param object Container object. + * @param property Potential contained property of object. + * @param value Potential expected property value. + * @param message Message to display on error. + */ + notPropertyVal(object: T, property: string, /* keyof T */ value: V, message?: string): void; + + /** + * Asserts that object has a property named by property, which can be a string + * using dot- and bracket-notation for deep reference. + * + * T Type of object. + * V Type of value. + * @param object Container object. + * @param property Potential contained property of object. + * @param value Potential expected property value. + * @param message Message to display on error. + */ + deepPropertyVal(object: T, property: string, value: V, message?: string): void; + + /** + * Asserts that object does not have a property named by property, which can be a + * string using dot- and bracket-notation for deep reference. + * + * T Type of object. + * V Type of value. + * @param object Container object. + * @param property Potential contained property of object. + * @param value Potential expected property value. + * @param message Message to display on error. + */ + notDeepPropertyVal(object: T, property: string, value: V, message?: string): void; + + /** + * Asserts that object has a length property with the expected value. + * + * T Type of object. + * @param object Container object. + * @param length Potential expected length of object. + * @param message Message to display on error. + */ + lengthOf( + object: T, + length: number, + message?: string, + ): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errMsgMatcher Expected error message matcher. + * @param ignored Ignored parameter. + * @param message Message to display on error. + */ + throw(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errorLike Expected error constructor or error instance. + * @param errMsgMatcher Expected error message matcher. + * @param message Message to display on error. + */ + throw( + fn: () => void, + errorLike?: ErrorConstructor | Error | null, + errMsgMatcher?: RegExp | string | null, + message?: string, + ): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errMsgMatcher Expected error message matcher. + * @param ignored Ignored parameter. + * @param message Message to display on error. + */ + throws(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errorLike Expected error constructor or error instance. + * @param errMsgMatcher Expected error message matcher. + * @param message Message to display on error. + */ + throws( + fn: () => void, + errorLike?: ErrorConstructor | Error | null, + errMsgMatcher?: RegExp | string | null, + message?: string, + ): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errMsgMatcher Expected error message matcher. + * @param ignored Ignored parameter. + * @param message Message to display on error. + */ + Throw(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errorLike Expected error constructor or error instance. + * @param errMsgMatcher Expected error message matcher. + * @param message Message to display on error. + */ + Throw( + fn: () => void, + errorLike?: ErrorConstructor | Error | null, + errMsgMatcher?: RegExp | string | null, + message?: string, + ): void; + + /** + * Asserts that fn will not throw an error. + * + * @param fn Function that may throw. + * @param errMsgMatcher Expected error message matcher. + * @param ignored Ignored parameter. + * @param message Message to display on error. + */ + doesNotThrow(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string): void; + + /** + * Asserts that fn will not throw an error. + * + * @param fn Function that may throw. + * @param errorLike Expected error constructor or error instance. + * @param errMsgMatcher Expected error message matcher. + * @param message Message to display on error. + */ + doesNotThrow( + fn: () => void, + errorLike?: ErrorConstructor | Error | null, + errMsgMatcher?: RegExp | string | null, + message?: string, + ): void; + + /** + * Compares two values using operator. + * + * @param val1 Left value during comparison. + * @param operator Comparison operator. + * @param val2 Right value during comparison. + * @param message Message to display on error. + */ + operator(val1: OperatorComparable, operator: Operator, val2: OperatorComparable, message?: string): void; + + /** + * Asserts that the target is equal to expected, to within a +/- delta range. + * + * @param actual Actual value + * @param expected Potential expected value. + * @param delta Maximum differenced between values. + * @param message Message to display on error. + */ + closeTo(actual: number, expected: number, delta: number, message?: string): void; + + /** + * Asserts that the target is equal to expected, to within a +/- delta range. + * + * @param actual Actual value + * @param expected Potential expected value. + * @param delta Maximum differenced between values. + * @param message Message to display on error. + */ + approximately(act: number, exp: number, delta: number, message?: string): void; + + /** + * Asserts that set1 and set2 have the same members. Order is not take into account. + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 have the same members using deep equality checking. + * Order is not take into account. + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameDeepMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that `set1` and `set2` don't have the same members in any order. + * Uses a deep equality check. + * + * T Type of set values. + * @param set1 + * @param set2 + * @param message + */ + notSameDeepMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 have the same members in the same order. + * Uses a strict equality check (===). + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 don’t have the same members in the same order. + * Uses a strict equality check (===). + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + notSameOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 have the same members in the same order. + * Uses a deep equality check. + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameDeepOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 don’t have the same members in the same order. + * Uses a deep equality check. + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + notSameDeepOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that subset is included in superset in the same order beginning with the first element in superset. + * Uses a strict equality check (===). + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset isn’t included in superset in the same order beginning with the first element in superset. + * Uses a strict equality check (===). + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + notIncludeOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset is included in superset in the same order beginning with the first element in superset. + * Uses a deep equality check. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeDeepOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset isn’t included in superset in the same order beginning with the first element in superset. + * Uses a deep equality check. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + notIncludeDeepOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset is included in superset. Order is not take into account. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset isn’t included in superset in any order. + * Uses a strict equality check (===). Duplicates are ignored. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential not contained set of values. + * @param message Message to display on error. + */ + notIncludeMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset is included in superset using deep equality checking. + * Order is not take into account. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeDeepMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that `subset` isn't included in `superset` in any order. Uses a + * deep equality check. Duplicates are ignored. + * + * assert.notIncludeDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { f: 5 } ], 'not include deep members'); + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + notIncludeDeepMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that non-object, non-array value inList appears in the flat array list. + * + * T Type of list values. + * @param inList Value expected to be in the list. + * @param list List of values. + * @param message Message to display on error. + */ + oneOf(inList: T, list: T[], message?: string): void; + + /** + * Asserts that a function changes the value of a property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected to be modified. + * @param message Message to display on error. + */ + changes(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function changes the value of a property by an amount (delta). + * + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + changesBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + changesBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts that a function does not change the value of a property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected not to be modified. + * @param message Message to display on error. + */ + doesNotChange(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function increases an object property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected to be increased. + * @param message Message to display on error. + */ + increases(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function increases a numeric object property or a function's return value by an amount (delta). + * + * T Type of object or function. + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + increasesBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + increasesBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts that a function does not increase an object property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected not to be increased. + * @param message Message to display on error. + */ + doesNotIncrease(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function does not increase a numeric object property or function's return value by an amount (delta). + * + * T Type of object or function. + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + + increasesButNotBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + increasesButNotBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts that a function decreases an object property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected to be decreased. + * @param message Message to display on error. + */ + decreases(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function decreases a numeric object property or a function's return value by an amount (delta) + * + * T Type of object or function. + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + + decreasesBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + decreasesBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts that a function does not decrease an object property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected not to be decreased. + * @param message Message to display on error. + */ + doesNotDecrease(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) + * + * T Type of object or function. + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + + doesNotDecreaseBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + doesNotDecreaseBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) + * + * T Type of object or function. + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + + decreasesButNotBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + decreasesButNotBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts if value is not a false value, and throws if it is a true value. + * + * T Type of object. + * @param object Actual value. + * @param message Message to display on error. + * @remarks This is added to allow for chai to be a drop-in replacement for + * Node’s assert class. + */ + ifError(object: T, message?: string): void; + + /** + * Asserts that object is extensible (can have new properties added to it). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isExtensible(object: T, message?: string): void; + + /** + * Asserts that object is extensible (can have new properties added to it). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + extensible(object: T, message?: string): void; + + /** + * Asserts that object is not extensible. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isNotExtensible(object: T, message?: string): void; + + /** + * Asserts that object is not extensible. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + notExtensible(object: T, message?: string): void; + + /** + * Asserts that object is sealed (can have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isSealed(object: T, message?: string): void; + + /** + * Asserts that object is sealed (can have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + sealed(object: T, message?: string): void; + + /** + * Asserts that object is not sealed. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isNotSealed(object: T, message?: string): void; + + /** + * Asserts that object is not sealed. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + notSealed(object: T, message?: string): void; + + /** + * Asserts that object is frozen (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isFrozen(object: T, message?: string): void; + + /** + * Asserts that object is frozen (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + frozen(object: T, message?: string): void; + + /** + * Asserts that object is not frozen (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isNotFrozen(object: T, message?: string): void; + + /** + * Asserts that object is not frozen (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + notFrozen(object: T, message?: string): void; + + /** + * Asserts that the target does not contain any values. For arrays and + * strings, it checks the length property. For Map and Set instances, it + * checks the size property. For non-function objects, it gets the count + * of own enumerable string keys. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isEmpty(object: T, message?: string): void; + + /** + * Asserts that the target contains values. For arrays and strings, it checks + * the length property. For Map and Set instances, it checks the size property. + * For non-function objects, it gets the count of own enumerable string keys. + * + * T Type of object. + * @param object Object to test. + * @param message Message to display on error. + */ + isNotEmpty(object: T, message?: string): void; + + /** + * Asserts that `object` has at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAnyKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all and only all of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAllKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all of the `keys` provided but may have more keys not listed. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + containsAllKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that `object` has none of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAnyKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that `object` does not have at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAllKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that `object` has at least one of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAnyDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all and only all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAllDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + containsAllDeepKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAnyDeepKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAllDeepKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that object has a direct or inherited property named by property, + * which can be a string using dot- and bracket-notation for nested reference. + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param message Message to display on error. + */ + nestedProperty(object: T, property: string, message?: string): void; + + /** + * Asserts that object does not have a property named by property, + * which can be a string using dot- and bracket-notation for nested reference. + * The property cannot exist on the object nor anywhere in its prototype chain. + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param message Message to display on error. + */ + notNestedProperty(object: T, property: string, message?: string): void; + + /** + * Asserts that object has a property named by property with value given by value. + * property can use dot- and bracket-notation for nested reference. Uses a strict equality check (===). + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param value Value to test. + * @param message Message to display on error. + */ + nestedPropertyVal(object: T, property: string, value: any, message?: string): void; + + /** + * Asserts that object does not have a property named by property with value given by value. + * property can use dot- and bracket-notation for nested reference. Uses a strict equality check (===). + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param value Value to test. + * @param message Message to display on error. + */ + notNestedPropertyVal(object: T, property: string, value: any, message?: string): void; + + /** + * Asserts that object has a property named by property with a value given by value. + * property can use dot- and bracket-notation for nested reference. Uses a deep equality check. + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param value Value to test. + * @param message Message to display on error. + */ + deepNestedPropertyVal(object: T, property: string, value: any, message?: string): void; + + /** + * Asserts that object does not have a property named by property with value given by value. + * property can use dot- and bracket-notation for nested reference. Uses a deep equality check. + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param value Value to test. + * @param message Message to display on error. + */ + notDeepNestedPropertyVal(object: T, property: string, value: any, message?: string): void; + } + + export interface Config { + /** + * Default: false + */ + includeStack: boolean; + + /** + * Default: true + */ + showDiff: boolean; + + /** + * Default: 40 + */ + truncateThreshold: number; + + /** + * Default: true + */ + useProxy: boolean; + + /** + * Default: ['then', 'catch', 'inspect', 'toJSON'] + */ + proxyExcludedKeys: string[]; + + deepEqual: (expected: L, actual: R) => void; + } + + export type { ImportedAssertionError as AssertionError }; + } +} + +export function use(fn: Chai.ChaiPlugin): Chai.ChaiStatic; + +export const util: Chai.ChaiUtils; +export const config: Chai.Config; +export const Assertion: Chai.AssertionStatic; +export const AssertionError: typeof ImportedAssertionError; +export function should(): Chai.Should; +export function Should(): Chai.Should; +export const assert: Chai.AssertStatic; +export const expect: Chai.ExpectStatic; diff --git a/tools/ui/node_modules/@types/chai/package.json b/tools/ui/node_modules/@types/chai/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7aec8d1c6a5bb77179f810e2bdf2c560f613aa69 --- /dev/null +++ b/tools/ui/node_modules/@types/chai/package.json @@ -0,0 +1,75 @@ +{ + "name": "@types/chai", + "version": "5.2.3", + "description": "TypeScript definitions for chai", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/chai", + "license": "MIT", + "contributors": [ + { + "name": "Bart van der Schoor", + "githubUsername": "Bartvds", + "url": "https://github.com/Bartvds" + }, + { + "name": "Andrew Brown", + "githubUsername": "AGBrown", + "url": "https://github.com/AGBrown" + }, + { + "name": "Olivier Chevet", + "githubUsername": "olivr70", + "url": "https://github.com/olivr70" + }, + { + "name": "Matt Wistrand", + "githubUsername": "mwistrand", + "url": "https://github.com/mwistrand" + }, + { + "name": "Shaun Luttin", + "githubUsername": "shaunluttin", + "url": "https://github.com/shaunluttin" + }, + { + "name": "Satana Charuwichitratana", + "githubUsername": "micksatana", + "url": "https://github.com/micksatana" + }, + { + "name": "Erik Schierboom", + "githubUsername": "ErikSchierboom", + "url": "https://github.com/ErikSchierboom" + }, + { + "name": "Bogdan Paranytsia", + "githubUsername": "bparan", + "url": "https://github.com/bparan" + }, + { + "name": "CXuesong", + "githubUsername": "CXuesong", + "url": "https://github.com/CXuesong" + }, + { + "name": "Joey Kilpatrick", + "githubUsername": "joeykilpatrick", + "url": "https://github.com/joeykilpatrick" + } + ], + "type": "module", + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/chai" + }, + "scripts": {}, + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "d9d83f1594f42010e624e46e4c8cfeee284bdd04cb05eb0730aec14140f2a833", + "typeScriptVersion": "5.2" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/chai/register-should.d.ts b/tools/ui/node_modules/@types/chai/register-should.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e14f93b30749b96cc8153df52e4ab247597114c --- /dev/null +++ b/tools/ui/node_modules/@types/chai/register-should.d.ts @@ -0,0 +1,7 @@ +declare global { + interface Object { + should: Chai.Assertion; + } +} + +export {}; diff --git a/tools/ui/node_modules/@types/cookie/LICENSE b/tools/ui/node_modules/@types/cookie/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/cookie/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/cookie/README.md b/tools/ui/node_modules/@types/cookie/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d2811ae8533c36ead77fa781bc99657ffb70c064 --- /dev/null +++ b/tools/ui/node_modules/@types/cookie/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/cookie` + +# Summary +This package contains type definitions for cookie (https://github.com/jshttp/cookie). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cookie. + +### Additional Details + * Last updated: Sun, 26 Nov 2023 22:07:01 GMT + * Dependencies: none + +# Credits +These definitions were written by [Pine Mizune](https://github.com/pine), and [Piotr Błażejewicz](https://github.com/peterblazejewicz). diff --git a/tools/ui/node_modules/@types/cookie/index.d.ts b/tools/ui/node_modules/@types/cookie/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4800c73c6f6e66c3f00fc7f1c75203d1b7107156 --- /dev/null +++ b/tools/ui/node_modules/@types/cookie/index.d.ts @@ -0,0 +1,154 @@ +/** + * Basic HTTP cookie parser and serializer for HTTP servers. + */ + +/** + * Additional serialization options + */ +export interface CookieSerializeOptions { + /** + * Specifies the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.3|Domain Set-Cookie attribute}. By default, no + * domain is set, and most clients will consider the cookie to apply to only + * the current domain. + */ + domain?: string | undefined; + + /** + * Specifies a function that will be used to encode a cookie's value. Since + * value of a cookie has a limited character set (and must be a simple + * string), this function can be used to encode a value into a string suited + * for a cookie's value. + * + * The default function is the global `encodeURIComponent`, which will + * encode a JavaScript string into UTF-8 byte sequences and then URL-encode + * any that fall outside of the cookie range. + */ + encode?(value: string): string; + + /** + * Specifies the `Date` object to be the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.1|`Expires` `Set-Cookie` attribute}. By default, + * no expiration is set, and most clients will consider this a "non-persistent cookie" and will delete + * it on a condition like exiting a web browser application. + * + * *Note* the {@link https://tools.ietf.org/html/rfc6265#section-5.3|cookie storage model specification} + * states that if both `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is + * possible not all clients by obey this, so if both are set, they should + * point to the same date and time. + */ + expires?: Date | undefined; + /** + * Specifies the boolean value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.6|`HttpOnly` `Set-Cookie` attribute}. + * When truthy, the `HttpOnly` attribute is set, otherwise it is not. By + * default, the `HttpOnly` attribute is not set. + * + * *Note* be careful when setting this to true, as compliant clients will + * not allow client-side JavaScript to see the cookie in `document.cookie`. + */ + httpOnly?: boolean | undefined; + /** + * Specifies the number (in seconds) to be the value for the `Max-Age` + * `Set-Cookie` attribute. The given number will be converted to an integer + * by rounding down. By default, no maximum age is set. + * + * *Note* the {@link https://tools.ietf.org/html/rfc6265#section-5.3|cookie storage model specification} + * states that if both `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is + * possible not all clients by obey this, so if both are set, they should + * point to the same date and time. + */ + maxAge?: number | undefined; + /** + * Specifies the `boolean` value for the [`Partitioned` `Set-Cookie`](rfc-cutler-httpbis-partitioned-cookies) + * attribute. When truthy, the `Partitioned` attribute is set, otherwise it is not. By default, the + * `Partitioned` attribute is not set. + * + * **note** This is an attribute that has not yet been fully standardized, and may change in the future. + * This also means many clients may ignore this attribute until they understand it. + * + * More information about can be found in [the proposal](https://github.com/privacycg/CHIPS) + */ + partitioned?: boolean | undefined; + /** + * Specifies the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.4|`Path` `Set-Cookie` attribute}. + * By default, the path is considered the "default path". + */ + path?: string | undefined; + /** + * Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribute][rfc-west-cookie-priority-00-4.1]. + * + * - `'low'` will set the `Priority` attribute to `Low`. + * - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set. + * - `'high'` will set the `Priority` attribute to `High`. + * + * More information about the different priority levels can be found in + * [the specification][rfc-west-cookie-priority-00-4.1]. + * + * **note** This is an attribute that has not yet been fully standardized, and may change in the future. + * This also means many clients may ignore this attribute until they understand it. + */ + priority?: "low" | "medium" | "high" | undefined; + /** + * Specifies the boolean or string to be the value for the {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7|`SameSite` `Set-Cookie` attribute}. + * + * - `true` will set the `SameSite` attribute to `Strict` for strict same + * site enforcement. + * - `false` will not set the `SameSite` attribute. + * - `'lax'` will set the `SameSite` attribute to Lax for lax same site + * enforcement. + * - `'strict'` will set the `SameSite` attribute to Strict for strict same + * site enforcement. + * - `'none'` will set the SameSite attribute to None for an explicit + * cross-site cookie. + * + * More information about the different enforcement levels can be found in {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7|the specification}. + * + * *note* This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it. + */ + sameSite?: true | false | "lax" | "strict" | "none" | undefined; + /** + * Specifies the boolean value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.5|`Secure` `Set-Cookie` attribute}. When truthy, the + * `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set. + * + * *Note* be careful when setting this to `true`, as compliant clients will + * not send the cookie back to the server in the future if the browser does + * not have an HTTPS connection. + */ + secure?: boolean | undefined; +} + +/** + * Additional parsing options + */ +export interface CookieParseOptions { + /** + * Specifies a function that will be used to decode a cookie's value. Since + * the value of a cookie has a limited character set (and must be a simple + * string), this function can be used to decode a previously-encoded cookie + * value into a JavaScript string or other object. + * + * The default function is the global `decodeURIComponent`, which will decode + * any URL-encoded sequences into their byte representations. + * + * *Note* if an error is thrown from this function, the original, non-decoded + * cookie value will be returned as the cookie's value. + */ + decode?(value: string): string; +} + +/** + * Parse an HTTP Cookie header string and returning an object of all cookie + * name-value pairs. + * + * @param str the string representing a `Cookie` header value + * @param [options] object containing parsing options + */ +export function parse(str: string, options?: CookieParseOptions): Record; + +/** + * Serialize a cookie name-value pair into a `Set-Cookie` header string. + * + * @param name the name for the cookie + * @param value value to set the cookie to + * @param [options] object containing serialization options + * @throws {TypeError} when `maxAge` options is invalid + */ +export function serialize(name: string, value: string, options?: CookieSerializeOptions): string; diff --git a/tools/ui/node_modules/@types/cookie/package.json b/tools/ui/node_modules/@types/cookie/package.json new file mode 100644 index 0000000000000000000000000000000000000000..683b1e51683e6f57983299ce03e9a2564a96abeb --- /dev/null +++ b/tools/ui/node_modules/@types/cookie/package.json @@ -0,0 +1,30 @@ +{ + "name": "@types/cookie", + "version": "0.6.0", + "description": "TypeScript definitions for cookie", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cookie", + "license": "MIT", + "contributors": [ + { + "name": "Pine Mizune", + "githubUsername": "pine", + "url": "https://github.com/pine" + }, + { + "name": "Piotr Błażejewicz", + "githubUsername": "peterblazejewicz", + "url": "https://github.com/peterblazejewicz" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/cookie" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "0fbdf9c886fb40c8dc7677b8b7d0f9e02ac5235e163d90244a4fb9004736a575", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-array/LICENSE b/tools/ui/node_modules/@types/d3-array/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-array/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-array/README.md b/tools/ui/node_modules/@types/d3-array/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ef4ba6b18399f549e4b3ce827d9e968d3e3c7d28 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-array/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-array` + +# Summary +This package contains type definitions for d3-array (https://github.com/d3/d3-array). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-array. + +### Additional Details + * Last updated: Fri, 12 Sep 2025 20:02:35 GMT + * Dependencies: none + +# Credits +These definitions were written by [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [Tom Wanzek](https://github.com/tomwanzek), [denisname](https://github.com/denisname), [Hugues Stefanski](https://github.com/ledragon), [Nathan Bierema](https://github.com/Methuselah96), and [Fil](https://github.com/Fil). diff --git a/tools/ui/node_modules/@types/d3-array/index.d.ts b/tools/ui/node_modules/@types/d3-array/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..aa489e7676f906e6a86ee065429866bc76ec4eb1 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-array/index.d.ts @@ -0,0 +1,1118 @@ +// Last module patch version validated against: 3.2.4 + +// -------------------------------------------------------------------------- +// Shared Types and Interfaces +// -------------------------------------------------------------------------- + +/** + * Administrivia: JavaScript primitive types and Date + */ +export type Primitive = number | string | boolean | Date; + +/** + * Administrivia: anything with a valueOf(): number method is comparable, so we allow it in numeric operations + */ +export interface Numeric { + valueOf(): number; +} + +/** + * Administrivia: a matrix of numeric values. + * If height is not specified, it is inferred from the given width and data.length. + */ +export interface Matrix { + data: ArrayLike; + width: number; + height?: number; +} + +/** + * Represents a nested/recursive InternMap type + * + * The first generic "TObject" refers to the type of the data object that is available in the accessor functions. + * The second generic "TReduce" refers to the type of the data available at the deepest level (the result data). + * The third generic "TKeys" refers to the type of the keys at each level of the nestes InternMap. + */ +export type NestedInternMap = TKeys extends [infer TFirst, ...infer TRest] + ? InternMap> + : TReduce; + +/** + * Represents a nested/recursive Array type + * + * The first generic "TObject" refers to the type of the data object that is available in the accessor functions. + * The second generic "TReduce" refers to the type of the data available at the deepest level (the result data). + * The third generic "TKeys" refers to the type of the keys at each level of the nestes Array. + */ +export type NestedArray = TKeys extends [infer TFirst, ...infer TRest] + ? Array<[TFirst, NestedArray]> + : TReduce; + +// -------------------------------------------------------------------------------------- +// Statistics +// -------------------------------------------------------------------------------------- + +/** + * Return the minimum value in the array using natural order. + */ +export function min(iterable: Iterable): string | undefined; + +/** + * Return the minimum value in the array using natural order. + */ +export function min(iterable: Iterable): T | undefined; +/** + * Return the minimum value in the array using natural order. + */ +export function min( + iterable: Iterable, + accessor: (datum: T, index: number, array: Iterable) => string | undefined | null, +): string | undefined; +/** + * Return the minimum value in the array using natural order. + */ +export function min( + iterable: Iterable, + accessor: (datum: T, index: number, array: Iterable) => U | undefined | null, +): U | undefined; + +/** + * Return the index of the minimum value in the array using natural order. + */ +export function minIndex(iterable: Iterable): number; +/** + * Return the index of the minimum value in the array using natural order and a projection function to map values. + */ +export function minIndex( + iterable: Iterable, + accessor: (datum: TDatum, index: number, array: Iterable) => unknown, +): number; +/** + * Return the index of the minimum value in the array using natural order. + */ +export function minIndex(iterable: Iterable): number; + +/** + * Return the maximum value in the array of strings using natural order. + */ +export function max(iterable: Iterable): string | undefined; +/** + * Return the maximum value in the array of numbers using natural order. + */ +export function max(iterable: Iterable): T | undefined; +/** + * Return the maximum value in the array using natural order and a projection function to map values to strings. + */ +export function max( + iterable: Iterable, + accessor: (datum: T, index: number, array: Iterable) => string | undefined | null, +): string | undefined; +/** + * Return the maximum value in the array using natural order and a projection function to map values to easily-sorted values. + */ +export function max( + iterable: Iterable, + accessor: (datum: T, index: number, array: Iterable) => U | undefined | null, +): U | undefined; + +/** + * Return the index of the maximum value in the array using natural order. + */ +export function maxIndex(iterable: Iterable): number; +/** + * Return the index of the maximum value in the array using natural order and a projection function to map values. + */ +export function maxIndex( + iterable: Iterable, + accessor: (datum: TDatum, index: number, array: Iterable) => unknown, +): number; + +/** + * Return the min and max simultaneously. + */ +export function extent(iterable: Iterable): [string, string] | [undefined, undefined]; +/** + * Return the min and max simultaneously. + */ +export function extent(iterable: Iterable): [T, T] | [undefined, undefined]; +/** + * Return the min and max simultaneously. + */ +export function extent( + iterable: Iterable, + accessor: (datum: T, index: number, array: Iterable) => string | undefined | null, +): [string, string] | [undefined, undefined]; +/** + * Return the min and max simultaneously. + */ +export function extent( + iterable: Iterable, + accessor: (datum: T, index: number, array: Iterable) => U | undefined | null, +): [U, U] | [undefined, undefined]; + +/** + * Returns the mode of the given iterable, i.e. the value which appears the most often. + * In case of equality, returns the first of the relevant values. + * If the iterable contains no comparable values, returns undefined. + * An optional accessor function may be specified, which is equivalent to calling Array.from before computing the mode. + * This method ignores undefined, null and NaN values; this is useful for ignoring missing data. + */ +export function mode(iterable: Iterable): number; +/** + * Returns the mode of the given iterable, i.e. the value which appears the most often. + * In case of equality, returns the first of the relevant values. + * If the iterable contains no comparable values, returns undefined. + * An optional accessor function may be specified, which is equivalent to calling Array.from before computing the mode. + * This method ignores undefined, null and NaN values; this is useful for ignoring missing data. + */ +export function mode( + iterable: Iterable, + accessor: (datum: T, index: number, array: Iterable) => number | undefined | null, +): number; + +/** + * Compute the sum of an array of numbers. + */ +export function sum(iterable: Iterable): number; +/** + * Compute the sum of an array, using the given accessor to convert values to numbers. + */ +export function sum( + iterable: Iterable, + accessor: (datum: T, index: number, array: Iterable) => number | undefined | null, +): number; + +/** + * Return the mean of an array of numbers + */ +export function mean(iterable: Iterable): number | undefined; +/** + * Return the mean of an array of numbers + */ +export function mean( + iterable: Iterable, + accessor: (datum: T, index: number, array: Iterable) => number | undefined | null, +): number | undefined; + +/** + * Return the median of an array of numbers + */ +export function median(iterable: Iterable): number | undefined; +/** + * Return the median of an array of numbers + */ +export function median( + iterable: Iterable, + accessor: (element: T, i: number, array: Iterable) => number | undefined | null, +): number | undefined; + +/** + * Like median, but returns the index of the element to the left of the median. + */ +export function medianIndex(iterable: Iterable): number; +/** + * Like median, but returns the index of the element to the left of the median. + */ +export function medianIndex( + iterable: Iterable, + accessor: (element: T, i: number, array: Iterable) => number | undefined | null, +): number; + +/** + * Returns the cumulative sum of the given iterable of numbers, as a Float64Array of the same length. + * If the iterable contains no numbers, returns zeros. + * An optional accessor function may be specified, which is equivalent to calling Array.from before computing the cumulative sum. + * This method ignores undefined and NaN values; this is useful for ignoring missing data. + */ +export function cumsum(iterable: Iterable): Float64Array; +/** + * Returns the cumulative sum of the given iterable of numbers, as a Float64Array of the same length. + * If the iterable contains no numbers, returns zeros. + * An optional accessor function may be specified, which is equivalent to calling Array.from before computing the cumulative sum. + * This method ignores undefined and NaN values; this is useful for ignoring missing data. + */ +export function cumsum( + iterable: Iterable, + accessor: (element: T, i: number, array: Iterable) => number | undefined | null, +): Float64Array; + +/** + * Returns the p-quantile of the given iterable of numbers, where p is a number in the range [0, 1]. + * + * An optional accessor function may be specified, which is equivalent to calling array.map(accessor) before computing the quantile. + */ +export function quantile(iterable: Iterable, p: number): number | undefined; +/** + * Returns the p-quantile of the given iterable of numbers, where p is a number in the range [0, 1]. + * + * An optional accessor function may be specified, which is equivalent to calling array.map(accessor) before computing the quantile. + */ +export function quantile( + iterable: Iterable, + p: number, + accessor: (element: T, i: number, array: Iterable) => number | undefined | null, +): number | undefined; + +/** + * Similar to quantile, but returns the index to the left of p. + */ +export function quantileIndex(iterable: Iterable, p: number): number; +/** + * Similar to quantile, but returns the index to the left of p. + */ +export function quantileIndex( + iterable: Iterable, + p: number, + accessor: (element: T, i: number, array: Iterable) => number | undefined | null, +): number; + +/** + * Similar to quantile, but expects the input to be a sorted array of values. + * In contrast with quantile, the accessor is only called on the elements needed to compute the quantile. + */ +export function quantileSorted( + array: Array, + p: number, +): number | undefined; +/** + * Similar to quantile, but expects the input to be a sorted array of values. + * In contrast with quantile, the accessor is only called on the elements needed to compute the quantile. + */ +export function quantileSorted( + array: T[], + p: number, + accessor: (element: T, i: number, array: T[]) => number | undefined | null, +): number | undefined; + +/** + * Returns an array with the rank of each value in the iterable, i.e. the zero-based index of the value when the iterable is sorted. + * Nullish values are sorted to the end and ranked NaN. + * An optional comparator or accessor function may be specified; the latter is equivalent to calling array.map(accessor) before computing the ranks. + * If comparator is not specified, it defaults to ascending. + * Ties (equivalent values) all get the same rank, defined as the first time the value is found. + */ +export function rank(iterable: Iterable): Float64Array; +/** + * Returns an array with the rank of each value in the iterable, i.e. the zero-based index of the value when the iterable is sorted. + * Nullish values are sorted to the end and ranked NaN. + * An optional comparator or accessor function may be specified; the latter is equivalent to calling array.map(accessor) before computing the ranks. + * If comparator is not specified, it defaults to ascending. + * Ties (equivalent values) all get the same rank, defined as the first time the value is found. + */ +export function rank( + iterable: Iterable, + accessorOrComparator: + | ((datum: T, index: number, array: Iterable) => number | undefined | null) + | ((a: T, b: T) => number | undefined | null), +): Float64Array; + +/** + * Returns an unbiased estimator of the population variance of the given iterable of numbers using Welford’s algorithm. + * If the iterable has fewer than two numbers, returns undefined. + * An optional accessor function may be specified, which is equivalent to calling Array.from before computing the variance. + * This method ignores undefined and NaN values; this is useful for ignoring missing data. + */ +export function variance(iterable: Iterable): number | undefined; +/** + * Returns an unbiased estimator of the population variance of the given iterable of numbers using Welford’s algorithm. + * If the iterable has fewer than two numbers, returns undefined. + * An optional accessor function may be specified, which is equivalent to calling Array.from before computing the variance. + * This method ignores undefined and NaN values; this is useful for ignoring missing data. + */ +export function variance( + iterable: Iterable, + accessor: (datum: T, index: number, array: Iterable) => number | undefined | null, +): number | undefined; + +/** + * Compute the standard deviation, defined as the square root of the bias-corrected variance, of the given array of numbers. + */ +export function deviation(iterable: Iterable): number | undefined; +/** + * Compute the standard deviation, defined as the square root of the bias-corrected variance, of the given array, + * using the given accessor to convert values to numbers. + */ +export function deviation( + iterable: Iterable, + accessor: (datum: T, index: number, array: Iterable) => number | undefined | null, +): number | undefined; + +/** + * Returns a full precision summation of the given values. + * Although slower, d3.fsum can replace d3.sum wherever greater precision is needed. Uses d3.Adder. + */ +export function fsum(values: Iterable): number; +/** + * Returns a full precision summation of the given values. + * Although slower, d3.fsum can replace d3.sum wherever greater precision is needed. Uses d3.Adder. + */ +export function fsum( + values: Iterable, + accessor: (datum: T, index: number, array: Iterable) => number | undefined | null, +): number; + +/** + * Returns a full precision cumulative sum of the given values. + * Although slower, d3.fcumsum can replace d3.cumsum when greater precision is needed. Uses d3.Adder. + */ +export function fcumsum(values: Iterable): Float64Array; +/** + * Returns a full precision cumulative sum of the given values. + * Although slower, d3.fcumsum can replace d3.cumsum when greater precision is needed. Uses d3.Adder. + */ +export function fcumsum( + values: Iterable, + accessor: (datum: T, index: number, array: Iterable) => number | undefined | null, +): Float64Array; + +export class Adder { + /** + * Creates a full precision adder for IEEE 754 floating point numbers, setting its initial value to 0. + */ + constructor(); + + /** + * Adds the specified number to the adder’s current value and returns the adder. + */ + add(number: number): Adder; + + /** + * Returns the IEEE 754 double precision representation of the adder’s current value. + * Most useful as the short-hand notation +adder. + */ + valueOf(): number; +} + +// -------------------------------------------------------------------------------------- +// Search +// -------------------------------------------------------------------------------------- + +/** + * Returns the least element of the specified iterable according to the specified comparator. + * If comparator is not specified, it defaults to ascending. + */ +export function least(iterable: Iterable, comparator?: (a: T, b: T) => number): T | undefined; +/** + * Returns the least element of the specified iterable according to the specified accessor. + */ +export function least(iterable: Iterable, accessor: (a: T) => unknown): T | undefined; + +/** + * Returns the index of the least element of the specified iterable according to the specified comparator. + */ +export function leastIndex(iterable: Iterable): number | undefined; +/** + * Returns the index of the least element of the specified iterable according to the specified comparator. + */ +export function leastIndex(iterable: Iterable, comparator: (a: T, b: T) => number): number | undefined; +/** + * Returns the index of the least element of the specified iterable according to the specified accessor. + */ +// tslint:disable-next-line:unified-signatures +export function leastIndex(iterable: Iterable, accessor: (a: T) => unknown): number | undefined; + +/** + * Returns the greatest element of the specified iterable according to the specified comparator or accessor. + * If the given iterable contains no comparable elements (i.e., the comparator returns NaN when comparing each element to itself), returns undefined. + * If comparator is not specified, it defaults to ascending. + */ +export function greatest(iterable: Iterable, comparator?: (a: T, b: T) => number): T | undefined; +/** + * Returns the greatest element of the specified iterable according to the specified comparator or accessor. + * If the given iterable contains no comparable elements (i.e., the comparator returns NaN when comparing each element to itself), returns undefined. + * If comparator is not specified, it defaults to ascending. + */ +export function greatest(iterable: Iterable, accessor: (a: T) => unknown): T | undefined; + +/** + * Returns the index of the greatest element of the specified iterable according to the specified comparator or accessor. + * If the given iterable contains no comparable elements (i.e., the comparator returns NaN when comparing each element to itself), returns -1. + * If comparator is not specified, it defaults to ascending. + */ +export function greatestIndex(iterable: Iterable): number | undefined; +/** + * Returns the index of the greatest element of the specified iterable according to the specified comparator or accessor. + * If the given iterable contains no comparable elements (i.e., the comparator returns NaN when comparing each element to itself), returns -1. + * If comparator is not specified, it defaults to ascending. + */ +export function greatestIndex(iterable: Iterable, comparator: (a: T, b: T) => number): number | undefined; +/** + * Returns the index of the greatest element of the specified iterable according to the specified comparator or accessor. + * If the given iterable contains no comparable elements (i.e., the comparator returns NaN when comparing each element to itself), returns -1. + * If comparator is not specified, it defaults to ascending. + */ +// tslint:disable-next-line:unified-signatures +export function greatestIndex(iterable: Iterable, accessor: (a: T) => unknown): number | undefined; + +export function bisectLeft(array: ArrayLike, x: number, lo?: number, hi?: number): number; +export function bisectLeft(array: ArrayLike, x: string, lo?: number, hi?: number): number; +export function bisectLeft(array: ArrayLike, x: Date, lo?: number, hi?: number): number; + +export function bisectRight(array: ArrayLike, x: number, lo?: number, hi?: number): number; +export function bisectRight(array: ArrayLike, x: string, lo?: number, hi?: number): number; +export function bisectRight(array: ArrayLike, x: Date, lo?: number, hi?: number): number; + +export function bisectCenter(array: ArrayLike, x: number, lo?: number, hi?: number): number; +export function bisectCenter(array: ArrayLike, x: string, lo?: number, hi?: number): number; +export function bisectCenter(array: ArrayLike, x: Date, lo?: number, hi?: number): number; + +export const bisect: typeof bisectRight; + +export interface Bisector { + left(array: ArrayLike, x: U, lo?: number, hi?: number): number; + right(array: ArrayLike, x: U, lo?: number, hi?: number): number; + center(array: ArrayLike, x: U, lo?: number, hi?: number): number; +} + +export function bisector(comparator: (a: T, b: U) => number): Bisector; +// tslint:disable-next-line:unified-signatures +export function bisector(accessor: (x: T) => U): Bisector; + +/** + * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. + * + * @param array The array to partially sort (in place). + * @param k The middle index for partial sorting. + * @param left The left index of the range to sort. + * @param right The right index. + * @param compare The compare function. + */ +export function quickselect( + array: ArrayLike, + k: number, + left?: number, + right?: number, + compare?: (a: Primitive | undefined, b: Primitive | undefined) => number, +): T[]; + +// NB. this is limited to primitive values due to D3's use of the <, >, and >= operators. Results get weird for object instances. +/** + * Compares two primitive values for sorting (in ascending order). + */ +export function ascending(a: Primitive | undefined, b: Primitive | undefined): number; + +// NB. this is limited to primitive values due to D3's use of the <, >, and >= operators. Results get weird for object instances. +/** + * Compares two primitive values for sorting (in descending order). + */ +export function descending(a: Primitive | undefined, b: Primitive | undefined): number; + +// -------------------------------------------------------------------------------------- +// Transformations +// -------------------------------------------------------------------------------------- + +/** + * Groups the specified iterable of values into an InternMap from key to array of value. + * + * @param iterable The iterable to group. + * @param keys The key functions. + */ +export function group( + iterable: Iterable, + ...keys: { + [Index in keyof TKeys]: (value: TObject, index: number, values: TObject[]) => TKeys[Index]; + } +): NestedInternMap; + +/** + * Equivalent to group, but returns nested arrays instead of nested maps. + * + * @param iterable The iterable to group. + * @param keys The key functions. + */ +export function groups( + iterable: Iterable, + ...keys: { + [Index in keyof TKeys]: (value: TObject, index: number, values: TObject[]) => TKeys[Index]; + } +): NestedArray; + +/** + * Equivalent to group, but returns a flat array of [key0, key1, …, values] instead of nested maps. + * + * @param iterable The iterable to group. + * @param keys The key functions. + */ +export function flatGroup( + iterable: Iterable, + ...keys: { + [Index in keyof TKeys]: (value: TObject, index: number, values: TObject[]) => TKeys[Index]; + } +): Array<[...TKeys, TObject[]]>; + +/** + * Equivalent to group but returns a unique value per compound key instead of an array, throwing if the key is not unique. + * + * @param iterable The iterable to group. + * @param key The key functions. + */ +export function index( + iterable: Iterable, + ...keys: { + [Index in keyof TKeys]: (value: TObject, index: number, values: TObject[]) => TKeys[Index]; + } +): NestedInternMap; + +/** + * Equivalent to index, but returns nested arrays instead of nested maps. + * + * @param iterable The iterable to group. + * @param keys The key functions. + */ +export function indexes( + iterable: Iterable, + ...keys: { + [Index in keyof TKeys]: (value: TObject, index: number, values: TObject[]) => TKeys[Index]; + } +): NestedArray; + +/** + * Groups and reduces the specified array of values into an InternMap from key to value. + * + * @param iterable The iterable to group. + * @param reduce The reduce function. + * @param keys The key functions. + */ +export function rollup( + iterable: Iterable, + reduce: (values: TObject[]) => TReduce, + ...keys: { + [Index in keyof TKeys]: (value: TObject, index: number, values: TObject[]) => TKeys[Index]; + } +): NestedInternMap; + +/** + * Equivalent to rollup, but returns nested arrays instead of nested maps. + * + * @param iterable The iterable to group. + * @param reduce The reduce function. + * @param keys The key functions. + */ +export function rollups( + iterable: Iterable, + reduce: (values: TObject[]) => TReduce, + ...keys: { + [Index in keyof TKeys]: (value: TObject, index: number, values: TObject[]) => TKeys[Index]; + } +): NestedArray; + +/** + * Equivalent to rollup, but returns a flat array of [key0, key1, …, value] instead of nested maps. + * + * @param iterable The iterable to group. + * @param reduce The reduce function. + * @param keys The key functions. + */ +export function flatRollup( + iterable: Iterable, + reduce: (values: TObject[]) => TReduce, + ...keys: { + [Index in keyof TKeys]: (value: TObject, index: number, values: TObject[]) => TKeys[Index]; + } +): Array<[...TKeys, TReduce]>; + +/** + * Groups the specified iterable of elements according to the specified key function, sorts the groups according to the specified comparator, and then returns an array of keys in sorted order. + * The comparator will be asked to compare two groups a and b and should return a negative value if a should be before b, a positive value if a should be after b, or zero for a partial ordering. + */ +export function groupSort( + iterable: Iterable, + comparator: (a: TObject[], b: TObject[]) => number, + key: (value: TObject) => TKey, +): TKey[]; +/** + * Groups the specified iterable of elements according to the specified key function, sorts the groups according to the specified accessor, and then returns an array of keys in sorted order. + */ +export function groupSort( + iterable: Iterable, + // tslint:disable-next-line:unified-signatures + accessor: (value: TObject[]) => unknown, + key: (value: TObject) => TKey, +): TKey[]; + +/** + * Returns the number of valid number values (i.e., not null, NaN, or undefined) in the specified iterable; accepts an accessor. + * + * @param iterable Input array. + */ +export function count(iterable: Iterable): number; +/** + * Returns the number of valid number values (i.e., not null, NaN, or undefined) in the specified iterable; accepts an accessor. + * + * @param iterable Input array. + * @param accessor Accessor method. + */ +export function count( + iterable: Iterable, + accessor: (a: TObject, b: TObject) => number | null | undefined, +): number; + +/** + * Computes the Cartesian product of any number of iterables. + * + * When called **without** a reducer, the result is an array of tuples, + * where each tuple contains one element from each input iterable. + * + * @typeParam T - A tuple type describing the element type of each iterable argument. + * For example, passing `[number[], string[]]` infers `T` as `[number, string]`. + * + * @param iterables - Two or more iterables to combine into a Cartesian product. + * @returns An array of tuples containing one value from each iterable. + * + * @example + * ```ts + * const nums = [1, 2]; + * const chars = ['a', 'b']; + * const out = cross(nums, chars); + * // ^? type: [number, string][] + * // Example value: [[1,'a'], [1,'b'], [2,'a'], [2,'b']] + * ``` + */ +export function cross( + ...iterables: { [K in keyof T]: Iterable } +): T[]; + +/** + * Computes the Cartesian product of any number of iterables and then applies + * a reducer to each tuple, returning the reduced values. + * + * The final argument **must** be the reducer function; all prior arguments are iterables. + * + * @typeParam T - A tuple type describing the element type of each iterable argument. + * @typeParam U - The result type produced by the reducer. + * + * @param args - The iterables to combine, followed by a reducer function. + * @param args.reducer - A function invoked with one element from each iterable + * (spread as individual parameters) that returns a reduced value. + * @returns An array of reduced values returned by the reducer. + * + * @example + * ```ts + * const nums = [1, 2]; + * const chars = ['a', 'b']; + * const out = cross(nums, chars, (n, c) => `${n}${c}`); + * // ^? type: string[] + * // Example value: ['1a', '1b', '2a', '2b'] + * ``` + */ +export function cross( + ...args: [...iterables: { [K in keyof T]: Iterable }, reducer: (...values: T) => U] +): U[]; + +/** + * Merges the specified arrays into a single array. + */ +export function merge(iterables: Iterable>): T[]; + +/** + * For each adjacent pair of elements in the specified array, returns a new array of tuples of elements i and i - 1. + * Returns the empty array if the input array has fewer than two elements. + * + * @param iterable Array of input elements + */ +export function pairs(iterable: Iterable): Array<[T, T]>; +/** + * For each adjacent pair of elements in the specified array, in order, invokes the specified reducer function passing the element i and element i - 1. + * Returns the resulting array of pair-wise reduced elements. + * Returns the empty array if the input array has fewer than two elements. + * + * @param iterable Array of input elements + * @param reducer A reducer function taking as input to adjacent elements of the input array and returning a reduced value. + */ +export function pairs(iterable: Iterable, reducer: (a: T, b: T) => U): U[]; + +/** + * Returns a permutation of the specified source object (or array) using the specified iterable of keys. + * The returned array contains the corresponding property of the source object for each key in keys, in order. + * For example, `permute(["a", "b", "c"], [1, 2, 0]) // ["b", "c", "a"]` + * + * It is acceptable to have more keys than source elements, and for keys to be duplicated or omitted. + */ +export function permute(source: { [key: number]: T }, keys: Iterable): T[]; +/** + * Extract the values from an object into an array with a stable order. For example: + * `var object = {yield: 27, year: 1931, site: "University Farm"};` + * `d3.permute(object, ["site", "yield"]); // ["University Farm", 27]` + */ +export function permute(source: T, keys: Iterable): Array; + +/** + * Randomizes the order of the specified array using the Fisher–Yates shuffle. + */ +export function shuffle(array: T[], lo?: number, hi?: number): T[]; +export function shuffle(array: Int8Array, lo?: number, hi?: number): Int8Array; +export function shuffle(array: Uint8Array, lo?: number, hi?: number): Uint8Array; +export function shuffle(array: Uint8ClampedArray, lo?: number, hi?: number): Uint8ClampedArray; +export function shuffle(array: Int16Array, lo?: number, hi?: number): Int16Array; +export function shuffle(array: Uint16Array, lo?: number, hi?: number): Uint16Array; +export function shuffle(array: Int32Array, lo?: number, hi?: number): Int32Array; +export function shuffle(array: Uint32Array, lo?: number, hi?: number): Uint32Array; +export function shuffle(array: Float32Array, lo?: number, hi?: number): Float32Array; +export function shuffle(array: Float64Array, lo?: number, hi?: number): Float64Array; + +/** + * Returns a shuffle function given the specified random source. + */ +export function shuffler(random: () => number): typeof shuffle; + +/** + * Generate an array of approximately count + 1 uniformly-spaced, nicely-rounded values between start and stop (inclusive). + * Each value is a power of ten multiplied by 1, 2 or 5. See also d3.tickIncrement, d3.tickStep and linear.ticks. + * + * Ticks are inclusive in the sense that they may include the specified start and stop values if (and only if) they are exact, + * nicely-rounded values consistent with the inferred step. More formally, each returned tick t satisfies start ≤ t and t ≤ stop. + * + * @param start Start value for ticks + * @param stop Stop value for ticks + * @param count count + 1 is the approximate number of ticks to be returned by d3.ticks. + */ +export function ticks(start: number, stop: number, count: number): number[]; + +/** + * Returns the difference between adjacent tick values if the same arguments were passed to d3.ticks: + * a nicely-rounded value that is a power of ten multiplied by 1, 2 or 5. + * + * Like d3.tickStep, except requires that start is always less than or equal to stop, and if the tick step for the given start, + * stop and count would be less than one, returns the negative inverse tick step instead. + * + * This method is always guaranteed to return an integer, and is used by d3.ticks to avoid guarantee that the returned tick values + * are represented as precisely as possible in IEEE 754 floating point. + * + * @param start Start value for ticks + * @param stop Stop value for ticks + * @param count count + 1 is the approximate number of ticks to be returned by d3.ticks. + */ +export function tickIncrement(start: number, stop: number, count: number): number; + +/** + * Returns the difference between adjacent tick values if the same arguments were passed to d3.ticks: + * a nicely-rounded value that is a power of ten multiplied by 1, 2 or 5. + * + * Note that due to the limited precision of IEEE 754 floating point, the returned value may not be exact decimals; + * use d3-format to format numbers for human consumption. + * + * @param start Start value for ticks + * @param stop Stop value for ticks + * @param count count + 1 is the approximate number of ticks to be returned by d3.ticks. + */ +export function tickStep(start: number, stop: number, count: number): number; + +/** + * Returns a new interval [niceStart, niceStop] covering the given interval [start, stop] and where niceStart and niceStop are guaranteed to align with the corresponding tick step. + * Like d3.tickIncrement, this requires that start is less than or equal to stop. + * + * @param start Start value for ticks + * @param stop Stop value for ticks + * @param count count + 1 is the approximate number of ticks to be returned by d3.ticks. + */ +export function nice(start: number, stop: number, count: number): [number, number]; + +/** + * Generates a 0-based numeric sequence. The output range does not include 'stop'. + */ +export function range(stop: number): number[]; +/** + * Generates a numeric sequence starting from the given start and stop values. 'step' defaults to 1. The output range does not include 'stop'. + */ +// tslint:disable-next-line:unified-signatures +export function range(start: number, stop: number, step?: number): number[]; + +/** + * Transpose a matrix provided in Array of Arrays format. + */ +export function transpose(matrix: ArrayLike>): T[][]; + +/** + * Returns an array of arrays, where the ith array contains the ith element from each of the argument arrays. + * The returned array is truncated in length to the shortest array in arrays. If arrays contains only a single array, the returned array + * contains one-element arrays. With no arguments, the returned array is empty. + */ +export function zip(...arrays: Array>): T[][]; + +// -------------------------------------------------------------------------------------- +// Blur +// -------------------------------------------------------------------------------------- + +/** + * Blurs an array of data in-place by applying three iterations of a moving average transform (box filter) + * for a fast approximation of a Gaussian kernel of the given radius, a non-negative number. + * Returns the given data. + */ +export function blur(data: ArrayLike, radius: number): ArrayLike; + +/** + * Blurs a matrix of the given width and height in-place by applying a horizontal blur of radius rx + * and a vertical blur of radius ry (which defaults to rx). + * The matrix values data are stored in a flat (one-dimensional) array. + * If height is not specified, it is inferred from the given width and data.length. + * Returns the blurred matrix {data, width, height}. + */ +export function blur2(data: Matrix, rx: number, ry?: number): Matrix; + +/** + * Blurs the given ImageData in-place, blurring each of the RGBA layers independently by applying an horizontal blur of radius rx + * and a vertical blur of radius ry (which defaults to rx). + * Returns the blurred ImageData. + */ +export function blurImage(imageData: ImageData, rx: number, ry?: number): ImageData; + +// -------------------------------------------------------------------------------------- +// Iterables +// -------------------------------------------------------------------------------------- + +/** + * Returns true if the given test function returns true for every value in the given iterable. + * This method returns as soon as test returns a non-truthy value or all values are iterated over. + * Equivalent to array.every. + */ +export function every( + iterable: Iterable, + test: (value: T, index: number, iterable: Iterable) => unknown, +): boolean; + +/** + * Returns true if the given test function returns true for any value in the given iterable. + * This method returns as soon as test returns a truthy value or all values are iterated over. + * Equivalent to array.some. + */ +export function some( + iterable: Iterable, + test: (value: T, index: number, iterable: Iterable) => unknown, +): boolean; + +/** + * Returns a new array containing the values from iterable, in order, for which the given test function returns true. + * Equivalent to array.filter. + */ +export function filter( + iterable: Iterable, + test: (value: T, index: number, iterable: Iterable) => unknown, +): T[]; + +/** + * Returns a new array containing the mapped values from iterable, in order, as defined by given mapper function. + * Equivalent to array.map and Array.from. + */ +export function map(iterable: Iterable, mapper: (value: T, index: number, iterable: Iterable) => U): U[]; + +/** + * Returns the reduced value defined by given reducer function, which is repeatedly invoked for each value in iterable, being passed the current reduced value and the next value. + * Equivalent to array.reduce. + */ +export function reduce( + iterable: Iterable, + reducer: (previousValue: T, currentValue: T, currentIndex: number, iterable: Iterable) => T, + initialValue?: T, +): T; +/** + * Returns the reduced value defined by given reducer function, which is repeatedly invoked for each value in iterable, being passed the current reduced value and the next value. + * Equivalent to array.reduce. + */ +export function reduce( + iterable: Iterable, + reducer: (previousValue: U, currentValue: T, currentIndex: number, iterable: Iterable) => U, + initialValue: U, +): U; + +/** + * Returns an array containing the values in the given iterable in reverse order. + * Equivalent to array.reverse, except that it does not mutate the given iterable. + */ +export function reverse(iterable: Iterable): T[]; + +/** + * Returns an array containing the values in the given iterable in the sorted order defined by the given comparator function. + * If comparator is not specified, it defaults to d3.ascending. + * Equivalent to array.sort, except that it does not mutate the given iterable, and the comparator defaults to natural order instead of lexicographic order. + */ +export function sort(iterable: Iterable, comparator?: (a: T, b: T) => number): T[]; +/** + * Returns an array containing the values in the given iterable in the sorted order defined by the given accessor function. + * This is equivalent to a comparator using natural order. + * The accessor is only invoked once per element, and thus may be nondeterministic. + * Multiple accessors may be specified to break ties. + */ +export function sort(iterable: Iterable, ...accessors: Array<(a: T) => unknown>): T[]; + +// -------------------------------------------------------------------------------------- +// Sets +// -------------------------------------------------------------------------------------- + +/** + * Returns a new InternSet containing every value in iterable that is not in any of the others iterables. + */ +export function difference(iterable: Iterable, ...others: Array>): InternSet; + +/** + * Returns a new InternSet containing every (distinct) value that appears in any of the given iterables. + * The order of values in the returned set is based on their first occurrence in the given iterables. + */ +export function union(...iterables: Array>): InternSet; + +/** + * Returns a new InternSet containing every (distinct) value that appears in all of the given iterables. + * The order of values in the returned set is based on their first occurrence in the given iterables. + */ +export function intersection(...iterables: Array>): InternSet; + +/** + * Returns true if a is a superset of b: if every value in the given iterable b is also in the given iterable a. + */ +export function superset(a: Iterable, b: Iterable): boolean; + +/** + * Returns true if a is a subset of b: if every value in the given iterable a is also in the given iterable b. + */ +export function subset(a: Iterable, b: Iterable): boolean; + +/** + * Returns true if a and b are disjoint: if a and b contain no shared value. + */ +export function disjoint(a: Iterable, b: Iterable): boolean; + +// -------------------------------------------------------------------------------------- +// Bins +// -------------------------------------------------------------------------------------- + +export interface Bin extends Array { + x0: Value | undefined; + x1: Value | undefined; +} + +/** + * Type definition for threshold generator which returns the count of recommended thresholds + */ +export type ThresholdCountGenerator = ( + values: ArrayLike, + min: number, + max: number, +) => number; + +/** + * Type definition for threshold generator which returns an array of recommended numbers thresholds + */ +export type ThresholdNumberArrayGenerator = ( + values: ArrayLike, + min: number, + max: number, +) => Value[]; + +/** + * Type definition for threshold generator which returns an array of recommended dates thresholds + */ +export type ThresholdDateArrayGenerator = ( + values: ArrayLike, + min: Date, + max: Date, +) => Value[]; + +export interface HistogramCommon { + (data: ArrayLike): Array>; + + value(): (d: Datum, i: number, data: ArrayLike) => Value; + value(valueAccessor: (d: Datum, i: number, data: ArrayLike) => Value): this; +} + +export interface HistogramGeneratorDate extends HistogramCommon { + domain(): (values: ArrayLike) => [Date, Date]; + domain(domain: [Date, Date] | ((values: ArrayLike) => [Date, Date])): this; + + thresholds(): ThresholdDateArrayGenerator; + /** + * Set the array of values to be used as thresholds in determining the bins. + * + * Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value, + * and the last bin.x1 is always equal to the maximum domain value. + * + * @param thresholds Either an array of threshold values used for binning. The elements must + * be of the same type as the materialized values of the histogram. + * Or a function which accepts as arguments the array of materialized values, and + * optionally the domain minimum and maximum. The function calculates and returns the array of values to be used as + * thresholds in determining the bins. + */ + thresholds(thresholds: ArrayLike | ThresholdDateArrayGenerator): this; +} + +export interface HistogramGeneratorNumber + extends HistogramCommon +{ + domain(): (values: Iterable) => [number, number] | [undefined, undefined]; + domain(domain: [number, number] | ((values: Iterable) => [number, number] | [undefined, undefined])): this; + + thresholds(): ThresholdCountGenerator | ThresholdNumberArrayGenerator; + /** + * Divide the domain uniformly into approximately count bins. IMPORTANT: This threshold + * setting approach only works, when the materialized values are numbers! + * + * Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value, + * and the last bin.x1 is always equal to the maximum domain value. + * + * @param count Either the desired number of uniform bins or a function which accepts as arguments the array of + * materialized values, and optionally the domain minimum and maximum. The function calculates and returns the + * suggested number of bins. + */ + thresholds(count: number | ThresholdCountGenerator): this; + /** + * Set the array of values to be used as thresholds in determining the bins. + * + * Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value, + * and the last bin.x1 is always equal to the maximum domain value. + * + * @param thresholds Either an array of threshold values used for binning. The elements must + * be of the same type as the materialized values of the histogram. + * Or a function which accepts as arguments the array of materialized values, and + * optionally the domain minimum and maximum. The function calculates and returns the array of values to be used as + * thresholds in determining the bins. + */ + // tslint:disable-next-line:unified-signatures + thresholds(thresholds: ArrayLike | ThresholdNumberArrayGenerator): this; +} + +/** + * @deprecated Use bin instead. + */ +export function histogram(): HistogramGeneratorNumber; + +/** + * @deprecated Use bin instead. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function histogram(): HistogramGeneratorNumber; + +/** + * @deprecated Use bin instead. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function histogram(): HistogramGeneratorDate; + +export function bin(): HistogramGeneratorNumber; +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function bin(): HistogramGeneratorNumber; +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function bin(): HistogramGeneratorDate; + +// -------------------------------------------------------------------------------------- +// Histogram Thresholds +// -------------------------------------------------------------------------------------- + +export function thresholdFreedmanDiaconis(values: ArrayLike, min: number, max: number): number; // of type ThresholdCountGenerator + +export function thresholdScott(values: ArrayLike, min: number, max: number): number; // of type ThresholdCountGenerator + +export function thresholdSturges(values: ArrayLike): number; // of type ThresholdCountGenerator + +// -------------------------------------------------------------------------------------- +// Interning +// -------------------------------------------------------------------------------------- + +/** + * The InternMap class extends the native JavaScript Map class, allowing Dates and other non-primitive keys by bypassing the SameValueZero algorithm when determining key equality. + */ +export class InternMap extends Map { +} + +/** + * The InternSet class extends the native JavaScript Set class, allowing Dates and other non-primitive keys by bypassing the SameValueZero algorithm when determining key equality. + */ +export class InternSet extends Set { +} diff --git a/tools/ui/node_modules/@types/d3-array/package.json b/tools/ui/node_modules/@types/d3-array/package.json new file mode 100644 index 0000000000000000000000000000000000000000..59a3c9d43c9dd13e4094af90a11953c1a7016c99 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-array/package.json @@ -0,0 +1,56 @@ +{ + "name": "@types/d3-array", + "version": "3.2.2", + "description": "TypeScript definitions for d3-array", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-array", + "license": "MIT", + "contributors": [ + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "Hugues Stefanski", + "githubUsername": "ledragon", + "url": "https://github.com/ledragon" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + }, + { + "name": "Fil", + "githubUsername": "Fil", + "url": "https://github.com/Fil" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-array" + }, + "scripts": {}, + "dependencies": {}, + "peerDependencies": {}, + "typesPublisherContentHash": "d8ff015b14e99aec79f6ac45682bd8237145131c804b94de0ed1e6bc003d5190", + "typeScriptVersion": "5.2" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-axis/LICENSE b/tools/ui/node_modules/@types/d3-axis/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-axis/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-axis/README.md b/tools/ui/node_modules/@types/d3-axis/README.md new file mode 100644 index 0000000000000000000000000000000000000000..da6c440a7f9f1c7320b5eba4d8a183c50d7fba98 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-axis/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-axis` + +# Summary +This package contains type definitions for d3-axis (https://github.com/d3/d3-axis/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-axis. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:36 GMT + * Dependencies: [@types/d3-selection](https://npmjs.com/package/@types/d3-selection) + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [denisname](https://github.com/denisname), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-axis/index.d.ts b/tools/ui/node_modules/@types/d3-axis/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..72e0342f4b6d8b8d05c3b447560934ee708ed98e --- /dev/null +++ b/tools/ui/node_modules/@types/d3-axis/index.d.ts @@ -0,0 +1,293 @@ +// Last module patch version validated against: 3.0.0 + +import { Selection, TransitionLike } from "d3-selection"; + +// -------------------------------------------------------------------------- +// Shared Types and Interfaces +// -------------------------------------------------------------------------- + +/** + * A helper type to alias elements which can serve as a domain for an axis. + */ +export type AxisDomain = number | string | Date | { valueOf(): number }; + +/** + * A helper interface to describe the minimal contract to be met by a time interval + * which can be passed into the Axis.ticks(...) or Axis.tickArguments(...) methods when + * creating time series axes. Under normal circumstances the argument will be of type + * TimeInterval or CountableTimeInterval as defined in d3-time. + * NB: This helper interface has been created to avoid tight coupling of d3-axis to + * d3-time at the level of definition files. I.e. d3-time is not a + * dependency of d3-axis in the D3 Javascript implementation. This minimal contract + * is based on an analysis of how d3-axis passes a time interval argument into a time scale, + * if a time scale was set using Axis.scale(...). And in turn on how a time scale uses + * the time interval when creating ticks from it. + */ +export interface AxisTimeInterval { + range(start: Date, stop: Date, step?: number): Date[]; +} + +/** + * A helper interface to which a scale passed into axis must conform (at a minimum) + * for axis to use the scale without error. + */ +export interface AxisScale { + (x: Domain): number | undefined; + domain(): Domain[]; + range(): number[]; + copy(): this; + bandwidth?(): number; + // TODO: Reconsider the below, note that the compiler does not differentiate the overloads w.r.t. optionality + // ticks?(count?: number): Domain[]; + // ticks?(count?: AxisTimeInterval): Date[]; + // tickFormat?(count?: number, specifier?: string): ((d: number) => string); + // tickFormat?(count?: number | AxisTimeInterval, specifier?: string): ((d: Date) => string); +} + +/** + * A helper type to alias elements which can serve as a container for an axis. + */ +export type AxisContainerElement = SVGSVGElement | SVGGElement; + +/** + * Interface defining an axis generator. The generic is the type of the axis domain. + */ +export interface Axis { + /** + * Render the axis to the given context. + * + * @param context A selection of or a transition defined on SVG containers (either SVG or G elements). + */ + ( + context: + | Selection + | Selection + | TransitionLike + | TransitionLike, + ): void; + + /** + * Gets the current scale underlying the axis. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + scale>(): A; + + /** + * Sets the scale and returns the axis. + * + * @param scale The scale to be used for axis generation. + */ + scale(scale: AxisScale): this; + + /** + * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. + * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * + * This method is also a convenience function for axis.tickArguments. + * + * @param count Number of ticks that should be rendered. + * @param specifier An optional format specifier to customize how the tick values are formatted. + */ + ticks(count: number, specifier?: string): this; + + /** + * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. + * Use with a TIME SCALE ONLY. + * + * This method is also a convenience function for axis.tickArguments. + * + * @param interval A time interval used to generate date-based ticks. This is typically a TimeInterval/CountableTimeInterval as defined + * in d3-time. E.g. as obtained by passing in d3.timeMinute.every(15). + * @param specifier An optional format specifier to customize how the tick values are formatted. + */ + // tslint:disable-next-line:unified-signatures + ticks(interval: AxisTimeInterval, specifier?: string): this; + + /** + * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. + * + * The meaning of the arguments depends on the axis’ scale type: most commonly, the arguments are a suggested count for the number of ticks + * (or a time interval for time scales), and an optional format specifier to customize how the tick values are formatted. + * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * This method is also a convenience function for axis.tickArguments. + */ + ticks(arg0: any, ...args: any[]): this; + + /** + * Get an array containing the currently set arguments to be passed into scale.ticks and scale.tickFormat, which defaults to the empty array. + */ + tickArguments(): any[]; + + /** + * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. + * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * See also axis.ticks. + * + * @param args The meaning of the arguments depends on the axis’ scale type: most commonly, the arguments are a + * suggested count for the number of ticks (or a time interval for time scales), and an optional format specifier to + * customize how the tick values are formatted. + */ + tickArguments(args: any[]): this; + + /** + * Returns the current tick values, which defaults to null. + */ + tickValues(): Domain[] | null; + + /** + * Specified values to be used for ticks rather than using the scale’s automatic tick generator. + * The explicit tick values take precedent over the tick arguments set by axis.tickArguments. + * However, any tick arguments will still be passed to the scale’s tickFormat function if a + * tick format is not also set. + * + * @param values An iterable with values from the Domain of the scale underlying the axis. + */ + tickValues(values: Iterable): this; + + /** + * Clears any previously-set explicit tick values and reverts back to the scale’s tick generator. + * + * @param values null + */ + tickValues(values: null): this; + + /** + * Returns the currently set tick format function, which defaults to null. + */ + tickFormat(): ((domainValue: Domain, index: number) => string) | null; + + /** + * Sets the tick format function and returns the axis. + * + * @param format A function mapping a value from the axis Domain to a formatted string + * for display purposes. When invoked, the format function is also passed a second argument representing the zero-based index + * of the tick label in the array of generated tick labels. + */ + tickFormat(format: (domainValue: Domain, index: number) => string): this; + + /** + * Reset the tick format function. A null format indicates that the scale’s + * default formatter should be used, which is generated by calling scale.tickFormat. + * In this case, the arguments specified by axis.tickArguments + * are likewise passed to scale.tickFormat. + * + * @param format null + */ + tickFormat(format: null): this; + + /** + * Get the current inner tick size, which defaults to 6. + */ + tickSize(): number; + /** + * Set the inner and outer tick size to the specified value and return the axis. + * + * @param size Tick size in pixels (Default is 6). + */ + tickSize(size: number): this; + + /** + * Get the current inner tick size, which defaults to 6. + * The inner tick size controls the length of the tick lines, + * offset from the native position of the axis. + */ + tickSizeInner(): number; + + /** + * Set the inner tick size to the specified value and return the axis. + * The inner tick size controls the length of the tick lines, + * offset from the native position of the axis. + * + * @param size Tick size in pixels (Default is 6). + */ + tickSizeInner(size: number): this; + + /** + * Get the current outer tick size, which defaults to 6. + * The outer tick size controls the length of the square ends of the domain path, + * offset from the native position of the axis. Thus, the “outer ticks” are not actually + * ticks but part of the domain path, and their position is determined by the associated + * scale’s domain extent. Thus, outer ticks may overlap with the first or last inner tick. + * An outer tick size of 0 suppresses the square ends of the domain path, + * instead producing a straight line. + */ + tickSizeOuter(): number; + + /** + * Set the current outer tick size and return the axis. + * The outer tick size controls the length of the square ends of the domain path, + * offset from the native position of the axis. Thus, the “outer ticks” are not actually + * ticks but part of the domain path, and their position is determined by the associated + * scale’s domain extent. Thus, outer ticks may overlap with the first or last inner tick. + * An outer tick size of 0 suppresses the square ends of the domain path, + * instead producing a straight line. + * + * @param size Tick size in pixels (Default is 6). + */ + tickSizeOuter(size: number): this; + + /** + * Get the current padding, which defaults to 3. + */ + tickPadding(): number; + + /** + * Set the current padding and return the axis. + * + * @param padding Padding in pixels (Default is 3). + */ + tickPadding(padding: number): this; + + /** + * Returns the current offset which defaults to 0 on devices with a devicePixelRatio greater than 1, and 0.5px otherwise. + * This default offset ensures crisp edges on low-resolution devices. + */ + offset(): number; + + /** + * Sets the offset to the specified value in pixels and returns the axis. + * Defaults to 0 on devices with a devicePixelRatio greater than 1, and 0.5px otherwise. + * This default offset ensures crisp edges on low-resolution devices. + */ + offset(offset: number): this; +} + +/** + * Constructs a new top-oriented axis generator for the given scale, with empty tick arguments, + * a tick size of 6 and padding of 3. In this orientation, ticks are drawn above the horizontal domain path. + * + * @param scale The scale to be used for axis generation. + */ +export function axisTop(scale: AxisScale): Axis; + +/** + * Constructs a new right-oriented axis generator for the given scale, with empty tick arguments, + * a tick size of 6 and padding of 3. In this orientation, ticks are drawn to the right of the vertical domain path. + * + * @param scale The scale to be used for axis generation. + */ +export function axisRight(scale: AxisScale): Axis; + +/** + * Constructs a new bottom-oriented axis generator for the given scale, with empty tick arguments, + * a tick size of 6 and padding of 3. In this orientation, ticks are drawn below the horizontal domain path. + * + * @param scale The scale to be used for axis generation. + */ +export function axisBottom(scale: AxisScale): Axis; + +/** + * Constructs a new left-oriented axis generator for the given scale, with empty tick arguments, + * a tick size of 6 and padding of 3. In this orientation, ticks are drawn to the left of the vertical domain path. + * + * @param scale The scale to be used for axis generation. + */ +export function axisLeft(scale: AxisScale): Axis; diff --git a/tools/ui/node_modules/@types/d3-axis/package.json b/tools/ui/node_modules/@types/d3-axis/package.json new file mode 100644 index 0000000000000000000000000000000000000000..112041689097ee4968b85b44d39c8728487f3e34 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-axis/package.json @@ -0,0 +1,47 @@ +{ + "name": "@types/d3-axis", + "version": "3.0.6", + "description": "TypeScript definitions for d3-axis", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-axis", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-axis" + }, + "scripts": {}, + "dependencies": { + "@types/d3-selection": "*" + }, + "typesPublisherContentHash": "54b1b488ceb700b459aa9157899d313ddf4dce4c5b9677facd2289f810392a79", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-brush/LICENSE b/tools/ui/node_modules/@types/d3-brush/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-brush/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-brush/README.md b/tools/ui/node_modules/@types/d3-brush/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cbf18df1caf853063a288bd7289b072a401659ad --- /dev/null +++ b/tools/ui/node_modules/@types/d3-brush/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-brush` + +# Summary +This package contains type definitions for d3-brush (https://github.com/d3/d3-brush/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-brush. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:36 GMT + * Dependencies: [@types/d3-selection](https://npmjs.com/package/@types/d3-selection) + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-brush/index.d.ts b/tools/ui/node_modules/@types/d3-brush/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..48f7607ed1eb5e618227165919cd9cfd47c3f1e4 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-brush/index.d.ts @@ -0,0 +1,255 @@ +// Last module patch version validated against: 3.0.0 + +import { Selection, TransitionLike, ValueFn } from "d3-selection"; + +/** + * Type alias for a BrushSelection. For a two-dimensional brush, it must be defined as [[x0, y0], [x1, y1]], + * where x0 is the minimum x-value, y0 is the minimum y-value, x1 is the maximum x-value, and y1 is the maximum y-value. + * For an x-brush, it must be defined as [x0, x1]; for a y-brush, it must be defined as [y0, y1]. + */ +export type BrushSelection = [[number, number], [number, number]] | [number, number]; + +/** + * A D3 brush behavior + * + * The generic refers to the type of the datum for the group element on which brush behavior is defined. + */ +export interface BrushBehavior { + /** + * Applies the brush to the specified group, which must be a selection of SVG G elements. + * This function is typically not invoked directly, and is instead invoked via selection.call. + * + * For details see: {@link https://github.com/d3/d3-brush#_brush} + * + * @param group A D3 selection of SVG G elements. + * @param args Optional arguments to be passed in. + */ + (group: Selection, ...args: any[]): void; + /** + * Clear the active selection of the brush on the specified SVG G element(s) selection. + * + * @param group A selection or a transition of SVG G elements + * @param selection The selection must be defined as an array of numbers, or null to clear the brush selection. + * For a two-dimensional brush, it must be defined as [[x0, y0], [x1, y1]], where x0 is the minimum x-value, y0 is the minimum y-value, x1 is the maximum x-value, and y1 is the maximum y-value. + * For an x-brush, it must be defined as [x0, x1]; for a y-brush, it must be defined as [y0, y1]. + * The selection may also be specified as a function which returns such an array; + * if a function, it is invoked for each selected element, being passed the current datum d and index i, with the this context as the current DOM element. + * The returned array defines the brush selection for that element. + * @param event + */ + move( + group: Selection | TransitionLike, + selection: null | BrushSelection | ValueFn, + event?: Event, + ): void; + + /** + * Clear the active selection of the brush on the specified SVG G element(s) selection. + * + * @param group A D3 selection of SVG G elements. + * @param event + */ + clear(group: Selection, event?: Event): void; + + /** + * Returns the current extent accessor. + */ + extent(): ValueFn; + /** + * Set the brushable extent to the specified array of points and returns this brush. + * + * The brush extent determines the size of the invisible overlay and also constrains the brush selection; + * the brush selection cannot go outside the brush extent. + * + * @param extent array of points [[x0, y0], [x1, y1]], where [x0, y0] is the top-left corner + * and [x1, y1] is the bottom-right corner. + */ + extent(extent: [[number, number], [number, number]]): this; + /** + * Set the brushable extent to the specified array of points returned by the accessor function + * evaluated for each element in the selection/transition and returns this brush. + * + * The brush extent determines the size of the invisible overlay and also constrains the brush selection; + * the brush selection cannot go outside the brush extent. + * + * @param extent An extent accessor function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element. The function returns an array of points [[x0, y0], [x1, y1]], + * where [x0, y0] is the top-left corner and [x1, y1] is the bottom-right corner. + */ + extent(extent: ValueFn): this; + + /** + * Returns the current filter function. + */ + filter(): (this: SVGGElement, event: any, d: Datum) => boolean; + /** + * Sets the filter to the specified filter function and returns the brush. + * + * If the filter returns falsey, the initiating event is ignored and no brush gesture is started. + * Thus, the filter determines which input events are ignored. The default filter ignores mousedown events on secondary buttons, + * since those buttons are typically intended for other purposes, such as the context menu. + * + * @param filterFn A filter function which is evaluated for each selected element, + * in order, being passed the current event `event` and datum `d`, with the `this` context as the current DOM element. + * The function returns a boolean value. + */ + filter(filterFn: (this: SVGGElement, event: any, d: Datum) => boolean): this; + + /** + * Returns the current touch support detector, which defaults to a function returning true, + * if the "ontouchstart" event is supported on the current element. + */ + touchable(): ValueFn; + /** + * Sets the touch support detector to the specified boolean value and returns the brush. + * + * Touch event listeners are only registered if the detector returns truthy for the corresponding element when the brush is applied. + * The default detector works well for most browsers that are capable of touch input, but not all; Chrome’s mobile device emulator, for example, + * fails detection. + * + * @param touchable A boolean value. true when touch event listeners should be applied to the corresponding element, otherwise false. + */ + touchable(touchable: boolean): this; + /** + * Sets the touch support detector to the specified function and returns the drag behavior. + * + * Touch event listeners are only registered if the detector returns truthy for the corresponding element when the brush is applied. + * The default detector works well for most browsers that are capable of touch input, but not all; Chrome’s mobile device emulator, for example, + * fails detection. + * + * @param touchable A touch support detector function, which returns true when touch event listeners should be applied to the corresponding element. + * The function is evaluated for each selected element to which the brush was applied, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element. The function returns a boolean value. + */ + touchable(touchable: ValueFn): this; + + /** + * Returns the current key modifiers flag. + */ + keyModifiers(): boolean; + /** + * Sets the key modifiers flag and returns the brush. + * + * The key modifiers flag determines whether the brush listens to key events during brushing. + * The default value is true. + * + * @param modifiers New value for key modifiers flag. + */ + keyModifiers(modifiers: boolean): this; + + /** + * Returns the current handle size, which defaults to six. + */ + handleSize(): number; + /** + * Sets the size of the brush handles to the specified number and returns the brush. + * + * This method must be called before applying the brush to a selection; + * changing the handle size does not affect brushes that were previously rendered. + * The default size is 6. + * + * @param size Size of the handle. + */ + handleSize(size: number): this; + + /** + * Returns the first currently-assigned listener matching the specified typenames, if any. + * + * @param typenames The typenames is a string containing one or more typename separated by whitespace. + * Each typename is a type, optionally followed by a period (.) and a name, such as "brush.foo"" and "brush.bar"; + * the name allows multiple listeners to be registered for the same type. The type must be one of the following: + * start (at the start of a brush gesture, such as on mousedown), brush (when the brush moves, such as on mousemove), or + * end (at the end of a brush gesture, such as on mouseup.) + */ + on(typenames: string): ((this: SVGGElement, event: any, d: Datum) => void) | undefined; + /** + * Removes the current event listeners for the specified typenames, if any. + * + * @param typenames The typenames is a string containing one or more typename separated by whitespace. + * Each typename is a type, optionally followed by a period (.) and a name, such as "brush.foo"" and "brush.bar"; + * the name allows multiple listeners to be registered for the same type. The type must be one of the following: + * start (at the start of a brush gesture, such as on mousedown), brush (when the brush moves, such as on mousemove), or + * end (at the end of a brush gesture, such as on mouseup.) + * @param listener Use null to remove the listener. + */ + on(typenames: string, listener: null): this; + /** + * Sets the event listener for the specified typenames and returns the brush. + * If an event listener was already registered for the same type and name, + * the existing listener is removed before the new listener is added. + * When a specified event is dispatched, each listener will be invoked with the same context and arguments as selection.on listeners. + * + * @param typenames The typenames is a string containing one or more typename separated by whitespace. + * Each typename is a type, optionally followed by a period (.) and a name, such as "brush.foo"" and "brush.bar"; + * the name allows multiple listeners to be registered for the same type. The type must be one of the following: + * start (at the start of a brush gesture, such as on mousedown), brush (when the brush moves, such as on mousemove), or + * end (at the end of a brush gesture, such as on mouseup.) + * @param listener An event listener function which is evaluated for each selected element, + * in order, being passed the current event `event` and datum `d`, with the `this` context as the current DOM element. + */ + on(typenames: string, listener: (this: SVGGElement, event: any, d: Datum) => void): this; +} + +/** + * Create a new two-dimensional brush. + * + * The generic "Datum" refers to the type of the data of the selected svg:g element to + * which the returned BrushBehavior will be applied. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function brush(): BrushBehavior; +/** + * Creates a new one-dimensional brush along the x-dimension. + * + * The generic "Datum" refers to the type of the data of the selected svg:g element to + * which the returned BrushBehavior will be applied. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function brushX(): BrushBehavior; +/** + * Creates a new one-dimensional brush along the y-dimension. + * + * The generic "Datum" refers to the type of the data of the selected svg:g element to + * which the returned BrushBehavior will be applied. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function brushY(): BrushBehavior; + +/** + * Return the current brush selection for the specified node. Internally, an element’s brush state is stored as element.__brush; + * however, you should use this method rather than accessing it directly. If the given node has no selection, returns null. + * Otherwise, the selection is defined as an array of numbers. + * + * @param node The node for which the brush selection should be returned. + */ +export function brushSelection(node: SVGGElement): BrushSelection | null; + +/** + * D3 brush event + * + * The generic refers to the type of the datum for the group element on which brush was defined. + */ +export interface D3BrushEvent { + /** + * The BrushBehavior associated with the event + */ + target: BrushBehavior; + /** + * The event type for the BrushEvent + */ + type: "start" | "brush" | "end" | string; // Leave failsafe string type for cases like 'brush.foo' + /** + * The current brush selection associated with the event. + * This is null when the selection is empty. + */ + selection: BrushSelection | null; + /** + * The underlying input event, such as mousemove or touchmove. + */ + sourceEvent: any; + /** + * The mode of the brush. + */ + mode: "drag" | "space" | "handle" | "center"; +} diff --git a/tools/ui/node_modules/@types/d3-brush/package.json b/tools/ui/node_modules/@types/d3-brush/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a1fa8a565f5b211e81904c32def4a1c976bef9f5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-brush/package.json @@ -0,0 +1,42 @@ +{ + "name": "@types/d3-brush", + "version": "3.0.6", + "description": "TypeScript definitions for d3-brush", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-brush", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-brush" + }, + "scripts": {}, + "dependencies": { + "@types/d3-selection": "*" + }, + "typesPublisherContentHash": "9236bf058564aa97984c8fb6e4ef96b84e6221485def99fbb4aebaccf68e0367", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-chord/LICENSE b/tools/ui/node_modules/@types/d3-chord/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-chord/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-chord/README.md b/tools/ui/node_modules/@types/d3-chord/README.md new file mode 100644 index 0000000000000000000000000000000000000000..16eada802686078a80639232548eefaa566c70e9 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-chord/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-chord` + +# Summary +This package contains type definitions for d3-chord (https://github.com/d3/d3-chord/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-chord. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:36 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-chord/index.d.ts b/tools/ui/node_modules/@types/d3-chord/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2e70ad326304c684a9569d1af8e2221423bbe47f --- /dev/null +++ b/tools/ui/node_modules/@types/d3-chord/index.d.ts @@ -0,0 +1,471 @@ +// Last module patch version validated against: 3.0.1 + +// --------------------------------------------------------------------- +// Chord +// --------------------------------------------------------------------- + +/** + * A chord subgroup serving as source or target of a chord between two nodes i an j (where i may be equal to j). + */ +export interface ChordSubgroup { + /** + * Start angle of the chord subgroup in radians + */ + startAngle: number; + + /*** + * End angle of the chord subgroup in radians + */ + endAngle: number; + + /** + * The flow value in matrix[i][j] from node i to node j + */ + value: number; + + /** + * The node index i + */ + index: number; +} + +/** + * A chord represents the combined bidirectional flow between two nodes i and j (where i may be equal to j) + */ +export interface Chord { + /** + * Chord subgroup constituting the source of Chord + */ + source: ChordSubgroup; + /** + * Chord subgroup constituting the Target of Chord + */ + target: ChordSubgroup; +} + +/** + * A chord group for a given node i representing the combined outflow for node i, + * corresponding to the elements matrix[i][0 … n - 1]. + */ +export interface ChordGroup { + /** + * The start angle of the chord group in radians + */ + startAngle: number; + + /** + * The end angle of the chord group in radians + */ + endAngle: number; + + /** + * The total outgoing flow value for node i + */ + value: number; + + /** + * The node index i + */ + index: number; +} + +/** + * An array of chords, where each chord represents the combined bidirectional flow between two nodes i and j (where i may be equal to j). + * The chords are based on a (n x n) matrix of flows between nodes. + * + * The chords are typically passed to d3.ribbon to display the network relationships. + * The returned array includes only chord objects for which the value matrix[i][j] or matrix[j][i] is non-zero. + * Furthermore, the returned array only contains unique chords: a given chord ij represents the bidirectional flow from i to j and from j to i, + * and does not contain a duplicate chord ji; i and j are chosen such that the chord’s source always represents the larger of matrix[i][j] and matrix[j][i]. + * In other words, chord.source.index equals chord.target.subindex, chord.source.subindex equals chord.target.index, + * chord.source.value is greater than or equal to chord.target.value, and chord.source.value is always greater than zero. + */ +export interface Chords extends Array { + /** + * An array of length n, where each group represents the combined outflow for node i, + * corresponding to the elements matrix[i][0 … n - 1] + */ + groups: ChordGroup[]; +} + +/** + * A D3 chord diagram Layout to visualize relationships or network flow with an aesthetically-pleasing circular layout. + * + * The relationships are represented as a square matrix of size n×n, where the matrix represents the directed flow amongst a network (a complete digraph) of n nodes. + */ +export interface ChordLayout { + /** + * Computes the chord layout for the specified square matrix of size n×n, where the matrix represents the directed flow amongst a network (a complete digraph) of n nodes. + * + * @param matrix An (n x n) matrix representing the directed flow amongst a network (a complete digraph) of n nodes.The given matrix must be an array of length n, + * where each element matrix[i] is an array of n numbers, where each matrix[i][j] represents the flow from the ith node in the network to the jth node. + * Each number matrix[i][j] must be nonnegative, though it can be zero if there is no flow from node i to node j. + */ + (matrix: number[][]): Chords; + + /** + * Returns the current pad angle in radians, which defaults to zero. + */ + padAngle(): number; + /** + * Sets the pad angle between adjacent groups to the specified number in radians and returns this chord layout. + * + * The default is zero. + * + * @param angle Pad angle between adjacent groups in radians. + */ + padAngle(angle: number): this; + + /** + * Returns the current group comparator, which defaults to null. + */ + sortGroups(): ((a: number, b: number) => number) | null; + /** + * Sets the group comparator to the specified function or null and returns this chord layout. + * If the group comparator is non-null, it is used to sort the groups by their total outflow. + * See also d3.ascending and d3.descending. + */ + sortGroups(compare: null | ((a: number, b: number) => number)): this; + + /** + * Returns the current subgroup comparator, which defaults to null. + */ + sortSubgroups(): ((a: number, b: number) => number) | null; + /** + * Sets the subgroup comparator to the specified function or null and returns this chord layout. + * If the subgroup comparator is non-null, it is used to sort the subgroups corresponding to matrix[i][0 … n - 1] for a given group i by their total outflow. + * See also d3.ascending and d3.descending. + */ + sortSubgroups(compare: null | ((a: number, b: number) => number)): this; + + /** + * Returns the current chord comparator, which defaults to null. + */ + sortChords(): ((a: number, b: number) => number) | null; + /** + * Sets the chord comparator to the specified function or null and returns this chord layout. + * If the chord comparator is non-null, it is used to sort the chords by their combined flow; this only affects the z-order of the chords. + * See also d3.ascending and d3.descending. + */ + sortChords(compare: null | ((a: number, b: number) => number)): this; +} + +/** + * Constructs a new chord diagram layout with the default settings. + */ +export function chord(): ChordLayout; + +/** + * A chord layout for directional flows. The chord from i to j is generated from the value in matrix[i][j] only. + */ +export function chordDirected(): ChordLayout; + +/** + * A transposed chord layout. Useful to highlight outgoing (rather than incoming) flows. + */ +export function chordTranspose(): ChordLayout; + +// --------------------------------------------------------------------- +// Ribbon +// --------------------------------------------------------------------- + +/** + * A minimal interface to support the default accessors used by RibbonGenerator for properties of + * source and target objects of a Ribbon. + * + * (Corresponds to ChordSubgroup) + */ +export interface RibbonSubgroup { + /** + * Start angle of the ribbon subgroup in radians + */ + startAngle: number; + /** + * End angle of the ribbon subgroup in radians + */ + endAngle: number; + /** + * Radius of the ribbon subgroup + */ + radius: number; +} + +/** + * A minimal interface to support the default source and target accessors used by RibbonGenerator. + * (Corresponds to Chord) + */ +export interface Ribbon { + /** + * Ribbon subgroup constituting the source of the Ribbon + */ + source: RibbonSubgroup; + /** + * Ribbon subgroup constituting the target of the Ribbon + */ + target: RibbonSubgroup; +} + +/** + * A ribbon generator to support rendering of chords in a chord diagram. + * + * The first generic corresponds to the type of the "this" context within which the ribbon generator and its accessor functions will be invoked. + * + * The second generic corresponds to the datum type representing a chord for which the ribbon is to be generated. The default type is Ribbon. + * + * The third generic corresponds to the datum type of the chord subgroup, i.e. source or target of the cord. The default type is RibbonSubgroup. + */ +export interface RibbonGenerator { + /** + * Generates a ribbon for the given arguments. + * + * IMPORTANT: If the ribbon generator has been configured with a rendering context, + * then the ribbon is rendered to this context as a sequence of path method calls and this function returns void. + * + * The "this" context within which this function is invoked, will be the context within which the accessor methods of the generator are invoked. + * All arguments passed into this function, will be passed to the accessor functions of the generator. + * + * @param d The datum representing the chord for which the ribbon is to be generated. + */ + (this: This, d: RibbonDatum, ...args: any[]): void; + /** + * Generates a ribbon for the given arguments. + * + * IMPORTANT: If the rendering context of the ribbon generator is null, + * then the ribbon is returned as a path data string. + * + * The "this" context within which this function is invoked, will be the context within which the accessor methods of the generator are invoked. + * All arguments passed into this function, will be passed to the accessor functions of the generator. + * + * @param d The datum representing the chord for which the ribbon is to be generated. + */ + (this: This, d: RibbonDatum, ...args: any[]): string | null; + + /** + * Returns the current source accessor, which defaults to a function returning the "source" property of the first argument passed into the accessor. + */ + source(): (this: This, d: RibbonDatum, ...args: any[]) => RibbonSubgroupDatum; + /** + * Sets the source accessor to the specified function and returns this ribbon generator. + * + * @param source An accessor function returning the source datum of the chord. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives the same arguments that were passed into the ribbon generator. + */ + source(source: (this: This, d: RibbonDatum, ...args: any[]) => RibbonSubgroupDatum): this; + + /** + * Returns the current target accessor, which defaults to a function returning the "target" property of the first argument passed into the accessor. + */ + target(): (this: This, d: RibbonDatum, ...args: any[]) => RibbonSubgroupDatum; + /** + * Sets the target accessor to the specified function and returns this ribbon generator. + * + * @param target An accessor function returning the target datum of the chord. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives the same arguments that were passed into the ribbon generator. + */ + target(target: (this: This, d: RibbonDatum, ...args: any[]) => RibbonSubgroupDatum): this; + + /** + * Returns the current radius accessor, which defaults to a function returning the "radius" property (assumed to be a number) of the source or + * target object returned by the source or target accessor, respectively. + */ + radius(): (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number; + /** + * Sets the radius to a fixed number and returns this ribbon generator. + * + * @param radius A fixed numeric value for the radius. + */ + radius(radius: number): this; + /** + * Sets the radius accessor to the specified function and returns this ribbon generator. + * + * @param radius An accessor function which is invoked for the source and target of the chord. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. + * It is also passed any additional arguments that were passed into the generator, with the exception of the first element representing the chord datum itself. + * The function returns the radius value. + */ + radius(radius: (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number): this; + + /** + * Returns the current source radius accessor, which defaults to a function returning the "radius" property (assumed to be a number) of the source or + * target object returned by the source or target accessor, respectively. + */ + sourceRadius(): (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number; + /** + * Sets the source radius to a fixed number and returns this ribbon generator. + * + * @param radius A fixed numeric value for the source radius. + */ + sourceRadius(radius: number): this; + /** + * Sets the source radius accessor to the specified function and returns this ribbon generator. + * + * @param radius An accessor function which is invoked for the source and target of the chord. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. + * It is also passed any additional arguments that were passed into the generator, with the exception of the first element representing the chord datum itself. + * The function returns the source radius value. + */ + sourceRadius(radius: (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number): this; + + /** + * Returns the current target radius accessor, which defaults to a function returning the "radius" property (assumed to be a number) of the source or + * target object returned by the source or target accessor, respectively. + */ + targetRadius(): (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number; + /** + * Sets the target radius to a fixed number and returns this ribbon generator. + * + * @param radius A fixed numeric value for the target radius. + */ + targetRadius(radius: number): this; + /** + * Sets the target radius accessor to the specified function and returns this ribbon generator. + * + * @param radius An accessor function which is invoked for the source and target of the chord. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. + * It is also passed any additional arguments that were passed into the generator, with the exception of the first element representing the chord datum itself. + * The function returns the target radius value. + */ + targetRadius(radius: (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number): this; + + /** + * Returns the current start angle accessor, which defaults to a function returning the "startAngle" property (assumed to be a number in radians) of the source or + * target object returned by the source or target accessor, respectively. + */ + startAngle(): (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number; + /** + * Sets the start angle to a fixed number in radians and returns this ribbon generator. + * + * @param angle A fixed numeric value for the start angle in radians. + */ + startAngle(angle: number): this; + /** + * Sets the start angle accessor to the specified function and returns this ribbon generator. + * + * @param angle An accessor function which is invoked for the source and target of the chord. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. + * It is also passed any additional arguments that were passed into the generator, with the exception of the first element representing the chord datum itself. + * The function returns the start angle in radians. + */ + startAngle(angle: (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number): this; + + /** + * Returns the current end angle accessor, which defaults to a function returning the "endAngle" property (assumed to be a number in radians) of the source or + * target object returned by the source or target accessor, respectively. + */ + endAngle(): (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number; + /** + * Sets the end angle to a fixed number in radians and returns this ribbon generator. + * + * @param angle A fixed numeric value for the end angle in radians. + */ + endAngle(angle: number): this; + /** + * Sets the end angle accessor to the specified function and returns this ribbon generator. + * + * @param angle An accessor function which is invoked for the source and target of the chord. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. + * It is also passed any additional arguments that were passed into the generator, with the exception of the first element representing the chord datum itself. + * The function returns the end angle in radians. + */ + endAngle(angle: (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number): this; + + /** + * Returns the current pad angle accessor, which defaults to a function returning 0. + */ + padAngle(): (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number; + /** + * Sets the pad angle to a fixed number in radians and returns this ribbon generator. + * + * @param angle A fixed numeric value for the pad angle in radians. + */ + padAngle(angle: number): this; + /** + * Sets the pad angle accessor to the specified function and returns this ribbon generator. + * + * @param angle An accessor function which is invoked for the source and target of the chord. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. + * It is also passed any additional arguments that were passed into the generator, with the exception of the first element representing the chord datum itself. + * The function returns the pad angle in radians. + */ + padAngle(angle: (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number): this; + + /** + * Returns the current rendering context, which defaults to null. + */ + context(): CanvasRenderingContext2D | null; + /** + * Sets the context and returns this ribbon generator. + * If the context is not null, then the generated ribbon is rendered to this context as a sequence of path method calls. + * Otherwise, a path data string representing the generated ribbon is returned. + * See also d3-path. + */ + context(context: CanvasRenderingContext2D | null): this; +} + +export interface RibbonArrowGenerator + extends RibbonGenerator +{ + headRadius(): (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number; + + headRadius(radius: number): this; + + headRadius(radius: (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number): this; +} + +/** + * Creates a new ribbon generator with the default settings. + */ +export function ribbon(): RibbonGenerator; +/** + * Creates a new ribbon generator with the default settings. + * + * Accessor functions must be configured for the ribbon generator, should the datum types differ from the defaults. + * + * The first generic corresponds to the datum type representing a chord for which the ribbon is to be generated. The default type is Chord. + * + * The second generic corresponds to the datum type of the chord subgroup, i.e. source or target of the cord. The default type is ChordSubgroup. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function ribbon(): RibbonGenerator; +/** + * Creates a new ribbon generator with the default settings. + * + * Accessor functions must be configured for the ribbon generator, should the datum types differ from the defaults. + * + * The first generic corresponds to the type of the "this" context within which the ribbon generator and its accessor functions will be invoked. + * + * The second generic corresponds to the datum type representing a chord for which the ribbon is to be generated. The default type is Chord. + * + * The third generic corresponds to the datum type of the chord subgroup, i.e. source or target of the cord. The default type is ChordSubgroup. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function ribbon(): RibbonGenerator; + +/** + * Creates a new arrow ribbon generator with the default settings. + */ +export function ribbonArrow(): RibbonArrowGenerator; +/** + * Creates a new arrow ribbon generator with the default settings. + * + * Accessor functions must be configured for the ribbon generator, should the datum types differ from the defaults. + * + * The first generic corresponds to the datum type representing a chord for which the ribbon is to be generated. The default type is Chord. + * + * The second generic corresponds to the datum type of the chord subgroup, i.e. source or target of the cord. The default type is ChordSubgroup. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function ribbonArrow(): RibbonArrowGenerator; +/** + * Creates a new arrow ribbon generator with the default settings. + * + * Accessor functions must be configured for the ribbon generator, should the datum types differ from the defaults. + * + * The first generic corresponds to the type of the "this" context within which the ribbon generator and its accessor functions will be invoked. + * + * The second generic corresponds to the datum type representing a chord for which the ribbon is to be generated. The default type is Chord. + * + * The third generic corresponds to the datum type of the chord subgroup, i.e. source or target of the cord. The default type is ChordSubgroup. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function ribbonArrow(): RibbonArrowGenerator; diff --git a/tools/ui/node_modules/@types/d3-chord/package.json b/tools/ui/node_modules/@types/d3-chord/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f1e1926dcfcfc8ad72bff00ac13c1b31b9accab6 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-chord/package.json @@ -0,0 +1,40 @@ +{ + "name": "@types/d3-chord", + "version": "3.0.6", + "description": "TypeScript definitions for d3-chord", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-chord", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-chord" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "4b753915a8486b9468d72bb011600af470757b5a78e0fefe46a9315e12c94140", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-color/LICENSE b/tools/ui/node_modules/@types/d3-color/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-color/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-color/README.md b/tools/ui/node_modules/@types/d3-color/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b4b375b8d272872ae5f278b00e76c9481f1cd609 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-color/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-color` + +# Summary +This package contains type definitions for d3-color (https://github.com/d3/d3-color/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-color. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:36 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [denisname](https://github.com/denisname), [Hugues Stefanski](https://github.com/ledragon), [Nathan Bierema](https://github.com/Methuselah96), and [Fil](https://github.com/Fil). diff --git a/tools/ui/node_modules/@types/d3-color/index.d.ts b/tools/ui/node_modules/@types/d3-color/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ffcfae7ab591e0c30ac116825538fb051b43817 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-color/index.d.ts @@ -0,0 +1,669 @@ +// Last module patch version validated against: 3.1.0 + +// --------------------------------------------------------------------------- +// Shared Type Definitions and Interfaces +// --------------------------------------------------------------------------- + +/** + * Type allowing for color objects from a specified color space + */ +export type ColorSpaceObject = RGBColor | HSLColor | LabColor | HCLColor | CubehelixColor; + +/** + * A helper interface of methods common to color objects (including colors defined outside the d3-color standard module, + * e.g. in d3-hsv). This interface + */ +export interface ColorCommonInstance { + /** + * Returns true if and only if the color is displayable on standard hardware. + * For example, this returns false for an RGB color if any channel value is less than zero or greater than 255, or if the opacity is not in the range [0, 1]. + */ + displayable(): boolean; + /** + * Returns a string representing this color according to the CSS Object Model specification, + * such as rgb(247, 234, 186) or rgba(247, 234, 186, 0.2). + * If this color is not displayable, a suitable displayable color is returned instead. + * For example, RGB channel values greater than 255 are clamped to 255. + */ + toString(): string; + /** + * Returns a brighter copy of this color. If k is specified, it controls how much brighter the returned color should be. + * If k is not specified, it defaults to 1. The behavior of this method is dependent on the implementing color space. + * + * @param k A color space dependent number to determine, how much brighter the returned color should be. + */ + brighter(k?: number): this; + /** + * Returns a darker copy of this color. If k is specified, it controls how much darker the returned color should be. + * If k is not specified, it defaults to 1. The behavior of this method is dependent on the implementing color space. + * + * @param k A color space dependent number to determine, how much darker the returned color should be. + */ + darker(k?: number): this; + /** + * Returns the RGB equivalent of this color. For RGB colors, that’s "this". + */ + rgb(): RGBColor; + /** + * Returns a hexadecimal string representing this color. + * If this color is not displayable, a suitable displayable color is returned instead. + * For example, RGB channel values greater than 255 are clamped to 255. + */ + hex(): string; +} + +/** + * A Color object which serves as a base class for + * colorspace-specific sub-class implementations. + */ +export interface Color { + /** + * Returns true if and only if the color is displayable on standard hardware. + * For example, this returns false for an RGB color if any channel value is less than zero or greater than 255, or if the opacity is not in the range [0, 1]. + */ + displayable(): boolean; // Note: While this method is used in prototyping for colors of specific colorspaces, it should not be called directly, as 'this.rgb' would not be implemented on Color + /** + * Returns a string representing this color according to the CSS Object Model specification, + * such as rgb(247, 234, 186) or rgba(247, 234, 186, 0.2). + * If this color is not displayable, a suitable displayable color is returned instead. + * For example, RGB channel values greater than 255 are clamped to 255. + */ + toString(): string; // Note: While this method is used in prototyping for colors of specific colorspaces, it should not be called directly, as 'this.rgb' would not be implemented on Color + /** + * Returns a hexadecimal string representing this color in RGB space, such as #f7eaba. + * If this color is not displayable, a suitable displayable color is returned instead. + * For example, RGB channel values greater than 255 are clamped to 255. + */ + formatHex(): string; + /** + * Returns a hexadecimal string representing this color in RGBA space, such as #f7eaba90. + * If this color is not displayable, a suitable displayable color is returned instead. + * For example, RGB channel values greater than 255 are clamped to 255. + */ + formatHex8(): string; + /** + * Returns a string representing this color according to the CSS Color Module Level 3 specification, such as hsl(257, 50%, 80%) or hsla(257, 50%, 80%, 0.2). + * If this color is not displayable, a suitable displayable color is returned instead by clamping S and L channel values to the interval [0, 100]. + */ + formatHsl(): string; + /** + * Returns a string representing this color according to the CSS Object Model specification, such as rgb(247, 234, 186) or rgba(247, 234, 186, 0.2). + * If this color is not displayable, a suitable displayable color is returned instead by clamping RGB channel values to the interval [0, 255]. + */ + formatRgb(): string; + /** + * @deprecated Use color.formatHex. + */ + hex(): string; +} + +/** + * A Color factory object, which may also be used with instanceof to test if an object is a color instance. + */ +export interface ColorFactory extends Function { + /** + * Parses the specified CSS Color Module Level 3 specifier string, returning an RGB or HSL color. + * If the specifier was not valid, null is returned. + * + * @param cssColorSpecifier A CSS Color Module Level 3 specifier string. + */ + (cssColorSpecifier: string): RGBColor | HSLColor | null; + /** + * Converts the provided color instance and returns an RGB or HSL color. + * + * @param color A permissible color space instance. + */ + (color: ColorSpaceObject | ColorCommonInstance): RGBColor | HSLColor; + /** + * Prototype of the factory, which can be used for instanceof testing + */ + readonly prototype: Color; +} + +/** + * An RGB color object. + */ +export interface RGBColor extends Color { + /** + * Value of red channel + */ + r: number; + /** + * Value of green channel + */ + g: number; + /** + * Value of blue channel + */ + b: number; + /** + * Opacity value + */ + opacity: number; + /** + * Returns a brighter copy of this color. If k is specified, it controls how much brighter the returned color should be. + * If k is not specified, it defaults to 1. + * + * @param k A color space dependent number to determine, how much brighter the returned color should be. + */ + brighter(k?: number): this; + /** + * Returns a darker copy of this color. If k is specified, it controls how much darker the returned color should be. + * If k is not specified, it defaults to 1. + * + * @param k A color space dependent number to determine, how much darker the returned color should be. + */ + darker(k?: number): this; + /** + * Returns the RGB equivalent of this color. + */ + rgb(): this; + /** + * Returns a copy of this color. + * + * @param values If values is specified, any enumerable own properties of values are assigned to the new returned color. + */ + copy( + values?: { + r?: number | undefined; + g?: number | undefined; + b?: number | undefined; + opacity?: number | undefined; + }, + ): this; + /** + * Returns a new RGB color where the r, g, and b channels are clamped to the range [0, 255] and rounded to the nearest integer value, + * and the opacity is clamped to the range [0, 1]. + */ + clamp(): this; +} + +/** + * An RGB color factory object, which may also be used with instanceof to test if an object + * is an RGB color instance. + */ +export interface RGBColorFactory extends Function { + /** + * Constructs a new RGB color based on the specified channel values and opacity. + * + * @param r Red channel value. + * @param g Green channel value. + * @param b Blue channel value. + * @param opacity Optional opacity value, defaults to 1. + */ + (r: number, g: number, b: number, opacity?: number): RGBColor; + /** + * Parses the specified CSS Color Module Level 3 specifier string, returning an RGB color. + * If the specifier was not valid, null is returned. + * + * @param cssColorSpecifier A CSS Color Module Level 3 specifier string. + */ + (cssColorSpecifier: string): RGBColor; + /** + * Converts the provided color instance and returns an RGB color. The color instance is converted to the RGB color space using color.rgb. + * Note that unlike color.rgb this method always returns a new instance, even if color is already an RGB color. + * + * @param color A permissible color space instance. + */ + // tslint:disable-next-line:unified-signatures + (color: ColorSpaceObject | ColorCommonInstance): RGBColor; + /** + * Prototype of the factory, which can be used for instanceof testing + */ + readonly prototype: RGBColor; +} + +/** + * An HSL color object. + */ +export interface HSLColor extends Color { + /** + * Hue channel value. + */ + h: number; + /** + * Saturation channel value. + */ + s: number; + /** + * Lightness channel value. + */ + l: number; + /** + * Opacity value. + */ + opacity: number; + /** + * Returns a brighter copy of this color. If k is specified, it controls how much brighter the returned color should be. + * If k is not specified, it defaults to 1. + * + * @param k A color space dependent number to determine, how much brighter the returned color should be. + */ + brighter(k?: number): this; + /** + * Returns a darker copy of this color. If k is specified, it controls how much darker the returned color should be. + * If k is not specified, it defaults to 1. + * + * @param k A color space dependent number to determine, how much darker the returned color should be. + */ + darker(k?: number): this; + /** + * Returns the RGB color equivalent of this color. + */ + rgb(): RGBColor; + /** + * Returns a copy of this color. + * + * @param values If values is specified, any enumerable own properties of values are assigned to the new returned color. + */ + copy( + values?: { + h?: number | undefined; + s?: number | undefined; + l?: number | undefined; + opacity?: number | undefined; + }, + ): this; + /** + * Returns a new HSL color where the h channel is clamped to the range [0, 360), and the s, l, and opacity channels are clamped to the range [0, 1]. + */ + clamp(): this; +} + +/** + * An HSL color factory object, which may also be used with instanceof to test if an object + * is an HSL color instance. + */ +export interface HSLColorFactory extends Function { + /** + * Constructs a new HSL color based on the specified channel values and opacity. + * + * @param h Hue channel value. + * @param s Saturation channel value. + * @param l Lightness channel value. + * @param opacity Optional opacity value, defaults to 1. + */ + (h: number, s: number, l: number, opacity?: number): HSLColor; + /** + * Parses the specified CSS Color Module Level 3 specifier string, returning an HSL color. + * If the specifier was not valid, null is returned. + * + * @param cssColorSpecifier A CSS Color Module Level 3 specifier string. + */ + (cssColorSpecifier: string): HSLColor; + /** + * Converts the provided color instance and returns an HSL color. + * The color instance is converted to the RGB color space using color.rgb and then converted to HSL. + * (Colors already in the HSL color space skip the conversion to RGB.) + * + * @param color A permissible color space instance. + */ + // tslint:disable-next-line:unified-signatures + (color: ColorSpaceObject | ColorCommonInstance): HSLColor; + /** + * Prototype of the factory, which can be used for instanceof testing + */ + readonly prototype: HSLColor; +} + +/** + * A Lab (CIELAB) color object. + */ +export interface LabColor extends Color { + /** + * Lightness typically in the range [0, 100]. + */ + l: number; + /** + * Position between red/magenta and green typically in [-160, +160]. + */ + a: number; + /** + * Position between yellow and blue typically in [-160, +160]. + */ + b: number; + /** + * Opacity value + */ + opacity: number; + /** + * Returns a brighter copy of this color. If k is specified, it controls how much brighter the returned color should be. + * If k is not specified, it defaults to 1. + * + * @param k A color space dependent number to determine, how much brighter the returned color should be. + */ + brighter(k?: number): this; + /** + * Returns a darker copy of this color. If k is specified, it controls how much darker the returned color should be. + * If k is not specified, it defaults to 1. + * + * @param k A color space dependent number to determine, how much darker the returned color should be. + */ + darker(k?: number): this; + /** + * Returns the RGB color equivalent of this color. + */ + rgb(): RGBColor; + /** + * Returns a copy of this color. + * + * @param values If values is specified, any enumerable own properties of values are assigned to the new returned color. + */ + copy( + values?: { + l?: number | undefined; + a?: number | undefined; + b?: number | undefined; + opacity?: number | undefined; + }, + ): this; +} + +/** + * A Lab (CIELAB) color factory object, which may also be used with instanceof to test if an object + * is a Lab color instance. + */ +export interface LabColorFactory extends Function { + /** + * Constructs a new CIELAB color based on the specified channel values and opacity. + * + * @param l Lightness typically in the range [0, 100]. + * @param a Position between red/magenta and green typically in [-160, +160]. + * @param b Position between yellow and blue typically in [-160, +160]. + * @param opacity Optional opacity value, defaults to 1. + */ + (l: number, a: number, b: number, opacity?: number): LabColor; + /** + * Parses the specified CSS Color Module Level 3 specifier string, returning a Lab color. + * If the specifier was not valid, null is returned. + * + * @param cssColorSpecifier A CSS Color Module Level 3 specifier string. + */ + (cssColorSpecifier: string): LabColor; + /** + * Converts the provided color instance and returns a Lab color. + * The color instance is converted to the RGB color space using color.rgb and then converted to CIELAB. + * (Colors already in the Lab color space skip the conversion to RGB, + * and colors in the HCL color space are converted directly to CIELAB.) + * + * @param color A permissible color space instance. + */ + // tslint:disable-next-line:unified-signatures + (color: ColorSpaceObject | ColorCommonInstance): LabColor; + /** + * Prototype of the factory, which can be used for instanceof testing + */ + readonly prototype: LabColor; +} + +/** + * A gray color factory for Lab (CIELAB) colors. + */ +export type GrayColorFactory = + /** + * Constructs a new CIELAB color with the specified l value and a = b = 0. + * + * @param l Lightness typically in the range [0, 100]. + * @param opacity Optional opacity value, defaults to 1. + */ + (l: number, opacity?: number) => LabColor; + +/** + * An HCL (CIELCH) color object. + */ +export interface HCLColor extends Color { + /** + * Hue channel value typically in [0, 360). + */ + h: number; + /** + * Chroma channel value typically in [0, 230]. + */ + c: number; + /** + * Luminance channel value typically in the range [0, 100]. + */ + l: number; + /** + * Opacity value + */ + opacity: number; + /** + * Returns a brighter copy of this color. If k is specified, it controls how much brighter the returned color should be. + * If k is not specified, it defaults to 1. + * + * @param k A color space dependent number to determine, how much brighter the returned color should be. + */ + brighter(k?: number): this; + /** + * Returns a darker copy of this color. If k is specified, it controls how much darker the returned color should be. + * If k is not specified, it defaults to 1. + * + * @param k A color space dependent number to determine, how much darker the returned color should be. + */ + darker(k?: number): this; + /** + * Returns the RGB color equivalent of this color. + */ + rgb(): RGBColor; + /** + * Returns a copy of this color. + * + * @param values If values is specified, any enumerable own properties of values are assigned to the new returned color. + */ + copy( + values?: { + h?: number | undefined; + c?: number | undefined; + l?: number | undefined; + opacity?: number | undefined; + }, + ): this; +} + +/** + * An HCL (CIELCH) color factory object, which may also be used with instanceof to test if an object + * is an HCL color instance. + */ +export interface HCLColorFactory extends Function { + /** + * Constructs a new HCL color based on the specified channel values and opacity. + * + * @param h Hue channel value typically in [0, 360). + * @param c Chroma channel value typically in [0, 230]. + * @param l Luminance channel value typically in the range [0, 100]. + * @param opacity Optional opacity value, defaults to 1. + */ + (h: number, c: number, l: number, opacity?: number): HCLColor; + /** + * Parses the specified CSS Color Module Level 3 specifier string, returning an HCL color. + * If the specifier was not valid, null is returned. + * + * @param cssColorSpecifier A CSS Color Module Level 3 specifier string. + */ + (cssColorSpecifier: string): HCLColor; + /** + * Converts the provided color instance and returns an HCL color. + * The color instance is converted to the RGB color space using color.rgb and then converted to HCL. + * (Colors already in the HCL color space skip the conversion to RGB, + * and colors in the Lab color space are converted directly to HCL.) + * + * @param color A permissible color space instance. + */ + // tslint:disable-next-line:unified-signatures + (color: ColorSpaceObject | ColorCommonInstance): HCLColor; + /** + * Prototype of the factory, which can be used for instanceof testing + */ + readonly prototype: HCLColor; +} + +/** + * An LCH (CIELCH) color factory function to create an HCL color object. + */ +export interface LCHColorFactory { + /** + * Constructs a new HCL color based on the specified channel values and opacity. + * + * @param l Luminance channel value typically in the range [0, 100]. + * @param c Chroma channel value typically in [0, 230]. + * @param h Hue channel value typically in [0, 360). + * @param opacity Optional opacity value, defaults to 1. + */ + (l: number, c: number, h: number, opacity?: number): HCLColor; + /** + * Parses the specified CSS Color Module Level 3 specifier string, returning an HCL color. + * If the specifier was not valid, null is returned. + * + * @param cssColorSpecifier A CSS color Module Level 3 specifier string. + */ + (cssColorSpecifier: string): HCLColor; + /** + * Converts the provided color instance and returns an HCL color. + * The color instance is converted to the RGB color space using color.rgb and then converted to HCL. + * (Colors already in the HCL color space skip the conversion to RGB, + * and colors in the Lab color space are converted directly to HCL.) + * + * @param color A permissible color space instance. + */ + // tslint:disable-next-line:unified-signatures + (color: ColorSpaceObject | ColorCommonInstance): HCLColor; +} + +/** + * Dave Green’s Cubehelix color object. + */ +export interface CubehelixColor extends Color { + /** + * Hue channel value. + */ + h: number; + /** + * Saturation channel value. + */ + s: number; + /** + * Lightness channel value. + */ + l: number; + /** + * Opacity value. + */ + opacity: number; + /** + * Returns a brighter copy of this color. If k is specified, it controls how much brighter the returned color should be. + * If k is not specified, it defaults to 1. + * + * @param k A color space dependent number to determine, how much brighter the returned color should be. + */ + brighter(k?: number): this; + /** + * Returns a darker copy of this color. If k is specified, it controls how much darker the returned color should be. + * If k is not specified, it defaults to 1. + * + * @param k A color space dependent number to determine, how much darker the returned color should be. + */ + darker(k?: number): this; + /** + * Returns the RGB color equivalent of this color. + */ + rgb(): RGBColor; + /** + * Returns a copy of this color. + * + * @param values If values is specified, any enumerable own properties of values are assigned to the new returned color. + */ + copy( + values?: { + h?: number | undefined; + s?: number | undefined; + l?: number | undefined; + opacity?: number | undefined; + }, + ): this; +} + +/** + * A color factory object for Dave Green's Cubehelix colors, which may also be used with instanceof to test if an object + * is a Cubehelix color instance. + */ +export interface CubehelixColorFactory extends Function { + /** + * Constructs a new Cubehelix color based on the specified channel values and opacity. + * + * @param h Hue channel value. + * @param s Saturation channel value. + * @param l Lightness channel value. + * @param opacity Optional opacity value, defaults to 1. + */ + (h: number, s: number, l: number, opacity?: number): CubehelixColor; + /** + * Parses the specified CSS Color Module Level 3 specifier string, returning an Cubehelix color. + * If the specifier was not valid, null is returned. + * + * @param cssColorSpecifier A CSS Color Module Level 3 specifier string. + */ + (cssColorSpecifier: string): CubehelixColor; + /** + * Converts the provided color instance and returns a Cubehelix color. + * The color instance is specified, it is converted to the RGB color space using color.rgb and then converted to Cubehelix. + * (Colors already in the Cubehelix color space skip the conversion to RGB.) + * + * @param color A permissible color space instance. + */ + // tslint:disable-next-line:unified-signatures + (color: ColorSpaceObject | ColorCommonInstance): CubehelixColor; + /** + * Prototype of the factory, which can be used for instanceof testing + */ + readonly prototype: CubehelixColor; +} + +// -------------------------------------------------------------------------- +// Color object factories +// -------------------------------------------------------------------------- + +/** + * A Color factory object, which may also be used with instanceof to test if an object is a color instance. + */ +export const color: ColorFactory; + +/** + * An RGB color factory object, which may also be used with instanceof to test if an object + * is an RGB color instance. + */ +export const rgb: RGBColorFactory; + +/** + * An HSL color factory object, which may also be used with instanceof to test if an object + * is an HSL color instance. + */ +export const hsl: HSLColorFactory; + +/** + * A Lab (CIELAB) color factory object, which may also be used with instanceof to test if an object + * is a Lab color instance. + */ +export const lab: LabColorFactory; + +/** + * A gray color factory for Lab (CIELAB) colors. + */ +export const gray: GrayColorFactory; + +/** + * An HCL (CIELCH) color factory object, which may also be used with instanceof to test if an object + * is an HCL color instance. + */ +export const hcl: HCLColorFactory; + +/** + * An LCH (CIELCH) color factory function to create an HCL color object. + */ +export const lch: LCHColorFactory; + +/** + * A color factory object for Dave Green's Cubehelix colors, which may also be used with instanceof to test if an object + * is a Cubehelix color instance. + */ +export const cubehelix: CubehelixColorFactory; diff --git a/tools/ui/node_modules/@types/d3-color/package.json b/tools/ui/node_modules/@types/d3-color/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6a59cadbaad79bbc68c8a61f33c32c42f7741d0a --- /dev/null +++ b/tools/ui/node_modules/@types/d3-color/package.json @@ -0,0 +1,55 @@ +{ + "name": "@types/d3-color", + "version": "3.1.3", + "description": "TypeScript definitions for d3-color", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-color", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "Hugues Stefanski", + "githubUsername": "ledragon", + "url": "https://github.com/ledragon" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + }, + { + "name": "Fil", + "githubUsername": "Fil", + "url": "https://github.com/Fil" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-color" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "89cf9357324cddaa31cfb539b1c33d118648ed55319f2a0d26f24b004975a947", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-contour/LICENSE b/tools/ui/node_modules/@types/d3-contour/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-contour/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-contour/README.md b/tools/ui/node_modules/@types/d3-contour/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a250644a291bdd62cf50eef4a52bce6f95491368 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-contour/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-contour` + +# Summary +This package contains type definitions for d3-contour (https://d3js.org/d3-contour/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-contour. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:36 GMT + * Dependencies: [@types/d3-array](https://npmjs.com/package/@types/d3-array), [@types/geojson](https://npmjs.com/package/@types/geojson) + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Hugues Stefanski](https://github.com/Ledragon), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-contour/index.d.ts b/tools/ui/node_modules/@types/d3-contour/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..57fe316772acb90f3bb0c241e6382366daca416d --- /dev/null +++ b/tools/ui/node_modules/@types/d3-contour/index.d.ts @@ -0,0 +1,222 @@ +// Last module patch version validated against: 3.0.1 + +import { ThresholdCountGenerator, ThresholdNumberArrayGenerator } from "d3-array"; +import { MultiPolygon } from "geojson"; + +/** + * An extended GeoJSON MultiPolygon representing a contour. + */ +export interface ContourMultiPolygon extends MultiPolygon { + /** + * Threshold value of the contour. + */ + value: number; +} + +/** + * A contour generator which computes contour polygons by applying marching squares to a rectangular array of numeric values. + * + * For each threshold value, the contour generator constructs a GeoJSON MultiPolygon geometry object representing the area + * where the input values are greater than or equal to the threshold value. + * The geometry is in planar coordinates, where ⟨i + 0.5, j + 0.5⟩ corresponds to element i + jn in the input values array. + */ +export interface Contours { + /** + * Computes the contours for the given array of values, returning an array of GeoJSON MultiPolygon geometry objects. + * Each geometry object represents the area where the input values are greater than or equal to the corresponding threshold value; + * the threshold value for each geometry object is exposed as geometry.value. + * + * The returned geometry objects are typically passed to d3.geoPath to display, + * using null or d3.geoIdentity as the associated projection + * + * @param values Array of input values. The input values must be an array of length n×m where [n, m] is the contour generator’s size; + * furthermore, each values[i + jn] must represent the value at the position ⟨i, j⟩. + */ + (values: number[]): ContourMultiPolygon[]; + + /** + * Computes a single contour, returning a GeoJSON MultiPolygon geometry object. + * This geometry object represents the area where the input values are greater than or equal to the given threshold value; + * the threshold value for the geometry object is exposed as geometry.value. + * + * @param values Array of input values. The input values must be an array of length n×m where [n, m] is the contour generator’s size; + * furthermore, each values[i + jn] must represent the value at the position ⟨i, j⟩. + * @param threshold Threshold value. + */ + contour(values: number[], threshold: number): ContourMultiPolygon; + + /** + * Return the expected size of the input values grid, which defaults to [1,1]. + */ + size(): [number, number]; + /** + * Sets the expected size of the input values grid to the contour generator and returns the contour generator. + * + * @param size Size of the input values grid specified as an array [n, m] + * where n is the number of columns in the grid and m is the number of rows; n and m must be positive integers. + */ + size(size: [number, number]): this; + + /** + * Returns the current smoothing flag, which defaults to true. + */ + smooth(): boolean; + /** + * Sets whether or not the generated contour polygons are smoothed using linear interpolation and returns the contour generator. + * + * @param smooth Flag to enable linear interpolation. The default is "true". + */ + smooth(smooth: boolean): this; + + /** + * Returns the current threshold generator, which by default implements Sturges’ formula. + */ + thresholds(): ThresholdCountGenerator | ThresholdNumberArrayGenerator; + /** + * Sets the threshold generator to the specified function or array and returns this contour generator. + * Thresholds are defined as an array of values [x0, x1, …]. + * The first generated contour corresponds to the area where the input values are greater than or equal to x0; + * the second contour corresponds to the area where the input values are greater than or equal to x1, and so on. + * Thus, there is exactly one generated MultiPolygon geometry object for each specified threshold value; the threshold value is exposed as geometry.value. + * If a count is specified instead of an array of thresholds, then the input values’ extent will be uniformly divided into approximately count bins; see d3.ticks. + */ + thresholds( + thresholds: number | number[] | ThresholdCountGenerator | ThresholdNumberArrayGenerator, + ): this; +} + +/** + * Construct a new contour generator with the default settings. + */ +export function contours(): Contours; + +/** + * A contour generator for density estimates. + * + * The generic refers to the data type of an element in the data array + * used with the density contour generator. If omitted, the default setting assumes that, + * the elements of the data array used with the density contour generator are two-element arrays. + * The first element corresponds to the x-dimension, the second to the y-dimension. + */ +export interface ContourDensity { + /** + * Estimates the density contours for the given array of data, returning an array of GeoJSON MultiPolygon geometry objects. + * Each geometry object represents the area where the estimated number of points per square pixel is greater than or equal to + * the corresponding threshold value; the threshold value for each geometry object is exposed as geometry.value. + * The returned geometry objects are typically passed to d3.geoPath to display, using null or d3.geoIdentity as the associated projection. + * See also d3.contours. + * + * The x- and y-coordinate for each data point are computed using density.x and density.y. + * The generated contours are only accurate within the estimator’s defined size. + * + * @param data Array of input data. + */ + (data: Datum[]): ContourMultiPolygon[]; + + /** + * Returns the current x-coordinate accessor. + * The default x-coordinate accessor is a functions which accepts as input a two-element array of numbers + * and returns the element at index 0. + */ + x(): (d: Datum) => number; + /** + * Sets the x-coordinate accessor and returns the density contour estimator. + * + * @param x An x-coordinate accessor function, which accepts as input an element of the input data array and returns the + * x-coordinate. + */ + x(x: (d: Datum) => number): this; + + /** + * Returns the current y-coordinate accessor. + * The default y-coordinate accessor is a functions which accepts as input a two-element array of numbers + * and returns the element at index 1. + */ + y(): (d: Datum) => number; + /** + * Sets the y-coordinate accessor and returns the density contour estimator. + * + * @param y An y-coordinate accessor function, which accepts as input an element of the input data array and returns the + * y-coordinate. + */ + y(y: (d: Datum) => number): this; + + /** + * Returns the current point weight accessor. + */ + weight(): (d: Datum) => number; + + /** + * Sets the point weight accessor and returns the density contour estimator. + * + * @param weight A point weight accessor function. + */ + weight(weight: (d: Datum) => number): this; + + /** + * Returns the current size, which defaults to [960, 500]. + */ + size(): [number, number]; + /** + * Sets the size of the density estimator to the specified bounds and returns the density contour estimator. + * + * @param size The size is specified as an array [width, height], where width is the maximum x-value and height is the maximum y-value. + */ + size(size: [number, number]): this; + + /** + * Returns the current cell size, which defaults to 4. + */ + cellSize(): number; + /** + * Sets the size of individual cells in the underlying bin grid to the specified positive integer and returns the density contour estimator. + * + * The cell size is rounded down to the nearest power of two. Smaller cells produce more detailed contour polygons, but are more expensive to compute. + * + * @param cellSize Cell size, a positive integer. + */ + cellSize(cellSize: number): this; + + /** + * Returns the current threshold generator, which by default generates about twenty nicely-rounded density thresholds. + */ + thresholds(): ThresholdCountGenerator | ThresholdNumberArrayGenerator; + /** + * Sets the threshold generator to the specified function or array and returns this contour generator. + * Thresholds are defined as an array of values [x0, x1, …]. + * The first generated density contour corresponds to the area where the estimated density is greater than or equal to x0; + * the second contour corresponds to the area where the estimated density is greater than or equal to x1, and so on. + * Thus, there is exactly one generated MultiPolygon geometry object for each specified threshold value; the threshold value is exposed as geometry.value. + * The first value x0 should typically be greater than zero. + * If a count is specified instead of an array of thresholds, then approximately count uniformly-spaced nicely-rounded thresholds will be generated; see d3.ticks. + */ + thresholds( + thresholds: number | number[] | ThresholdCountGenerator | ThresholdNumberArrayGenerator, + ): this; + + /** + * Returns the current bandwidth, which defaults to 20.4939…. + */ + bandwidth(): number; + /** + * Sets the bandwidth (the standard deviation) of the Gaussian kernel and returns the density contour estimator. + * + * @param bandwidth Bandwidth (the standard deviation) of the Gaussian kernel. + * The specified bandwidth is currently rounded to the nearest supported value by this implementation, and must be nonnegative. + */ + bandwidth(bandwidth: number): this; +} + +/** + * Construct a new contour generator for density estimates. + * + * The generic refers to the data type of an element in the data array + * used with the density contour generator. If omitted, the default setting assumes that, + * the elements of the data array used with the density contour generator are two-element arrays. + * The first element corresponds to the x-dimension, the second to the y-dimension. + * + * Important: ensure that the x- and y-accessor functions are configured to + * match the data type used for the generic Datum. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function contourDensity(): ContourDensity; diff --git a/tools/ui/node_modules/@types/d3-contour/package.json b/tools/ui/node_modules/@types/d3-contour/package.json new file mode 100644 index 0000000000000000000000000000000000000000..04c3d5513820907c1c9ae18ff18e832d9a87ba73 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-contour/package.json @@ -0,0 +1,38 @@ +{ + "name": "@types/d3-contour", + "version": "3.0.6", + "description": "TypeScript definitions for d3-contour", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-contour", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Hugues Stefanski", + "githubUsername": "Ledragon", + "url": "https://github.com/Ledragon" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-contour" + }, + "scripts": {}, + "dependencies": { + "@types/d3-array": "*", + "@types/geojson": "*" + }, + "typesPublisherContentHash": "a2a836bf53d1aa8ce0ab664fbae003884449208333886bc8a93937935bc3df4e", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-delaunay/LICENSE b/tools/ui/node_modules/@types/d3-delaunay/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-delaunay/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-delaunay/README.md b/tools/ui/node_modules/@types/d3-delaunay/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a7a78e65bc8566b79f8c27cb4ed1db556818b85d --- /dev/null +++ b/tools/ui/node_modules/@types/d3-delaunay/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-delaunay` + +# Summary +This package contains type definitions for d3-delaunay (https://github.com/d3/d3-delaunay). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-delaunay. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:36 GMT + * Dependencies: none + +# Credits +These definitions were written by [Bradley Odell](https://github.com/BTOdell), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-delaunay/index.d.ts b/tools/ui/node_modules/@types/d3-delaunay/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f09dbfa12cffb3cbe45ab7801775609575e7727 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-delaunay/index.d.ts @@ -0,0 +1,316 @@ +/** + * Delaunay triangulation + */ +export class Delaunay

{ + /** + * Returns the Delaunay triangulation for the given flat array [x0, y0, x1, y1, …] of points. + */ + constructor(points: ArrayLike); + + /** + * Returns the Delaunay triangulation for the given array or iterable of points where each point is an array in the form: [x, y]. + */ + static from(points: ArrayLike | Iterable): Delaunay; + /** + * Returns the Delaunay triangulation for the given array or iterable of points. + * Otherwise, the getX and getY functions are invoked for each point in order, and must return the respective x- and y-coordinate for each point. + * If that is specified, the functions getX and getY are invoked with that as this. + * (See Array.from for reference.) + */ + static from

( + points: ArrayLike

| Iterable

, + getX: Delaunay.GetCoordinate | Iterable

>, + getY: Delaunay.GetCoordinate | Iterable

>, + that?: any, + ): Delaunay

; + + /** + * The coordinates of the points as an array [x0, y0, x1, y1, ...]. + * Typically, this is a Float64Array, however you can use any array-like type in the constructor. + */ + points: ArrayLike; + + /** + * The halfedge indices as an Int32Array [j0, j1, ...]. + * For each index 0 <= i < halfedges.length, there is a halfedge from triangle vertex j = halfedges[i] to triangle vertex i. + */ + halfedges: Int32Array; + + /** + * An Int32Array of point indexes that form the convex hull in counterclockwise order. + * If the points are collinear, returns them ordered. + */ + hull: Uint32Array; + + /** + * The triangle vertex indices as an Uint32Array [i0, j0, k0, i1, j1, k1, ...]. + * Each contiguous triplet of indices i, j, k forms a counterclockwise triangle. + * The coordinates of the triangle's points can be found by going through 'points'. + */ + triangles: Uint32Array; + + /** + * The incoming halfedge indexes as a Int32Array [e0, e1, e2, ...]. + * For each point i, inedges[i] is the halfedge index e of an incoming halfedge. + * For coincident points, the halfedge index is -1; for points on the convex hull, the incoming halfedge is on the convex hull; for other points, the choice of incoming halfedge is arbitrary. + */ + inedges: Int32Array; + + /** + * Returns the index of the input point that is closest to the specified point ⟨x, y⟩. + * The search is started at the specified point i. If i is not specified, it defaults to zero. + */ + find(x: number, y: number, i?: number): number; + + /** + * Returns an iterable over the indexes of the neighboring points to the specified point i. + * The iterable is empty if i is a coincident point. + */ + neighbors(i: number): IterableIterator; + + /** + * Renders the edges of the Delaunay triangulation to an SVG path string. + */ + render(): string; + /** + * Renders the edges of the Delaunay triangulation to the specified context. + * The specified context must implement the context.moveTo and context.lineTo methods from the CanvasPathMethods API. + */ + render(context: Delaunay.MoveContext & Delaunay.LineContext): void; + + /** + * Renders the convex hull of the Delaunay triangulation to an SVG path string. + */ + renderHull(): string; + /** + * Renders the convex hull of the Delaunay triangulation to the specified context. + * The specified context must implement the context.moveTo and context.lineTo methods from the CanvasPathMethods API. + */ + renderHull(context: Delaunay.MoveContext & Delaunay.LineContext): void; + + /** + * Renders triangle i of the Delaunay triangulation to an SVG path string. + */ + renderTriangle(i: number): string; + /** + * Renders triangle i of the Delaunay triangulation to the specified context. + * The specified context must implement the context.moveTo, context.lineTo and context.closePath methods from the CanvasPathMethods API. + */ + renderTriangle(i: number, context: Delaunay.MoveContext & Delaunay.LineContext & Delaunay.ClosableContext): void; + + /** + * Renders the input points of the Delaunay triangulation to an SVG path string as circles with radius 2. + */ + renderPoints(): string; + /** + * Renders the input points of the Delaunay triangulation to an SVG path string as circles with the specified radius. + */ + renderPoints(context: undefined, radius: number): string; + /** + * Renders the input points of the Delaunay triangulation to the specified context as circles with the specified radius. + * If radius is not specified, it defaults to 2. + * The specified context must implement the context.moveTo and context.arc methods from the CanvasPathMethods API. + */ + renderPoints(context: Delaunay.MoveContext & Delaunay.ArcContext, radius?: number): void; + + /** + * Returns the closed polygon [[x0, y0], [x1, y1], ..., [x0, y0]] representing the convex hull. + */ + hullPolygon(): Delaunay.Polygon; + + /** + * Returns the closed polygon [[x0, y0], [x1, y1], [x2, y2], [x0, y0]] representing the triangle i. + */ + trianglePolygon(i: number): Delaunay.Triangle; + /** + * Returns an iterable over the polygons for each triangle, in order. + */ + trianglePolygons(): IterableIterator; + + /** + * Updates the triangulation after the points have been modified in-place. + */ + update(): this; + + /** + * Returns the Voronoi diagram for the associated points. + * When rendering, the diagram will be clipped to the specified bounds = [xmin, ymin, xmax, ymax]. + * If bounds is not specified, it defaults to [0, 0, 960, 500]. + * See To Infinity and Back Again for an interactive explanation of Voronoi cell clipping. + */ + voronoi(bounds?: Delaunay.Bounds): Voronoi

; +} + +export namespace Delaunay { + /** + * A point represented as an array tuple [x, y]. + */ + type Point = [number, number]; + + /** + * A closed polygon [[x0, y0], [x1, y1], [x2, y2], [x0, y0]] representing a triangle. + */ + type Triangle = Point[]; + + /** + * A closed polygon [[x0, y0], [x1, y1], ..., [x0, y0]]. + */ + type Polygon = Point[]; + + /** + * A rectangular area [x, y, width, height]. + */ + type Bounds = [number, number, number, number]; + + /** + * A function to extract a x- or y-coordinate from the specified point. + */ + type GetCoordinate = (point: P, i: number, points: PS) => number; + + /** + * An interface for the rect() method of the CanvasPathMethods API. + */ + interface RectContext { + /** + * rect() method of the CanvasPathMethods API. + */ + rect(x: number, y: number, width: number, height: number): void; + } + + /** + * An interface for the moveTo() method of the CanvasPathMethods API. + */ + interface MoveContext { + /** + * moveTo() method of the CanvasPathMethods API. + */ + moveTo(x: number, y: number): void; + } + + /** + * An interface for the lineTo() method of the CanvasPathMethods API. + */ + interface LineContext { + /** + * lineTo() method of the CanvasPathMethods API. + */ + lineTo(x: number, y: number): void; + } + + /** + * An interface for the arc() method of the CanvasPathMethods API. + */ + interface ArcContext { + /** + * arc() method of the CanvasPathMethods API. + */ + arc( + x: number, + y: number, + radius: number, + startAngle: number, + endAngle: number, + counterclockwise?: boolean, + ): void; + } + + /** + * An interface for the closePath() method of the CanvasPathMethods API. + */ + interface ClosableContext { + /** + * closePath() method of the CanvasPathMethods API. + */ + closePath(): void; + } +} + +/** + * Voronoi regions + */ +export class Voronoi

{ + /** + * The Voronoi diagram’s associated Delaunay triangulation. + */ + delaunay: Delaunay

; + + /** + * The circumcenters of the Delaunay triangles [cx0, cy0, cx1, cy1, ...]. + * Each contiguous pair of coordinates cx, cy is the circumcenter for the corresponding triangle. + * These circumcenters form the coordinates of the Voronoi cell polygons. + */ + circumcenters: Float64Array; + + /** + * An array [vx0, vy0, wx0, wy0, ...] where each non-zero quadruple describes an open (infinite) cell + * on the outer hull, giving the directions of two open half-lines. + */ + vectors: Float64Array; + + /** + * The bounds of the viewport [xmin, ymin, xmax, ymax] for rendering the Voronoi diagram. + * These values only affect the rendering methods (voronoi.render, voronoi.renderBounds, cell.render). + */ + xmin: number; + ymin: number; + xmax: number; + ymax: number; + + /** + * Returns true if the cell with the specified index i contains the specified point ⟨x, y⟩. + * (This method is not affected by the associated Voronoi diagram’s viewport bounds.) + */ + contains(i: number, x: number, y: number): boolean; + + /** + * Returns an iterable over the indexes of the cells that share a common edge with the specified cell i. + * Voronoi neighbors are always neighbors on the Delaunay graph, but the converse is false when the common edge has been clipped out by the Voronoi diagram’s viewport. + */ + neighbors(i: number): Iterable; + + /** + * Renders the mesh of Voronoi cells to an SVG path string. + */ + render(): string; + /** + * Renders the mesh of Voronoi cells to the specified context. + * The specified context must implement the context.moveTo and context.lineTo methods from the CanvasPathMethods API. + */ + render(context: Delaunay.MoveContext & Delaunay.LineContext): void; + + /** + * Renders the viewport extent to an SVG path string. + */ + renderBounds(): string; + /** + * Renders the viewport extent to the specified context. + * The specified context must implement the context.rect method from the CanvasPathMethods API. + * Equivalent to context.rect(voronoi.xmin, voronoi.ymin, voronoi.xmax - voronoi.xmin, voronoi.ymax - voronoi.ymin). + */ + renderBounds(context: Delaunay.RectContext): void; + + /** + * Renders the cell with the specified index i to an SVG path string. + */ + renderCell(i: number): string; + /** + * Renders the cell with the specified index i to the specified context. + * The specified context must implement the context.moveTo, context.lineTo, and context.closePath methods from the CanvasPathMethods API. + */ + renderCell(i: number, context: Delaunay.MoveContext & Delaunay.LineContext & Delaunay.ClosableContext): void; + + /** + * Returns an iterable over the non-empty polygons for each cell, with the cell index as property. + */ + cellPolygons(): IterableIterator; + + /** + * Returns the convex, closed polygon [[x0, y0], [x1, y1], ..., [x0, y0]] representing the cell for the specified point i. + */ + cellPolygon(i: number): Delaunay.Polygon; + + /** + * Updates the Voronoi diagram and underlying triangulation after the points have been modified in-place — useful for Lloyd’s relaxation. + */ + update(): this; +} diff --git a/tools/ui/node_modules/@types/d3-delaunay/package.json b/tools/ui/node_modules/@types/d3-delaunay/package.json new file mode 100644 index 0000000000000000000000000000000000000000..db2aa42bc395ad807f42f37280d0d9b93950c8cc --- /dev/null +++ b/tools/ui/node_modules/@types/d3-delaunay/package.json @@ -0,0 +1,30 @@ +{ + "name": "@types/d3-delaunay", + "version": "6.0.4", + "description": "TypeScript definitions for d3-delaunay", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-delaunay", + "license": "MIT", + "contributors": [ + { + "name": "Bradley Odell", + "githubUsername": "BTOdell", + "url": "https://github.com/BTOdell" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-delaunay" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "3e9eae0049dbbb71f5268e23d09f4145f04bb5283a48d839914edcdd05b42211", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-dispatch/LICENSE b/tools/ui/node_modules/@types/d3-dispatch/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-dispatch/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-dispatch/README.md b/tools/ui/node_modules/@types/d3-dispatch/README.md new file mode 100644 index 0000000000000000000000000000000000000000..98d6e2ac4b1e808bc3733dcd563a8c969d36f5e1 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-dispatch/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-dispatch` + +# Summary +This package contains type definitions for d3-dispatch (https://github.com/d3/d3-dispatch/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-dispatch. + +### Additional Details + * Last updated: Wed, 30 Jul 2025 13:15:13 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [denisname](https://github.com/denisname), [Nathan Bierema](https://github.com/Methuselah96), and [Kyle Hensel](https://github.com/k-yle). diff --git a/tools/ui/node_modules/@types/d3-dispatch/index.d.ts b/tools/ui/node_modules/@types/d3-dispatch/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7ee74ca82e5ca9a2e3f86c82549b7653e2fa21cf --- /dev/null +++ b/tools/ui/node_modules/@types/d3-dispatch/index.d.ts @@ -0,0 +1,96 @@ +// Last module patch version validated against: 3.0.1 + +/** helper function, maps over a union type */ +type MapUnion = K extends any ? T[K] : never; + +export namespace Dispatch { + /** given a string like `a.1 b c.2`, it returns a union like `'a' | 'b' | 'c'` */ + type ExtractEventNames = Input extends "" ? never + : Input extends `${infer A} ${infer B}` // multiple events + ? ExtractEventNames | ExtractEventNames + : Input extends `${infer A}.${string}` // single event with a name + ? A + : Input; // single event with no name + + /** + * defines all the events that can be emitted. + * Each property is the arguments for that event. + */ + interface GenericEventMap { + [eventName: string]: any[]; + } +} + +export interface Dispatch { + /** + * Like `function.apply`, invokes each registered callback for the specified type, + * passing the callback the specified arguments, with `that` as the `this` context. + * + * @param type A specified event type. + * @param that The `this` context for the callback. + * @param args Additional arguments to be passed to the callback. + * @throws "unknown type" on unknown event type. + */ + apply(type: U, that?: This, args?: EventMap[U]): void; + + /** + * Like `function.call`, invokes each registered callback for the specified type, + * passing the callback the specified arguments, with `that` as the `this` context. + * See dispatch.apply for more information. + * + * @param type A specified event type. + * @param that The `this` context for the callback. + * @param args Additional arguments to be passed to the callback. + * @throws "unknown type" on unknown event type. + */ + call(type: U, that?: This, ...args: EventMap[U]): void; + + /** + * Returns a copy of this dispatch object. + * Changes to this dispatch do not affect the returned copy and vice versa. + */ + copy(): Dispatch; + + /** + * Returns the callback for the specified typenames, if any. + * If multiple typenames are specified, the first matching callback is returned. + */ + on( + typenames: Source, + ): Dispatch.ExtractEventNames extends keyof EventMap + ? ((this: This, ...args: MapUnion, EventMap>) => void) | undefined + : never; + + /** + * Adds or removes the callback for the specified typenames. + * If a callback function is specified, it is registered for the specified (fully-qualified) typenames. + * If a callback was already registered for the given typenames, the existing callback is removed before the new callback is added. + * The specified typenames is a string, such as start or end.foo. + * The type may be optionally followed by a period (.) and a name; the optional name allows multiple callbacks to be registered to receive events of the same type, such as start.foo and start.bar. + * To specify multiple typenames, separate typenames with spaces, such as start end or start.foo start.bar. + * To remove all callbacks for a given name foo, say dispatch.on(".foo", null). + */ + on( + typenames: Source, + callback: Dispatch.ExtractEventNames extends keyof EventMap + ? ((this: This, ...args: MapUnion, EventMap>) => void) | null + : never, + ): this; +} + +/** + * Creates a new dispatch for the specified event types. Each type is a string, such as "start" or "end". + * + * @param types The event types. + * @throws "illegal type" on empty string or duplicated event types. + */ +/* eslint-disable @definitelytyped/no-unnecessary-generics */ +export function dispatch< + This extends object, + EventMap extends Record, + const EventNames extends keyof any = keyof EventMap, +>( + ...types: EventNames[] +): Dispatch; + +export {}; diff --git a/tools/ui/node_modules/@types/d3-dispatch/package.json b/tools/ui/node_modules/@types/d3-dispatch/package.json new file mode 100644 index 0000000000000000000000000000000000000000..677a1d8d9e50b8f3299fd4712cfe7aa668938eb5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-dispatch/package.json @@ -0,0 +1,51 @@ +{ + "name": "@types/d3-dispatch", + "version": "3.0.7", + "description": "TypeScript definitions for d3-dispatch", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-dispatch", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + }, + { + "name": "Kyle Hensel", + "githubUsername": "k-yle", + "url": "https://github.com/k-yle" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-dispatch" + }, + "scripts": {}, + "dependencies": {}, + "peerDependencies": {}, + "typesPublisherContentHash": "be4052c6f2bf18bd5e9b8e514a0c6e7d09cd01d684460cef8a794c71e73e3627", + "typeScriptVersion": "5.1" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-drag/LICENSE b/tools/ui/node_modules/@types/d3-drag/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-drag/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-drag/README.md b/tools/ui/node_modules/@types/d3-drag/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7a66bf9653cb2d0cc69a04a85db91f17f9cdeef1 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-drag/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-drag` + +# Summary +This package contains type definitions for d3-drag (https://github.com/d3/d3-drag/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-drag. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:36 GMT + * Dependencies: [@types/d3-selection](https://npmjs.com/package/@types/d3-selection) + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-drag/index.d.ts b/tools/ui/node_modules/@types/d3-drag/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8200e5e0d314a76459f5b43b055bf995246f1081 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-drag/index.d.ts @@ -0,0 +1,395 @@ +// Last module patch version validated against: 3.0.0 + +import { Selection, ValueFn } from "d3-selection"; + +// -------------------------------------------------------------------------- +// Shared Type Definitions and Interfaces +// -------------------------------------------------------------------------- + +/** + * DraggedElementBaseType serves as an alias for the 'minimal' data type which can be selected + * without 'd3-drag' (and related code in 'd3-selection') trying to use properties internally which would otherwise not + * be supported. + */ +export type DraggedElementBaseType = Element; + +/** + * Container element type usable for mouse/touch functions + */ +export type DragContainerElement = HTMLElement | SVGSVGElement | SVGGElement; // HTMLElement includes HTMLCanvasElement + +/** + * The subject datum should at a minimum expose x and y properties, so that the relative position + * of the subject and the pointer can be preserved during the drag gesture. + */ +export interface SubjectPosition { + /** + * x-coordinate + */ + x: number; + /** + * y-coordinate + */ + y: number; +} + +/** + * A D3 Drag Behavior + * + * The first generic refers to the type of element to be dragged. + * The second generic refers to the type of the datum of the dragged element. + * The third generic refers to the type of the drag behavior subject. + * + * The subject of a drag gesture represents the thing being dragged. + * It is computed when an initiating input event is received, + * such as a mousedown or touchstart, immediately before the drag gesture starts. + * The subject is then exposed as event.subject on subsequent drag events for this gesture. + * + * The default subject is the datum of the element in the originating selection (see drag) + * that received the initiating input event; if this datum is undefined, + * an object representing the coordinates of the pointer is created. + * When dragging circle elements in SVG, the default subject is thus the datum of the circle being dragged. + * With Canvas, the default subject is the canvas element’s datum (regardless of where on the canvas you click). + * In this case, a custom subject accessor would be more appropriate, + * such as one that picks the closest circle to the mouse within a given search radius. + */ +export interface DragBehavior extends Function { + /** + * Applies the drag behavior to the selected elements. + * This function is typically not invoked directly, and is instead invoked via selection.call. + * + * For details see: {@link https://github.com/d3/d3-drag#_drag} + * + * @param selection A D3 selection of elements. + * @param args Optional arguments to be passed in. + */ + (selection: Selection, ...args: any[]): void; + + /** + * Returns the current container accessor function. + */ + container(): ValueFn; + /** + * Sets the container accessor to the specified function and returns the drag behavior. + * + * The container of a drag gesture determines the coordinate system of subsequent drag events, affecting event.x and event.y. + * The element returned by the container accessor is subsequently passed to d3.pointer to determine the local coordinates of the pointer. + * + * The default container accessor returns the parent node of the element in the originating selection (see drag) + * that received the initiating input event. This is often appropriate when dragging SVG or HTML elements, + * since those elements are typically positioned relative to a parent. For dragging graphical elements with a Canvas, + * however, you may want to redefine the container as the initiating element itself, using "this" in the accessor + * function. + * + * @param accessor A container accessor function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element. The function returns the container element. + */ + container(accessor: ValueFn): this; + /** + * Sets the container accessor to the specified object and returns the drag behavior. + * + * The container of a drag gesture determines the coordinate system of subsequent drag events, affecting event.x and event.y. + * The element returned by the container accessor is subsequently passed to d3.pointer to determine the local coordinates of the pointer. + * + * The default container accessor returns the parent node of the element in the originating selection (see drag) + * that received the initiating input event. This is often appropriate when dragging SVG or HTML elements, + * since those elements are typically positioned relative to a parent. For dragging graphical elements with a Canvas, + * however, you may want to redefine the container as the initiating element itself, such as drag.container(canvas). + * + * @param container Container element for the drag gesture. + */ + container(container: DragContainerElement): this; + + /** + * Returns the current filter function. + */ + filter(): (this: GElement, event: any, d: Datum) => boolean; + /** + * Sets the event filter to the specified filter function and returns the drag behavior. + * + * If the filter returns falsey, the initiating event is ignored and no drag gesture is started. + * Thus, the filter determines which input events are ignored. The default filter ignores mousedown events on secondary buttons, + * since those buttons are typically intended for other purposes, such as the context menu. + * + * @param filterFn A filter function which is evaluated for each selected element, + * in order, being passed the current event (event) and datum d, with the this context as the current DOM element. + * The function returns a boolean value. + */ + filter(filterFn: (this: GElement, event: any, d: Datum) => boolean): this; + + /** + * Returns the current touch support detector, which defaults to a function returning true, + * if the "ontouchstart" event is supported on the current element. + */ + touchable(): ValueFn; + /** + * Sets the touch support detector to the specified boolean value and returns the drag behavior. + * + * Touch event listeners are only registered if the detector returns truthy for the corresponding element when the drag behavior is applied. + * The default detector works well for most browsers that are capable of touch input, but not all; Chrome’s mobile device emulator, for example, + * fails detection. + * + * @param touchable A boolean value. true when touch event listeners should be applied to the corresponding element, otherwise false. + */ + touchable(touchable: boolean): this; + /** + * Sets the touch support detector to the specified function and returns the drag behavior. + * + * Touch event listeners are only registered if the detector returns truthy for the corresponding element when the drag behavior is applied. + * The default detector works well for most browsers that are capable of touch input, but not all; Chrome’s mobile device emulator, for example, + * fails detection. + * + * @param touchable A touch support detector function, which returns true when touch event listeners should be applied to the corresponding element. + * The function is evaluated for each selected element to which the drag behavior was applied, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element. The function returns a boolean value. + */ + touchable(touchable: ValueFn): this; + + /** + * Returns the current subject accessor functions. + */ + subject(): (this: GElement, event: any, d: Datum) => Subject; + /** + * Sets the subject accessor to the specified function and returns the drag behavior. + * + * The subject of a drag gesture represents the thing being dragged. + * It is computed when an initiating input event is received, + * such as a mousedown or touchstart, immediately before the drag gesture starts. + * The subject is then exposed as event.subject on subsequent drag events for this gesture. + * + * The default subject is the datum of the element in the originating selection (see drag) + * that received the initiating input event; if this datum is undefined, + * an object representing the coordinates of the pointer is created. + * When dragging circle elements in SVG, the default subject is thus the datum of the circle being dragged. + * With Canvas, the default subject is the canvas element’s datum (regardless of where on the canvas you click). + * In this case, a custom subject accessor would be more appropriate, + * such as one that picks the closest circle to the mouse within a given search radius. + * + * The subject of a drag gesture may not be changed after the gesture starts. + * + * During the evaluation of the subject accessor, event is a beforestart drag event. + * Use event.sourceEvent to access the initiating input event and event.identifier to access the touch identifier. + * The event.x and event.y are relative to the container, and are computed using d3.pointer. + * + * @param accessor An extent accessor function which is evaluated for each selected element, + * in order, being passed the current event (`event`) and datum `d`, with the `this` context as the current DOM element. + * The returned subject should be an object that exposes x and y properties, + * so that the relative position of the subject and the pointer can be preserved during the drag gesture. + * If the subject is null or undefined, no drag gesture is started for this pointer; + * however, other starting touches may yet start drag gestures. + */ + subject(accessor: (this: GElement, event: any, d: Datum) => Subject): this; + + /** + * Return the current click distance threshold, which defaults to zero. + */ + clickDistance(): number; + /** + * Set the maximum distance that the mouse can move between mousedown and mouseup that will trigger + * a subsequent click event. If at any point between mousedown and mouseup the mouse is greater than or equal to + * distance from its position on mousedown, the click event following mouseup will be suppressed. + * + * @param distance The distance threshold between mousedown and mouseup measured in client coordinates (event.clientX and event.clientY). + * The default is zero. + */ + clickDistance(distance: number): this; + + /** + * Return the first currently-assigned listener matching the specified typenames, if any. + * + * @param typenames The typenames is a string containing one or more typename separated by whitespace. + * Each typename is a type, optionally followed by a period (.) and a name, such as "drag.foo"" and "drag.bar"; + * the name allows multiple listeners to be registered for the same type. The type must be one of the following: + * start (after a new pointer becomes active [on mousedown or touchstart]), drag (after an active pointer moves [on mousemove or touchmove], or + * end (after an active pointer becomes inactive [on mouseup, touchend or touchcancel].) + */ + on(typenames: string): ((this: GElement, event: any, d: Datum) => void) | undefined; + /** + * Remove the current event listeners for the specified typenames, if any, return the drag behavior. + * + * @param typenames The typenames is a string containing one or more typename separated by whitespace. + * Each typename is a type, optionally followed by a period (.) and a name, such as "drag.foo"" and "drag.bar"; + * the name allows multiple listeners to be registered for the same type. The type must be one of the following: + * start (after a new pointer becomes active [on mousedown or touchstart]), drag (after an active pointer moves [on mousemove or touchmove], or + * end (after an active pointer becomes inactive [on mouseup, touchend or touchcancel].) + * @param listener Use null to remove the listener. + */ + on(typenames: string, listener: null): this; + /** + * Set the event listener for the specified typenames and return the drag behavior. + * If an event listener was already registered for the same type and name, + * the existing listener is removed before the new listener is added. + * When a specified event is dispatched, each listener will be invoked with the same context and arguments as selection.on listeners. + * + * Changes to registered listeners via drag.on during a drag gesture do not affect the current drag gesture. + * Instead, you must use event.on, which also allows you to register temporary event listeners for the current drag gesture. + * Separate events are dispatched for each active pointer during a drag gesture. + * For example, if simultaneously dragging multiple subjects with multiple fingers, a start event is dispatched for each finger, + * even if both fingers start touching simultaneously. + * + * @param typenames The typenames is a string containing one or more typename separated by whitespace. + * Each typename is a type, optionally followed by a period (.) and a name, such as "drag.foo"" and "drag.bar"; + * the name allows multiple listeners to be registered for the same type. The type must be one of the following: + * start (after a new pointer becomes active [on mousedown or touchstart]), drag (after an active pointer moves [on mousemove or touchmove], or + * end (after an active pointer becomes inactive [on mouseup, touchend or touchcancel].) + * @param listener An event listener function which is evaluated for each selected element, + * in order, being passed the current event (event) and datum d, with the this context as the current DOM element. + */ + on(typenames: string, listener: (this: GElement, event: any, d: Datum) => void): this; +} + +/** + * Creates a new drag behavior. The returned behavior, drag, is both an object and a function, and is + * typically applied to selected elements via selection.call. + * + * Use this signature when using the default subject accessor. + * + * The first generic refers to the type of element to be dragged. + * The second generic refers to the type of the datum of the dragged element. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function drag(): DragBehavior< + GElement, + Datum, + Datum | SubjectPosition +>; +/** + * Creates a new drag behavior. The returned behavior, drag, is both an object and a function, and is + * typically applied to selected elements via selection.call. + * + * Use this signature when using a custom subject accessor. + * + * The first generic refers to the type of element to be dragged. + * The second generic refers to the type of the datum of the dragged element. + * The third generic refers to the type of the drag behavior subject. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function drag(): DragBehavior; + +/** + * D3 Drag event + * + * The first generic refers to the type of element to be dragged. + * The second generic refers to the type of the datum of the dragged element. + * The third generic refers to the type of the drag behavior subject. + */ +export interface D3DragEvent { + /** + * The DragBehavior associated with the event + */ + target: DragBehavior; + /** + * The event type for the DragEvent + */ + type: "start" | "drag" | "end" | string; // Leave failsafe string type for cases like 'drag.foo' + /** + * The drag subject, defined by drag.subject. + */ + subject: Subject; + /** + * The new x-coordinate of the subject, relative to the container + */ + x: number; + /** + * The new y-coordinate of the subject, relative to the container + */ + y: number; + /** + * The change in x-coordinate since the previous drag event. + */ + dx: number; + /** + * The change in y-coordinate since the previous drag event. + */ + dy: number; + /** + * The string “mouse”, or a numeric touch identifier. + */ + identifier: "mouse" | number; + /** + * The number of currently active drag gestures (on start and end, not including this one). + * + * The event.active field is useful for detecting the first start event and the last end event + * in a sequence of concurrent drag gestures: it is zero when the first drag gesture starts, + * and zero when the last drag gesture ends. + */ + active: number; + /** + * The underlying input event, such as mousemove or touchmove. + */ + sourceEvent: any; + /** + * Return the first currently-assigned listener matching the specified typenames, if any. + * + * Equivalent to drag.on, but only applies to the current drag gesture. Before the drag gesture starts, + * a copy of the current drag event listeners is made. This copy is bound to the current drag gesture + * and modified by event.on. This is useful for temporary listeners that only receive events for the current drag gesture. + * + * @param typenames The typenames is a string containing one or more typename separated by whitespace. + * Each typename is a type, optionally followed by a period (.) and a name, such as "drag.foo"" and "drag.bar"; + * the name allows multiple listeners to be registered for the same type. The type must be one of the following: + * start (after a new pointer becomes active [on mousedown or touchstart]), drag (after an active pointer moves [on mousemove or touchmove], or + * end (after an active pointer becomes inactive [on mouseup, touchend or touchcancel].) + */ + on(typenames: string): ((this: GElement, event: any, d: Datum) => void) | undefined; + /** + * Remove the current event listeners for the specified typenames, if any, return the drag behavior. + * + * Equivalent to drag.on, but only applies to the current drag gesture. Before the drag gesture starts, + * a copy of the current drag event listeners is made. This copy is bound to the current drag gesture + * and modified by event.on. This is useful for temporary listeners that only receive events for the current drag gesture. + * + * @param typenames The typenames is a string containing one or more typename separated by whitespace. + * Each typename is a type, optionally followed by a period (.) and a name, such as "drag.foo"" and "drag.bar"; + * the name allows multiple listeners to be registered for the same type. The type must be one of the following: + * start (after a new pointer becomes active [on mousedown or touchstart]), drag (after an active pointer moves [on mousemove or touchmove], or + * end (after an active pointer becomes inactive [on mouseup, touchend or touchcancel].) + * @param listener Use null to remove the listener. + */ + on(typenames: string, listener: null): this; + /** + * Set the event listener for the specified typenames and return the drag behavior. + * If an event listener was already registered for the same type and name, + * the existing listener is removed before the new listener is added. + * When a specified event is dispatched, each listener will be invoked with the same context and arguments as selection.on listeners. + * + * Equivalent to drag.on, but only applies to the current drag gesture. Before the drag gesture starts, + * a copy of the current drag event listeners is made. This copy is bound to the current drag gesture + * and modified by event.on. This is useful for temporary listeners that only receive events for the current drag gesture. + * + * @param typenames The typenames is a string containing one or more typename separated by whitespace. + * Each typename is a type, optionally followed by a period (.) and a name, such as "drag.foo"" and "drag.bar"; + * the name allows multiple listeners to be registered for the same type. The type must be one of the following: + * start (after a new pointer becomes active [on mousedown or touchstart]), drag (after an active pointer moves [on mousemove or touchmove], or + * end (after an active pointer becomes inactive [on mouseup, touchend or touchcancel].) + * @param listener An event listener function which is evaluated for each selected element, + * in order, being passed the current event (event) and datum d, with the this context as the current DOM element. + */ + on(typenames: string, listener: (this: GElement, event: any, d: Datum) => void): this; +} + +/** + * Prevents native drag-and-drop and text selection on the specified window. + * As an alternative to preventing the default action of mousedown events, + * this method prevents undesirable default actions following mousedown. In supported browsers, + * this means capturing dragstart and selectstart events, preventing the associated default actions, + * and immediately stopping their propagation. In browsers that do not support selection events, + * the user-select CSS property is set to none on the document element. + * This method is intended to be called on mousedown, followed by d3.dragEnable on mouseup. + * + * @param window The window for which drag should be disabled. + */ +export function dragDisable(window: Window): void; + +/** + * Allows native drag-and-drop and text selection on the specified window; undoes the effect of d3.dragDisable. + * This method is intended to be called on mouseup, preceded by d3.dragDisable on mousedown. + * If noclick is true, this method also temporarily suppresses click events. + * The suppression of click events expires after a zero-millisecond timeout, + * such that it only suppress the click event that would immediately follow the current mouseup event, if any. + * + * @param window The window for which drag should be (re-)enabled. + * @param noClick An optional flag. If noclick is true, this method also temporarily suppresses click events. + */ +export function dragEnable(window: Window, noClick?: boolean): void; diff --git a/tools/ui/node_modules/@types/d3-drag/package.json b/tools/ui/node_modules/@types/d3-drag/package.json new file mode 100644 index 0000000000000000000000000000000000000000..83aa1e6a5938539138fcb4c6924176f4019e69da --- /dev/null +++ b/tools/ui/node_modules/@types/d3-drag/package.json @@ -0,0 +1,42 @@ +{ + "name": "@types/d3-drag", + "version": "3.0.7", + "description": "TypeScript definitions for d3-drag", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-drag", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-drag" + }, + "scripts": {}, + "dependencies": { + "@types/d3-selection": "*" + }, + "typesPublisherContentHash": "cbd098773821019893d7397be4129e19f5b62205943d423ef95a612ec9c9eac6", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-dsv/LICENSE b/tools/ui/node_modules/@types/d3-dsv/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-dsv/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-dsv/README.md b/tools/ui/node_modules/@types/d3-dsv/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cb57107d4134033c0fd5158d9f4668cd6fb2143e --- /dev/null +++ b/tools/ui/node_modules/@types/d3-dsv/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-dsv` + +# Summary +This package contains type definitions for d3-dsv (https://github.com/d3/d3-dsv/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-dsv. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:36 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [denisname](https://github.com/denisname), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-dsv/index.d.ts b/tools/ui/node_modules/@types/d3-dsv/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4afece9ded9ee2959cf0edb1bab035ca65757fdf --- /dev/null +++ b/tools/ui/node_modules/@types/d3-dsv/index.d.ts @@ -0,0 +1,482 @@ +// Last module patch version validated against: 3.0.1 + +// ------------------------------------------------------------------------------------------ +// Shared Types and Interfaces +// ------------------------------------------------------------------------------------------ + +/** + * An object representing a DSV parsed row with values represented as strings. + */ +export type DSVRowString = { + [key in Columns]: string; +}; + +/** + * An object in raw format before parsing, that is with only string values. + */ +export type DSVRaw = { + [key in keyof T]: string; +}; + +/** + * An object representing a DSV parsed row with values represented as an arbitrary datatype, depending + * on the performed parsed row mapping. + * + * @deprecated Use `object` instead. + */ +export interface DSVRowAny { + [key: string]: any; +} + +/** + * An array object representing all deserialized rows. The array is enhanced with a property listing + * the names of the parsed columns. + */ +export interface DSVRowArray extends Array> { + /** + * List of column names. + */ + columns: Columns[]; +} + +/** + * An array object representing all parsed rows. The array is enhanced with a property listing + * the names of the parsed columns. + */ +export interface DSVParsedArray extends Array { + /** + * List of column names. + */ + columns: Array; +} + +// ------------------------------------------------------------------------------------------ +// CSV Parsers and Formatters +// ------------------------------------------------------------------------------------------ + +// csvParse(...) ============================================================================ + +/** + * Parses the specified string, which must be in the comma-separated values format, returning an array of objects representing the parsed rows. + * + * Unlike csvParseRows, this method requires that the first line of the CSV content contains a comma-separated list of column names; + * these column names become the attributes on the returned objects. + * + * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). + * + * Equivalent to `dsvFormat(",").parse`. + * Note: requires unsafe-eval content security policy. + * + * @param csvString A string, which must be in the comma-separated values format. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function csvParse(csvString: string): DSVRowArray; +/** + * Parses the specified string, which must be in the comma-separated values format, returning an array of objects representing the parsed rows. + * + * Unlike csvParseRows, this method requires that the first line of the CSV content contains a comma-separated list of column names; + * these column names become the attributes on the returned objects. + * + * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). + * + * Equivalent to `dsvFormat(",").parse`. + * Note: requires unsafe-eval content security policy. + * + * @param csvString A string, which must be in the comma-separated values format. + * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), + * the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ +export function csvParse( + csvString: string, + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null, +): DSVParsedArray; + +// csvParseRows(...) ======================================================================== + +/** + * Parses the specified string, which must be in the comma-separated values format, returning an array of arrays representing the parsed rows. + * + * Unlike csvParse, this method treats the header line as a standard row, and should be used whenever CSV content does not contain a header. + * Each row is represented as an array rather than an object. Rows may have variable length. + * + * If a row conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types. + * In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the + operator), but better is to specify a row conversion function. + * + * Equivalent to `dsvFormat(",").parseRows`. + * + * @param csvString A string, which must be in the comma-separated values format. + */ +export function csvParseRows(csvString: string): string[][]; +/** + * Parses the specified string, which must be in the comma-separated values format, returning an array of arrays representing the parsed rows. + * + * Unlike csvParse, this method treats the header line as a standard row, and should be used whenever CSV content does not contain a header. + * Each row is represented as an array rather than an object. Rows may have variable length. + * + * Equivalent to `dsvFormat(",").parseRows`. + * + * @param csvString A string, which must be in the comma-separated values format. + * @param row A row conversion function which is invoked for each row, being passed an array representing the current row (d), the index (i) + * starting at zero for the first row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ +export function csvParseRows( + csvString: string, + row: (rawRow: string[], index: number) => ParsedRow | undefined | null, +): ParsedRow[]; + +// csvFormat(...) ============================================================================ + +/** + * Formats the specified array of object rows as comma-separated values, returning a string. + * This operation is the inverse of csvParse. Each row will be separated by a newline (\n), + * and each column within each row will be separated by the comma-delimiter. + * Values that contain either the comma-delimiter, a double-quote (") or a newline will be escaped using double-quotes. + * + * If columns is not specified, the list of column names that forms the header row is determined by the union of all properties on all objects in rows; + * the order of columns is nondeterministic. + * + * Equivalent to `dsvFormat(",").format`. + * + * @param rows Array of object rows. + * @param columns An array of strings representing the column names. + */ +export function csvFormat(rows: readonly T[], columns?: ReadonlyArray): string; + +// csvFormatBody(...) ============================================================================ + +/** + * Equivalent to dsvFormat(",").formatBody. + * + * @param rows Array of object rows. + * @param columns An array of strings representing the column names. + */ +export function csvFormatBody(rows: readonly T[], columns?: ReadonlyArray): string; + +// csvFormatRows(...) ======================================================================== + +/** + * Formats the specified array of array of string rows as comma-separated values, returning a string. + * This operation is the reverse of csvParseRows. Each row will be separated by a newline (\n), + * and each column within each row will be separated by the comma-delimiter. + * Values that contain either the comma-delimiter, a double-quote (") or a newline will be escaped using double-quotes. + * + * To convert an array of objects to an array of arrays while explicitly specifying the columns, use array.map. + * If you like, you can also array.concat this result with an array of column names to generate the first row. + * + * Equivalent to `dsvFormat(",").formatRows`. + * + * @param rows An array of array of string rows. + */ +export function csvFormatRows(rows: readonly string[][]): string; + +// csvFormatRow(...) ======================================================================== + +/** + * Equivalent to dsvFormat(",").formatRow. + * + * @param row An array of strings representing a row. + */ +export function csvFormatRow(row: readonly string[]): string; + +// csvFormatValue(...) ======================================================================== + +/** + * Equivalent to dsvFormat(",").formatValue. + * + * @param value A value. + */ +export function csvFormatValue(value: string): string; + +// ------------------------------------------------------------------------------------------ +// TSV Parsers and Formatters +// ------------------------------------------------------------------------------------------ + +// tsvParse(...) ============================================================================ + +/** + * Parses the specified string, which must be in the tab-separated values format, returning an array of objects representing the parsed rows. + * + * Unlike tsvParseRows, this method requires that the first line of the TSV content contains a tab-separated list of column names; + * these column names become the attributes on the returned objects. + * + * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). + * + * Equivalent to `dsvFormat("\t").parse`. + * Note: requires unsafe-eval content security policy. + * + * @param tsvString A string, which must be in the tab-separated values format. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function tsvParse(tsvString: string): DSVRowArray; +/** + * Parses the specified string, which must be in the tab-separated values format, returning an array of objects representing the parsed rows. + * + * Unlike tsvParseRows, this method requires that the first line of the TSV content contains a tab-separated list of column names; + * these column names become the attributes on the returned objects. + * + * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). + * + * Equivalent to `dsvFormat("\t").parse`. + * Note: requires unsafe-eval content security policy. + * + * @param tsvString A string, which must be in the tab-separated values format. + * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), + * the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ +export function tsvParse( + tsvString: string, + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null, +): DSVParsedArray; + +// tsvParseRows(...) ======================================================================== + +/** + * Parses the specified string, which must be in the tab-separated values format, returning an array of arrays representing the parsed rows. + * + * Unlike tsvParse, this method treats the header line as a standard row, and should be used whenever TSV content does not contain a header. + * Each row is represented as an array rather than an object. Rows may have variable length. + * + * If a row conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types. + * In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the + operator), but better is to specify a row conversion function. + * + * Equivalent to `dsvFormat("\t").parseRows`. + * + * @param tsvString A string, which must be in the tab-separated values format. + */ +export function tsvParseRows(tsvString: string): string[][]; +/** + * Parses the specified string, which must be in the tab-separated values format, returning an array of arrays representing the parsed rows. + * + * Unlike tsvParse, this method treats the header line as a standard row, and should be used whenever TSV content does not contain a header. + * Each row is represented as an array rather than an object. Rows may have variable length. + * + * Equivalent to `dsvFormat("\t").parseRows`. + * + * @param tsvString A string, which must be in the tab-separated values format. + * @param row A row conversion function which is invoked for each row, being passed an array representing the current row (d), the index (i) + * starting at zero for the first row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ +export function tsvParseRows( + tsvString: string, + row: (rawRow: string[], index: number) => ParsedRow | undefined | null, +): ParsedRow[]; + +// tsvFormat(...) ============================================================================ + +/** + * Formats the specified array of object rows as tab-separated values, returning a string. + * This operation is the inverse of tsvParse. Each row will be separated by a newline (\n), + * and each column within each row will be separated by the tab-delimiter. + * Values that contain either the tab-delimiter, a double-quote (") or a newline will be escaped using double-quotes. + * + * If columns is not specified, the list of column names that forms the header row is determined by the union of all properties on all objects in rows; + * the order of columns is nondeterministic. + * + * Equivalent to `dsvFormat("\t").format`. + * + * @param rows Array of object rows. + * @param columns An array of strings representing the column names. + */ +export function tsvFormat(rows: readonly T[], columns?: ReadonlyArray): string; + +// tsvFormatBody(...) ============================================================================ + +/** + * Equivalent to dsvFormat("\t").formatBody. + * + * @param rows Array of object rows. + * @param columns An array of strings representing the column names. + */ +export function tsvFormatBody(rows: readonly T[], columns?: ReadonlyArray): string; + +// tsvFormatRows(...) ======================================================================== + +/** + * Formats the specified array of array of string rows as tab-separated values, returning a string. + * This operation is the reverse of tsvParseRows. Each row will be separated by a newline (\n), + * and each column within each row will be separated by the tab-delimiter. + * Values that contain either the tab-delimiter, a double-quote (") or a newline will be escaped using double-quotes. + * + * To convert an array of objects to an array of arrays while explicitly specifying the columns, use array.map. + * If you like, you can also array.concat this result with an array of column names to generate the first row. + * + * Equivalent to `dsvFormat("\t").formatRows`. + * + * @param rows An array of array of string rows. + */ +export function tsvFormatRows(rows: readonly string[][]): string; + +// tsvFormatRow(...) ======================================================================== + +/** + * Equivalent to dsvFormat("\t").formatRow. + * + * @param row An array of strings representing a row. + */ +export function tsvFormatRow(row: readonly string[]): string; + +// tsvFormatValue(...) ======================================================================== + +/** + * Equivalent to dsvFormat("\t").formatValue. + * + * @param value A value. + */ +export function tsvFormatValue(value: string): string; + +// ------------------------------------------------------------------------------------------ +// DSV Generalized Parsers and Formatters +// ------------------------------------------------------------------------------------------ + +/** + * A DSV parser and formatter + */ +export interface DSV { + /** + * Parses the specified string, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of objects representing the parsed rows. + * + * Unlike dsv.parseRows, this method requires that the first line of the DSV content contains a delimiter-separated list of column names; + * these column names become the attributes on the returned objects. + * + * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). + * + * If the column names are not unique, only the last value is returned for each name; to access all values, use dsv.parseRows instead. + * + * Note: requires unsafe-eval content security policy. + * + * @param dsvString A string, which must be in the delimiter-separated values format with the appropriate delimiter. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + parse(dsvString: string): DSVRowArray; + /** + * Parses the specified string, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of objects representing the parsed rows. + * + * Unlike dsv.parseRows, this method requires that the first line of the DSV content contains a delimiter-separated list of column names; + * these column names become the attributes on the returned objects. + * + * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). + * + * If the column names are not unique, only the last value is returned for each name; to access all values, use dsv.parseRows instead. + * + * Note: requires unsafe-eval content security policy. + * + * @param dsvString A string, which must be in the delimiter-separated values format with the appropriate delimiter. + * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), + * the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ + parse( + dsvString: string, + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null, + ): DSVParsedArray; + + /** + * Parses the specified string, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of arrays representing the parsed rows. + * + * Unlike dsv.parse, this method treats the header line as a standard row, and should be used whenever DSV content does not contain a header. + * Each row is represented as an array rather than an object. Rows may have variable length. + * + * If a row conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types. + * In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the + operator), but better is to specify a row conversion function. + * + * @param dsvString A string, which must be in the delimiter-separated values format with the appropriate delimiter. + */ + parseRows(dsvString: string): string[][]; + /** + * Parses the specified string, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of arrays representing the parsed rows. + * + * Unlike dsv.parse, this method treats the header line as a standard row, and should be used whenever DSV content does not contain a header. + * Each row is represented as an array rather than an object. Rows may have variable length. + * + * @param dsvString A string, which must be in the delimiter-separated values format with the appropriate delimiter. + * @param row A row conversion function which is invoked for each row, being passed an array representing the current row (d), the index (i) + * starting at zero for the first row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ + parseRows( + dsvString: string, + row: (rawRow: string[], index: number) => ParsedRow | undefined | null, + ): ParsedRow[]; + + /** + * Formats the specified array of object rows as delimiter-separated values, returning a string. + * This operation is the inverse of dsv.parse. Each row will be separated by a newline (\n), + * and each column within each row will be separated by the delimiter (such as a comma, ,). + * Values that contain either the delimiter, a double-quote (") or a newline will be escaped using double-quotes. + * + * If columns is not specified, the list of column names that forms the header row is determined by the union of all properties on all objects in rows; + * the order of columns is nondeterministic. + * + * @param rows Array of object rows. + * @param columns An array of strings representing the column names. + */ + format(rows: readonly T[], columns?: ReadonlyArray): string; + + /** + * Equivalent to dsv.format, but omits the header row. + * This is useful, for example, when appending rows to an existing file. + * + * @param rows Array of object rows. + * @param columns An array of strings representing the column names. + */ + formatBody(rows: readonly T[], columns?: ReadonlyArray): string; + + /** + * Formats the specified array of array of string rows as delimiter-separated values, returning a string. + * This operation is the reverse of dsv.parseRows. Each row will be separated by a newline (\n), + * and each column within each row will be separated by the delimiter (such as a comma, ,). + * Values that contain either the delimiter, a double-quote (") or a newline will be escaped using double-quotes. + * + * To convert an array of objects to an array of arrays while explicitly specifying the columns, use array.map. + * If you like, you can also array.concat this result with an array of column names to generate the first row. + * + * @param rows An array of array of string rows. + */ + formatRows(rows: readonly string[][]): string; + + /** + * Formats a single array row of strings as delimiter-separated values, returning a string. + * Each column within the row will be separated by the delimiter (such as a comma, ,). + * Values that contain either the delimiter, a double-quote (") or a newline will be escaped using double-quotes. + * + * @param row An array of strings representing a row. + */ + formatRow(row: readonly string[]): string; + + /** + * Format a single value or string as a delimiter-separated value, returning a string. + * A value that contains either the delimiter, a double-quote (") or a newline will be escaped using double-quotes. + * + * @param value A value. + */ + formatValue(value: string): string; +} + +/** + * Constructs a new DSV parser and formatter for the specified delimiter. + * + * @param delimiter A delimiter character. The delimiter must be a single character (i.e., a single 16-bit code unit); + * so, ASCII delimiters are fine, but emoji delimiters are not. + */ +export function dsvFormat(delimiter: string): DSV; + +/** + * Infers the types of values on the object and coerces them accordingly, returning the mutated object. + * This function is intended to be used as a row accessor function in conjunction with dsv.parse and dsv.parseRows. + * + * @param object An object (or array) representing a parsed row + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function autoType( + object: DSVRowString | readonly string[], +): ParsedRow; diff --git a/tools/ui/node_modules/@types/d3-dsv/package.json b/tools/ui/node_modules/@types/d3-dsv/package.json new file mode 100644 index 0000000000000000000000000000000000000000..606f688063a49d409213fb0b296dbb2f5cfae709 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-dsv/package.json @@ -0,0 +1,45 @@ +{ + "name": "@types/d3-dsv", + "version": "3.0.7", + "description": "TypeScript definitions for d3-dsv", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-dsv", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-dsv" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "e9b5b33060064f4b1a2d7d09112fff5edf59333c56449dc3dbeb10c8912024b1", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-ease/LICENSE b/tools/ui/node_modules/@types/d3-ease/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-ease/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-ease/README.md b/tools/ui/node_modules/@types/d3-ease/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6cbc631dc1b7af8197c82f54cf10a08f3851fea4 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-ease/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-ease` + +# Summary +This package contains type definitions for d3-ease (https://github.com/d3/d3-ease/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-ease. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:36 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-ease/index.d.ts b/tools/ui/node_modules/@types/d3-ease/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..91b9906a818916cfd62a9a9b431cd378a1d2ec6b --- /dev/null +++ b/tools/ui/node_modules/@types/d3-ease/index.d.ts @@ -0,0 +1,316 @@ +// Last module patch version validated against: 3.0.1 + +// -------------------------------------------------------------------------- +// Easing Functions +// -------------------------------------------------------------------------- + +/** + * Linear easing; the identity function; linear(t) returns t. + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeLinear(normalizedTime: number): number; + +/** + * Symmetric quadratic easing; scales quadIn for t in [0, 0.5] and quadOut for t in [0.5, 1]. Also equivalent to poly.exponent(2). + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeQuad(normalizedTime: number): number; + +/** + * Quadratic easing; equivalent to polyIn.exponent(2). + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeQuadIn(normalizedTime: number): number; + +/** + * Reverse quadratic easing; equivalent to 1 - quadIn(1 - t). Also equivalent to polyOut.exponent(2). + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeQuadOut(normalizedTime: number): number; + +/** + * Symmetric quadratic easing; scales quadIn for t in [0, 0.5] and quadOut for t in [0.5, 1]. Also equivalent to poly.exponent(2). + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeQuadInOut(normalizedTime: number): number; + +/** + * Symmetric cubic easing; scales cubicIn for t in [0, 0.5] and cubicOut for t in [0.5, 1]. Also equivalent to poly.exponent(3). + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeCubic(normalizedTime: number): number; + +/** + * Cubic easing; equivalent to polyIn.exponent(3). + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeCubicIn(normalizedTime: number): number; + +/** + * Reverse cubic easing; equivalent to 1 - cubicIn(1 - t). Also equivalent to polyOut.exponent(3). + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeCubicOut(normalizedTime: number): number; + +/** + * Symmetric cubic easing; scales cubicIn for t in [0, 0.5] and cubicOut for t in [0.5, 1]. Also equivalent to poly.exponent(3). + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeCubicInOut(normalizedTime: number): number; + +/** + * Polynomial easing function factory + */ +export interface PolynomialEasingFactory { + /** + * Calculate eased time. + * @param normalizedTime Normalized time typically in the range [0, 1] + */ + (normalizedTime: number): number; + /** + * Returns a new polynomial easing with the specified exponent e. + * If the exponent is not specified, it defaults to 3, equivalent to cubic. + * + * @param e Exponent for polynomial easing. + */ + exponent(e: number): PolynomialEasingFactory; +} + +/** + * Symmetric polynomial easing/easing factory; scales polyIn for t in [0, 0.5] and polyOut for t in [0.5, 1]. + * If the exponent is not specified, it defaults to 3, equivalent to cubic. + */ +export const easePoly: PolynomialEasingFactory; +/** + * Polynomial easing/easing factory; raises t to the specified exponent. + * If the exponent is not specified, it defaults to 3, equivalent to cubicIn. + */ +export const easePolyIn: PolynomialEasingFactory; + +/** + * Reverse polynomial easing/easing factory; equivalent to 1 - polyIn(1 - t). + * If the exponent is not specified, it defaults to 3, equivalent to cubicOut. + */ +export const easePolyOut: PolynomialEasingFactory; + +/** + * Symmetric polynomial easing/easing factory; scales polyIn for t in [0, 0.5] and polyOut for t in [0.5, 1]. + * If the exponent is not specified, it defaults to 3, equivalent to cubic. + */ +export const easePolyInOut: PolynomialEasingFactory; + +/** + * Symmetric sinusoidal easing; scales sinIn for t in [0, 0.5] and sinOut for t in [0.5, 1]. + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeSin(normalizedTime: number): number; + +/** + * Sinusoidal easing; returns sin(t). + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeSinIn(normalizedTime: number): number; + +/** + * Reverse sinusoidal easing; equivalent to 1 - sinIn(1 - t). + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeSinOut(normalizedTime: number): number; + +/** + * Symmetric sinusoidal easing; scales sinIn for t in [0, 0.5] and sinOut for t in [0.5, 1]. + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeSinInOut(normalizedTime: number): number; + +/** + * Symmetric exponential easing; scales expIn for t in [0, 0.5] and expOut for t in [0.5, 1]. + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeExp(normalizedTime: number): number; + +/** + * Exponential easing; raises 2 to the exponent 10 * (t - 1). + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeExpIn(normalizedTime: number): number; + +/** + * Reverse exponential easing; equivalent to 1 - expIn(1 - t). + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeExpOut(normalizedTime: number): number; + +/** + * Symmetric exponential easing; scales expIn for t in [0, 0.5] and expOut for t in [0.5, 1]. + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeExpInOut(normalizedTime: number): number; + +/** + * Symmetric circular easing; scales circleIn for t in [0, 0.5] and circleOut for t in [0.5, 1]. + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeCircle(normalizedTime: number): number; + +/** + * Circular easing. + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeCircleIn(normalizedTime: number): number; + +/** + * Reverse circular easing; equivalent to 1 - circleIn(1 - t). + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeCircleOut(normalizedTime: number): number; + +/** + * Symmetric circular easing; scales circleIn for t in [0, 0.5] and circleOut for t in [0.5, 1]. + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeCircleInOut(normalizedTime: number): number; + +/** + * Reverse bounce easing; equivalent to 1 - bounceIn(1 - t). + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeBounce(normalizedTime: number): number; + +/** + * Bounce easing, like a rubber ball. + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeBounceIn(normalizedTime: number): number; + +/** + * Reverse bounce easing; equivalent to 1 - bounceIn(1 - t). + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeBounceOut(normalizedTime: number): number; + +/** + * Symmetric bounce easing; scales bounceIn for t in [0, 0.5] and bounceOut for t in [0.5, 1]. + * + * @param normalizedTime Normalized time typically in the range [0, 1] + */ +export function easeBounceInOut(normalizedTime: number): number; + +/** + * Anticipatory easing function factory + */ +export interface BackEasingFactory { + /** + * Calculate eased time. + * @param normalizedTime Normalized time typically in the range [0, 1] + */ + (normalizedTime: number): number; + /** + * Returns a new back easing with the specified overshoot s. + * The degree of overshoot is configurable; if not specified, it defaults to 1.70158. + * + * @param s Overshoot parameter + */ + overshoot(s: number): BackEasingFactory; +} + +/** + * Symmetric anticipatory easing; scales backIn for t in [0, 0.5] and backOut for t in [0.5, 1]. + * The degree of overshoot is configurable; it not specified, it defaults to 1.70158. + */ +export const easeBack: BackEasingFactory; + +/** + * Anticipatory easing, like a dancer bending their knees before jumping off the floor. + * The degree of overshoot is configurable; it not specified, it defaults to 1.70158. + */ +export const easeBackIn: BackEasingFactory; + +/** + * Reverse anticipatory easing; equivalent to 1 - backIn(1 - t). + * The degree of overshoot is configurable; it not specified, it defaults to 1.70158. + */ +export const easeBackOut: BackEasingFactory; + +/** + * Symmetric anticipatory easing; scales backIn for t in [0, 0.5] and backOut for t in [0.5, 1]. + * The degree of overshoot is configurable; it not specified, it defaults to 1.70158. + */ +export const easeBackInOut: BackEasingFactory; + +/** + * Elastic easing function factory + */ +export interface ElasticEasingFactory { + /** + * Calculate eased time. + * @param normalizedTime Normalized time typically in the range [0, 1] + */ + (normalizedTime: number): number; + /** + * Returns a new elastic easing with the specified amplitude a. + * Defaults to 1,if not specified. + * + * @param a Amplitude for elastic easing. + */ + amplitude(a: number): ElasticEasingFactory; + /** + * Returns a new elastic easing with the specified amplitude a. + * Defaults to 0.3,if not specified. + * + * @param p Period for elastic easing. + */ + period(p: number): ElasticEasingFactory; +} + +/** + * Reverse elastic easing; equivalent to 1 - elasticIn(1 - t). + * The amplitude and period of the oscillation are configurable; + * if not specified, they default to 1 and 0.3, respectively. + */ +export const easeElastic: ElasticEasingFactory; + +/** + * Elastic easing, like a rubber band. + * The amplitude and period of the oscillation are configurable; + * if not specified, they default to 1 and 0.3, respectively. + */ +export const easeElasticIn: ElasticEasingFactory; + +/** + * Reverse elastic easing; equivalent to 1 - elasticIn(1 - t). + * The amplitude and period of the oscillation are configurable; + * if not specified, they default to 1 and 0.3, respectively. + */ +export const easeElasticOut: ElasticEasingFactory; + +/** + * Symmetric elastic easing; scales elasticIn for t in [0, 0.5] and elasticOut for t in [0.5, 1]. + * The amplitude and period of the oscillation are configurable; + * if not specified, they default to 1 and 0.3, respectively. + */ +export const easeElasticInOut: ElasticEasingFactory; diff --git a/tools/ui/node_modules/@types/d3-ease/package.json b/tools/ui/node_modules/@types/d3-ease/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ab041df07b3990f575836b102c86cef700629035 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-ease/package.json @@ -0,0 +1,40 @@ +{ + "name": "@types/d3-ease", + "version": "3.0.2", + "description": "TypeScript definitions for d3-ease", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-ease", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-ease" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "2995c518f8de4fa6f2abb2f13065cb4fe65acaea9422f9883b24414ef50cd1ab", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-fetch/LICENSE b/tools/ui/node_modules/@types/d3-fetch/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-fetch/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-fetch/README.md b/tools/ui/node_modules/@types/d3-fetch/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9b4aed29290434e817e335036df34e89e3fb0c07 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-fetch/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-fetch` + +# Summary +This package contains type definitions for d3-fetch (https://d3js.org/d3-fetch/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-fetch. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:36 GMT + * Dependencies: [@types/d3-dsv](https://npmjs.com/package/@types/d3-dsv) + +# Credits +These definitions were written by [Hugues Stefanski](https://github.com/ledragon), [denisname](https://github.com/denisname), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-fetch/index.d.ts b/tools/ui/node_modules/@types/d3-fetch/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3f71704ae1564862cae2106abb9243c640832710 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-fetch/index.d.ts @@ -0,0 +1,282 @@ +// Last module patch version validated against: 3.0.1 + +import { DSVParsedArray, DSVRowArray, DSVRowString } from "d3-dsv"; + +/** + * Fetches the binary file at the specified input URL and returns it as a Promise of a Blob. + * If init is specified, it is passed along to the underlying call to fetch. + * + * @param url A valid URL string. + * @param init An optional request initialization object. + */ +export function blob(url: string, init?: RequestInit): Promise; + +/** + * Fetches the binary file at the specified input URL and returns it as a Promise of an ArrayBuffer. + * If init is specified, it is passed along to the underlying call to fetch. + * + * @param url A valid URL string. + * @param init An optional request initialization object. + */ +export function buffer(url: string, init?: RequestInit): Promise; + +/** + * Fetches the CSV file at the specified input URL and returns + * a promise of an array of objects representing the parsed rows. The values of the properties of the parsed row + * objects are represented as strings. + * + * If init is specified, it is passed along to the underlying call to fetch. + * + * The generic parameter describes the column names as a union of string literal types. + * + * @param url A valid URL string. + * @param init An optional request initialization object. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function csv( + url: string, + init?: RequestInit, +): Promise>; +/** + * Fetches the CSV file at the specified input URL and returns + * a promise of an array of objects representing the parsed rows. + * + * The specified row conversion function is used to map and filter row objects to a more-specific representation; + * see dsv.csvParse for details. + * + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. + * + * @param url A valid URL string. + * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), + * the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be omitted from the array returned by dsv.csvParse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ +export function csv( + url: string, + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null, +): Promise>; +/** + * Fetches the CSV file at the specified input URL and returns + * a promise of an array of objects representing the parsed rows. + * + * The init object is passed along to the underlying call to fetch. + * + * The specified row conversion function is used to map and filter row objects to a more-specific representation; + * see dsv.csvParse for details. + * + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. + * + * @param url A valid URL string. + * @param init An request initialization object. + * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), + * the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be omitted from the array returned by dsv.csvParse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ +export function csv( + url: string, + init: RequestInit, + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null, +): Promise>; + +/** + * Fetches the DSV file with the specified delimiter character at the specified input URL and returns + * a promise of an array of objects representing the parsed rows. The values of the properties of the parsed row + * objects are represented as strings. + * + * If init is specified, it is passed along to the underlying call to fetch. + * + * The generic parameter describes the column names as a union of string literal types. + * + * @param delimiter The delimiter character used in the DSV file to be fetched. + * @param url A valid URL string. + * @param init An optional request initialization object. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function dsv( + delimiter: string, + url: string, + init?: RequestInit, +): Promise>; +/** + * Fetches the DSV file with the specified delimiter character at the specified input URL and returns + * a promise of an array of objects representing the parsed rows. + * + * The specified row conversion function is used to map and filter row objects to a more-specific representation; + * see dsv.parse for details. + * + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. + * + * @param delimiter The delimiter character used in the DSV file to be fetched. + * @param url A valid URL string. + * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), + * the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ +export function dsv( + delimiter: string, + url: string, + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null, +): Promise>; +/** + * Fetches the DSV file with the specified delimiter character at the specified input URL and returns + * a promise of an array of objects representing the parsed rows. + * + * The init object is passed along to the underlying call to fetch. + * + * The specified row conversion function is used to map and filter row objects to a more-specific representation; + * see dsv.parse for details. + * + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. + * + * @param delimiter The delimiter character used in the DSV file to be fetched. + * @param url A valid URL string. + * @param init An request initialization object. + * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), + * the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ +export function dsv( + delimiter: string, + url: string, + init: RequestInit, + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null, +): Promise>; + +/** + * Fetches the file at the specified input URL as text, parses it as HTML and returns a Promise of an HTML DOM Document. + * + * If init is specified, it is passed along to the underlying call to fetch. + * + * @param url A valid URL string. + * @param init An optional request initialization object. + */ +export function html(url: string, init?: RequestInit): Promise; + +/** + * Fetches the image at the specified input URL and returns a promise of an HTML image element. + * + * If init is specified, sets any additional properties on the image before loading. + * + * @param url A valid URL string. + * @param init An optional object of image properties to set. + */ +export function image(url: string, init?: Partial): Promise; + +/** + * Fetches the json file at the specified input URL and returns it as a Promise of a parsed JSON object. + * + * If init is specified, it is passed along to the underlying call to fetch. + * + * If the server returns a status code of [204 No Content](https://developer.mozilla.org/docs/Web/HTTP/Status/204) + * or [205 Reset Content](https://developer.mozilla.org/docs/Web/HTTP/Status/205), the promise resolves to `undefined`. + * + * The generic parameter describes the type of the object parsed from the returned JSON. + * + * @param url A valid URL string. + * @param init An optional request initialization object. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function json( + url: string, + init?: RequestInit, +): Promise; + +/** + * Fetches the file at the specified input URL as text, parses it as SVG and returns a Promise of an SVG Document. + * + * If init is specified, it is passed along to the underlying call to fetch. + * + * @param url A valid URL string. + * @param init An optional request initialization object. + */ +export function svg(url: string, init?: RequestInit): Promise; + +/** + * Fetches the text file at the specified input URL and returns it as a Promise of a string. + * + * If init is specified, it is passed along to the underlying call to fetch. + * + * @param url A valid URL string. + * @param init An optional request initialization object. + */ +export function text(url: string, init?: RequestInit): Promise; + +/** + * Fetches the TSV file at the specified input URL and returns + * a promise of an array of objects representing the parsed rows. + * + * If init is specified, it is passed along to the underlying call to fetch. + * + * The generic parameter describes the column names as a union of string literal types. + * + * @param url A valid URL string. + * @param init An optional request initialization object. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function tsv( + url: string, + init?: RequestInit, +): Promise>; +/** + * Fetches the TSV file at the specified input URL and returns + * a promise of an array of objects representing the parsed rows. The values of the properties of the parsed row + * objects are represented as strings. + * + * The specified row conversion function is used to map and filter row objects to a more-specific representation; + * see dsv.tsvParse for details. + * + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. + * + * @param url A valid URL string. + * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), + * the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be omitted from the array returned by dsv.tsvParse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ +export function tsv( + url: string, + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null, +): Promise>; +/** + * Fetches the TSV file at the specified input URL and returns + * a promise of an array of objects representing the parsed rows. + * + * The init object is passed along to the underlying call to fetch. + * + * The specified row conversion function is used to map and filter row objects to a more-specific representation; + * see dsv.tsvParse for details. + * + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. + * + * @param url A valid URL string. + * @param init An request initialization object. + * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), + * the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be omitted from the array returned by dsv.tsvParse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ +export function tsv( + url: string, + init: RequestInit, + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null, +): Promise>; + +/** + * Fetches the file at the specified input URL as text, parses it as XML and returns a Promise of an XML Document. + * + * If init is specified, it is passed along to the underlying call to fetch. + * + * @param url A valid URL string. + * @param init An optional request initialization object. + */ +export function xml(url: string, init?: RequestInit): Promise; diff --git a/tools/ui/node_modules/@types/d3-fetch/package.json b/tools/ui/node_modules/@types/d3-fetch/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6fb7e5f1e5771b5dbd352e2f595aa58a70ef7b6b --- /dev/null +++ b/tools/ui/node_modules/@types/d3-fetch/package.json @@ -0,0 +1,37 @@ +{ + "name": "@types/d3-fetch", + "version": "3.0.7", + "description": "TypeScript definitions for d3-fetch", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-fetch", + "license": "MIT", + "contributors": [ + { + "name": "Hugues Stefanski", + "githubUsername": "ledragon", + "url": "https://github.com/ledragon" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-fetch" + }, + "scripts": {}, + "dependencies": { + "@types/d3-dsv": "*" + }, + "typesPublisherContentHash": "0757ff56bd9c67608b51696a50c55993b4588c4d3ec13c6b6f8a3ddd75b375af", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-force/LICENSE b/tools/ui/node_modules/@types/d3-force/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-force/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-force/README.md b/tools/ui/node_modules/@types/d3-force/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3a6610211b34f0f4046a9300c55c79907ab96852 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-force/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-force` + +# Summary +This package contains type definitions for d3-force (https://github.com/d3/d3-force/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-force. + +### Additional Details + * Last updated: Mon, 17 Jun 2024 20:07:03 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [denisname](https://github.com/denisname), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-force/index.d.ts b/tools/ui/node_modules/@types/d3-force/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8801ae53bed761c5a2d2c3dc9cbfc3d19e931abc --- /dev/null +++ b/tools/ui/node_modules/@types/d3-force/index.d.ts @@ -0,0 +1,899 @@ +// Last module patch version validated against: 3.0.0 + +// ----------------------------------------------------------------------- +// Force Simulation +// ----------------------------------------------------------------------- + +/** + * The base data structure for the datum of a Simulation Node. + * The optional properties contained in this data structure are internally assigned + * by the Simulation upon (re-)initialization. + * + * When defining a data type to use for node data, it should be an extension of this interface + * and respect the already "earmarked" properties used by the simulation. + * + * IMPORTANT: Prior to initialization, the following properties are optional: index, x, y, vx, and vy. + * After initialization they will be defined. The optional properties fx and fy are ONLY defined, + * if the node's position has been fixed. + */ +export interface SimulationNodeDatum { + /** + * Node’s zero-based index into nodes array. This property is set during the initialization process of a simulation. + */ + index?: number | undefined; + /** + * Node’s current x-position + */ + x?: number | undefined; + /** + * Node’s current y-position + */ + y?: number | undefined; + /** + * Node’s current x-velocity + */ + vx?: number | undefined; + /** + * Node’s current y-velocity + */ + vy?: number | undefined; + /** + * Node’s fixed x-position (if position was fixed) + */ + fx?: number | null | undefined; + /** + * Node’s fixed y-position (if position was fixed) + */ + fy?: number | null | undefined; +} + +/** + * The base data structure for the datum of a Simulation Link, as used by ForceLink. + * The optional properties contained in this data structure are internally assigned + * by when initializing with ForceLink.links(...) + * + * IMPORTANT: The source and target properties may be internally mutated in type during the + * ForceLink initialization process (possibly being changed from a node index in the nodes array, + * or a node id string to the simulation node object which was mapped in using the current + * ForceLink.id(...) accessor function.) + */ +export interface SimulationLinkDatum { + /** + * Link’s source node. + * For convenience, a link’s source and target properties may be initialized using numeric or string identifiers rather than object references; see link.id. + * When the link force is initialized (or re-initialized, as when the nodes or links change), any link.source or link.target property which is not an object + * is replaced by an object reference to the corresponding node with the given identifier. + * After initialization, the source property represents the source node object. + */ + source: NodeDatum | string | number; + /** + * Link’s source link + * For convenience, a link’s source and target properties may be initialized using numeric or string identifiers rather than object references; see link.id. + * When the link force is initialized (or re-initialized, as when the nodes or links change), any link.source or link.target property which is not an object + * is replaced by an object reference to the corresponding node with the given identifier. + * After initialization, the target property represents the target node object. + */ + target: NodeDatum | string | number; + /** + * The zero-based index into the links array. Internally generated when calling ForceLink.links(...) + */ + index?: number | undefined; +} + +/** + * A Force Simulation + * + * The first generic refers to the type of the datum associated with a node in the simulation. + * The second generic refers to the type of the datum associated with a link in the simulation, if applicable. + */ +export interface Simulation< + NodeDatum extends SimulationNodeDatum, + LinkDatum extends SimulationLinkDatum | undefined, +> { + /** + * Restart the simulation’s internal timer and return the simulation. + * In conjunction with simulation.alphaTarget or simulation.alpha, this method can be used to “reheat” the simulation during interaction, + * such as when dragging a node, or to resume the simulation after temporarily pausing it with simulation.stop. + */ + restart(): this; + + /** + * Stop the simulation’s internal timer, if it is running, and return the simulation. If the timer is already stopped, this method does nothing. + * This method is useful for running the simulation manually; see simulation.tick. + */ + stop(): this; + + /** + * Manually steps the simulation by the specified number of *iterations*, and returns the simulation. If *iterations* is not specified, it defaults to 1 (single step). + * + * For each iteration, it increments the current alpha by (alphaTarget - alpha) × alphaDecay; then invokes each registered force, passing the new alpha; + * then decrements each node’s velocity by velocity × velocityDecay; lastly increments each node’s position by velocity. + * + * This method does not dispatch events; events are only dispatched by the internal timer when the simulation is started automatically upon + * creation or by calling simulation.restart. The natural number of ticks when the simulation is started is + * ⌈log(alphaMin) / log(1 - alphaDecay)⌉; by default, this is 300. + */ + tick(iterations?: number): this; + + /** + * Returns the simulation’s array of nodes as specified to the constructor. + */ + nodes(): NodeDatum[]; + /** + * Set the simulation’s nodes to the specified array of objects, initialize their positions and velocities if necessary, + * and then re-initialize any bound forces; Returns the simulation. + * + * Each node must be an object. The following properties are assigned by the simulation: + * - index (the node’s zero-based index into nodes) + * - x (the node’s current x-position) + * - y (the node’s current y-position) + * - vx (the node’s current x-velocity) + * - vy (the node’s current y-velocity) + * + * The position [x,y] and velocity [vx,vy] may be subsequently modified by forces and by the simulation. + * If either vx or vy is NaN, the velocity is initialized to [0,0]. If either x or y is NaN, the position is initialized in a phyllotaxis arrangement, + * so chosen to ensure a deterministic, uniform distribution. + * + * To fix a node in a given position, you may specify two additional properties: + * - fx (the node’s fixed x-position) + * - fy (the node’s fixed y-position) + * + * At the end of each tick, after the application of any forces, a node with a defined node.fx has node.x reset to this value and node.vx set to zero; + * likewise, a node with a defined node.fy has node.y reset to this value and node.vy set to zero. + * To unfix a node that was previously fixed, set node.fx and node.fy to null, or delete these properties. + * + * If the specified array of nodes is modified, such as when nodes are added to or removed from the simulation, + * this method must be called again with the new (or changed) array to notify the simulation and bound forces of the change; + * the simulation does not make a defensive copy of the specified array. + */ + nodes(nodesData: NodeDatum[]): this; + + /** + * Return the current alpha of the simulation, which defaults to 1. + * + * alpha is roughly analogous to temperature in simulated annealing. + * It decreases over time as the simulation “cools down”. + * When alpha reaches alphaMin, the simulation stops; see simulation.restart. + */ + alpha(): number; + /** + * Set the current alpha to the specified number in the range [0,1] and return this simulation. + * The default is 1. + * + * alpha is roughly analogous to temperature in simulated annealing. + * It decreases over time as the simulation “cools down”. + * When alpha reaches alphaMin, the simulation stops; see simulation.restart. + * + * @param alpha Current alpha of simulation. + */ + alpha(alpha: number): this; + + /** + * Return the current minimum alpha value, which defaults to 0.001. + */ + alphaMin(): number; + /** + * Set the minimum alpha to the specified number in the range [0,1] and return this simulation. + * The default is 0.001. The simulation’s internal timer stops when the current alpha is less than the minimum alpha. + * The default alpha decay rate of ~0.0228 corresponds to 300 iterations. + * + * @param min Minimum alpha of simulation. + */ + alphaMin(min: number): this; + + /** + * Return the current alpha decay rate, which defaults to 0.0228… = 1 - pow(0.001, 1 / 300) where 0.001 is the default minimum alpha. + */ + alphaDecay(): number; + /** + * Set the alpha decay rate to the specified number in the range [0,1] and return this simulation. + * The default is 0.0228… = 1 - pow(0.001, 1 / 300) where 0.001 is the default minimum alpha. + * + * The alpha decay rate determines how quickly the current alpha interpolates towards the desired target alpha; + * since the default target alpha is zero, by default this controls how quickly the simulation cools. + * Higher decay rates cause the simulation to stabilize more quickly, but risk getting stuck in a local minimum; + * lower values cause the simulation to take longer to run, but typically converge on a better layout. + * To have the simulation run forever at the current alpha, set the decay rate to zero; + * alternatively, set a target alpha greater than the minimum alpha. + * + * @param decay Alpha decay rate. + */ + alphaDecay(decay: number): this; + + /** + * Returns the current target alpha value, which defaults to 0. + */ + alphaTarget(): number; + /** + * Set the current target alpha to the specified number in the range [0,1] and return this simulation. + * The default is 0. + * + * @param target Alpha target value. + */ + alphaTarget(target: number): this; + + /** + * Return the current target alpha value, which defaults to 0.4. + */ + velocityDecay(): number; + /** + * Set the velocity decay factor to the specified number in the range [0,1] and return this simulation. + * The default is 0.4. + * + * The decay factor is akin to atmospheric friction; after the application of any forces during a tick, + * each node’s velocity is multiplied by 1 - decay. As with lowering the alpha decay rate, + * less velocity decay may converge on a better solution, but risks numerical instabilities and oscillation. + * + * @param decay Velocity Decay. + */ + velocityDecay(decay: number): this; + + /** + * Return the force with the specified name, or undefined if there is no such force. + * (By default, new simulations have no forces.) + * + * Given that it is in general not known, what type of force has been registered under + * a specified name, use the generic to cast the result to the appropriate type, if known. + * + * @param name Name of the registered force. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + force>(name: string): F | undefined; + /** + * If force is specified, assigns the force for the specified name and returns this simulation. + * To remove the force with the given name, pass null as the force. + */ + force(name: string, force: null | Force): this; + + /** + * Return the node closest to the position [x,y] with the given search radius. + * If radius is not specified, it defaults to infinity. + * If there is no node within the search area, returns undefined. + * + * @param x x-coordinate + * @param y y-coordinate + * @param radius Optional search radius. Defaults to infinity. + */ + find(x: number, y: number, radius?: number): NodeDatum | undefined; + + /** + * Returns this simulation’s current random source which defaults to a fixed-seed linear congruential generator. + * See also random.source. + */ + randomSource(): () => number; + /** + * Sets the function used to generate random numbers; this should be a function that returns a number between 0 (inclusive) and 1 (exclusive). + * + * @param source The function used to generate random numbers. + */ + randomSource(source: () => number): this; + + /** + * Return the first currently-assigned listener matching the specified typenames, if any. + * + * @param typenames The typenames is a string containing one or more typename separated by whitespace. Each typename is a type, + * optionally followed by a period (.) and a name, such as "tick.foo" and "tick.bar"; the name allows multiple listeners to be registered for the same type. + * The type must be one of the following: "tick" (after each tick of the simulation’s internal timer) or + * "end" (after the simulation’s timer stops when alpha < alphaMin). + */ + on(typenames: "tick" | "end" | string): ((this: Simulation) => void) | undefined; + /** + * Sets the event listener for the specified typenames and returns this simulation. + * If an event listener was already registered for the same type and name, the existing listener is removed before the new listener is added. + * If listener is null, removes the current event listeners for the specified typenames, if any. + * When a specified event is dispatched, each listener will be invoked with the this context as the simulation. + */ + on(typenames: "tick" | "end" | string, listener: null | ((this: this) => void)): this; +} + +/** + * Create a new simulation with the specified array of nodes and no forces. + * If nodes is not specified, it defaults to the empty array. + * The simulator starts automatically; use simulation.on to listen for tick events as the simulation runs. + * If you wish to run the simulation manually instead, call simulation.stop, and then call simulation.tick as desired. + * + * Use this signature, when creating a simulation WITHOUT link force(s). + * + * The generic refers to the type of the data for a node. + * + * @param nodesData Optional array of nodes data, defaults to empty array. + */ +export function forceSimulation( + nodesData?: NodeDatum[], +): Simulation; +/** + * Create a new simulation with the specified array of nodes and no forces. + * If nodes is not specified, it defaults to the empty array. + * The simulator starts automatically; use simulation.on to listen for tick events as the simulation runs. + * If you wish to run the simulation manually instead, call simulation.stop, and then call simulation.tick as desired. + * + * Use this signature, when creating a simulation WITH link force(s). + * + * The first generic refers to the type of data for a node. + * The second generic refers to the type of data for a link. + * + * @param nodesData Optional array of nodes data, defaults to empty array. + */ +export function forceSimulation< + NodeDatum extends SimulationNodeDatum, + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + LinkDatum extends SimulationLinkDatum, +>(nodesData?: NodeDatum[]): Simulation; + +// ---------------------------------------------------------------------- +// Forces +// ---------------------------------------------------------------------- + +/** + * A force is simply a function that modifies nodes’ positions or velocities; in this context, a force can apply a classical physical force such as electrical charge or gravity, + * or it can resolve a geometric constraint, such as keeping nodes within a bounding box or keeping linked nodes a fixed distance apart. + * + * Forces typically read the node’s current position [x,y] and then add to (or subtract from) the node’s velocity [vx,vy]. + * However, forces may also “peek ahead” to the anticipated next position of the node, [x + vx,y + vy]; this is necessary for resolving geometric constraints through iterative relaxation. + * Forces may also modify the position directly, which is sometimes useful to avoid adding energy to the simulation, such as when recentering the simulation in the viewport. + * + * Forces may optionally implement force.initialize to receive the simulation’s array of nodes. + */ +export interface Force< + NodeDatum extends SimulationNodeDatum, + LinkDatum extends SimulationLinkDatum | undefined, +> { + /** + * Apply this force, optionally observing the specified alpha. + * Typically, the force is applied to the array of nodes previously passed to force.initialize, + * however, some forces may apply to a subset of nodes, or behave differently. + * For example, d3.forceLink applies to the source and target of each link. + */ + (alpha: number): void; + /** + * Supplies the array of nodes and random source to this force. This method is called when a force is bound to a simulation via simulation.force + * and when the simulation’s nodes change via simulation.nodes. + * + * A force may perform necessary work during initialization, such as evaluating per-node parameters, to avoid repeatedly performing work during each application of the force. + */ + initialize?(nodes: NodeDatum[], random: () => number): void; +} + +// Centering ------------------------------------------------------------ + +/** + * The centering force translates nodes uniformly so that the mean position of all nodes + * (the center of mass if all nodes have equal weight) is at the given position [x,y]. + * This force modifies the positions of nodes on each application; it does not modify velocities, + * as doing so would typically cause the nodes to overshoot and oscillate around the desired center. + * This force helps keeps nodes in the center of the viewport, and unlike the positioning force, + * it does not distort their relative positions. + * + * The generic refers to the type of data for a node. + */ +export interface ForceCenter extends Force { + /** + * Supplies the array of nodes and random source to this force. This method is called when a force is bound to a simulation via simulation.force + * and when the simulation’s nodes change via simulation.nodes. + * + * A force may perform necessary work during initialization, such as evaluating per-node parameters, to avoid repeatedly performing work during each application of the force. + */ + initialize(nodes: NodeDatum[], random: () => number): void; + + /** + * Return the current x-coordinate of the centering position, which defaults to zero. + */ + x(): number; + /** + * Set the x-coordinate of the centering position. + * + * @param x x-coordinate. + */ + x(x: number): this; + + /** + * Return the current y-coordinate of the centering position, which defaults to zero. + */ + y(): number; + /** + * Set the y-coordinate of the centering position. + * + * @param y y-coordinate. + */ + y(y: number): this; + + /** + * Returns the force’s current strength, which defaults to 1. + */ + strength(): number; + + /** + * Sets the centering force’s strength. + * A reduced strength of e.g. 0.05 softens the movements on interactive graphs in which new nodes enter or exit the graph. + * @param strength The centering force's strength. + */ + strength(strength: number): this; +} + +/** + * Create a new centering force with the specified x- and y- coordinates. + * If x and y are not specified, they default to [0,0]. + * + * The centering force translates nodes uniformly so that the mean position of all nodes + * (the center of mass if all nodes have equal weight) is at the given position [x,y]. + * This force modifies the positions of nodes on each application; it does not modify velocities, + * as doing so would typically cause the nodes to overshoot and oscillate around the desired center. + * This force helps keeps nodes in the center of the viewport, and unlike the positioning force, + * it does not distort their relative positions. + * + * The generic refers to the type of data for a node. + * + * @param x An optional x-coordinate for the centering position, defaults to 0. + * @param y An optional y-coordinate for the centering position, defaults to 0. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function forceCenter(x?: number, y?: number): ForceCenter; + +// Collision ------------------------------------------------------------ + +/** + * The collision force treats nodes as circles with a given radius, rather than points, and prevents nodes from overlapping. + * More formally, two nodes a and b are separated so that the distance between a and b is at least radius(a) + radius(b). + * To reduce jitter, this is by default a “soft” constraint with a configurable strength and iteration count. + * + * The generic refers to the type of data for a node. + */ +export interface ForceCollide extends Force { + /** + * Supplies the array of nodes and random source to this force. This method is called when a force is bound to a simulation via simulation.force + * and when the simulation’s nodes change via simulation.nodes. + * + * A force may perform necessary work during initialization, such as evaluating per-node parameters, to avoid repeatedly performing work during each application of the force. + */ + initialize(nodes: NodeDatum[], random: () => number): void; + + /** + * Returns the current radius accessor function. + */ + radius(): (node: NodeDatum, i: number, nodes: NodeDatum[]) => number; + /** + * Sets the radius accessor to the specified number or function, re-evaluates the radius accessor for each node, and returns this force. + * The radius accessor is invoked for each node in the simulation, being passed the node and its zero-based index. + * The resulting number is then stored internally, such that the radius of each node is only recomputed when the + * force is initialized or when this method is called with a new radius, and not on every application of the force. + */ + radius(radius: number | ((node: NodeDatum, i: number, nodes: NodeDatum[]) => number)): this; + + /** + * Return the current strength, which defaults to 1. + */ + strength(): number; + /** + * Set the force strength to the specified number in the range [0,1] and return this force. + * The default strength is 1. + * + * Overlapping nodes are resolved through iterative relaxation. + * For each node, the other nodes that are anticipated to overlap at the next tick (using the anticipated positions [x + vx,y + vy]) are determined; + * the node’s velocity is then modified to push the node out of each overlapping node. + * The change in velocity is dampened by the force’s strength such that the resolution of simultaneous overlaps can be blended together to find a stable solution. + * + * @param strength Strength. + */ + strength(strength: number): this; + + /** + * Return the current iteration count which defaults to 1. + */ + iterations(): number; + /** + * Sets the number of iterations per application to the specified number and return this force. + * + * Increasing the number of iterations greatly increases the rigidity of the constraint and avoids partial overlap of nodes, + * but also increases the runtime cost to evaluate the force. + * + * @param iterations Number of iterations. + */ + iterations(iterations: number): this; +} + +/** + * Creates a new circle collision force with the specified radius. + * If radius is not specified, it defaults to the constant one for all nodes. + */ +export function forceCollide( + radius?: number | ((node: NodeDatum, i: number, nodes: NodeDatum[]) => number), +): ForceCollide; + +// Link ---------------------------------------------------------------- + +/** + * The link force pushes linked nodes together or apart according to the desired link distance. + * The strength of the force is proportional to the difference between the linked nodes’ distance and the target distance, similar to a spring force. + * + * The first generic refers to the type of data for a node. + * The second generic refers to the type of data for a link. + */ +export interface ForceLink> + extends Force +{ + /** + * Supplies the array of nodes and random source to this force. This method is called when a force is bound to a simulation via simulation.force + * and when the simulation’s nodes change via simulation.nodes. + * + * A force may perform necessary work during initialization, such as evaluating per-node parameters, to avoid repeatedly performing work during each application of the force. + */ + initialize(nodes: NodeDatum[], random: () => number): void; + + /** + * Return the current array of links, which defaults to the empty array. + */ + links(): LinkDatum[]; + /** + * Set the array of links associated with this force, recompute the distance and strength parameters for each link, and return this force. + * + * Each link is an object with the following properties: + * * source - the link’s source node; see simulation.nodes + * * target - the link’s target node; see simulation.nodes + * * index - the zero-based index into links, assigned by this method + * + * For convenience, a link’s source and target properties may be initialized using numeric or string identifiers rather than object references; see link.id. + * When the link force is initialized (or re-initialized, as when the nodes or links change), any link.source or link.target property which is not an object + * is replaced by an object reference to the corresponding node with the given identifier. + * If the specified array of links is modified, such as when links are added to or removed from the simulation, + * this method must be called again with the new (or changed) array to notify the force of the change; + * the force does not make a defensive copy of the specified array. + * + * @param links An array of link data. + */ + links(links: LinkDatum[]): this; + + /** + * Return the current node id accessor, which defaults to the numeric node.index. + */ + id(): (node: NodeDatum, i: number, nodesData: NodeDatum[]) => string | number; + /** + * Set the node id accessor to the specified function and return this force. + * + * The default id accessor allows each link’s source and target to be specified as a zero-based index + * into the nodes array. + * + * The id accessor is invoked for each node whenever the force is initialized, + * as when the nodes or links change, being passed the node, the zero-based index of the node in the node array, and the node array. + * + * @param id A node id accessor function which is invoked for each node in the simulation, + * being passed the node, the zero-based index of the node in the node array, and the node array. It returns a string or number to represent the node id which can be used + * for matching link source and link target strings during the ForceLink initialization. + */ + id(id: (node: NodeDatum, i: number, nodesData: NodeDatum[]) => string | number): this; + + /** + * Return the current distance accessor, which defaults to implying a default distance of 30. + */ + distance(): (link: LinkDatum, i: number, links: LinkDatum[]) => number; + /** + * Sets the distance accessor to the specified number or function, re-evaluates the distance accessor for each link, and returns this force. + * The distance accessor is invoked for each link, being passed the link and its zero-based index. + * The resulting number is then stored internally, such that the distance of each link is only recomputed when the + * force is initialized or when this method is called with a new distance, and not on every application of the force. + */ + distance(distance: number | ((link: LinkDatum, i: number, links: LinkDatum[]) => number)): this; + + /** + * Return the current strength accessor. + * For details regarding the default behavior see: {@link https://github.com/d3/d3-force#link_strength} + */ + strength(): (link: LinkDatum, i: number, links: LinkDatum[]) => number; + /** + * Sets the strength accessor to the specified number or function, re-evaluates the strength accessor for each link, and returns this force. + * The strength accessor is invoked for each link, being passed the link and its zero-based index. + * The resulting number is then stored internally, such that the strength of each link is only recomputed when the + * force is initialized or when this method is called with a new strength, and not on every application of the force. + */ + strength(strength: number | ((link: LinkDatum, i: number, links: LinkDatum[]) => number)): this; + + /** + * Return the current iteration count which defaults to 1. + */ + iterations(): number; + /** + * Sets the number of iterations per application to the specified number and return this force. + * + * Increasing the number of iterations greatly increases the rigidity of the constraint and is useful for complex structures such as lattices, + * but also increases the runtime cost to evaluate the force. + * + * @param iterations Number of iterations. + */ + iterations(iterations: number): this; +} + +/** + * Creates a new link force with the specified links and default parameters. + * If links is not specified, it defaults to the empty array. + */ +export function forceLink>( + links?: LinksDatum[], +): ForceLink; + +// Many Body ---------------------------------------------------------------- + +/** + * The many-body (or n-body) force applies mutually amongst all nodes. It can be used to simulate gravity (attraction) if the strength is positive, + * or electrostatic charge (repulsion) if the strength is negative. This implementation uses quadtrees and the Barnes–Hut approximation to greatly + * improve performance; the accuracy can be customized using the theta parameter. + * + * Unlike links, which only affect two linked nodes, the charge force is global: every node affects every other node, even if they are on disconnected subgraphs. + * + * The generic refers to the type of data for a node. + */ +export interface ForceManyBody extends Force { + /** + * Supplies the array of nodes and random source to this force. This method is called when a force is bound to a simulation via simulation.force + * and when the simulation’s nodes change via simulation.nodes. + * + * A force may perform necessary work during initialization, such as evaluating per-node parameters, to avoid repeatedly performing work during each application of the force. + */ + initialize(nodes: NodeDatum[], random: () => number): void; + + /** + * Return the current strength accessor. + * + * For details regarding the default behavior see: {@link https://github.com/d3/d3-force#manyBody_strength} + */ + strength(): (d: NodeDatum, i: number, data: NodeDatum[]) => number; + /** + * sets the strength accessor to the specified number or function, re-evaluates the strength accessor for each node, and returns this force. + * A positive value causes nodes to attract each other, similar to gravity, while a negative value causes nodes to repel each other, similar to electrostatic charge. + * The strength accessor is invoked for each node in the simulation, being passed the node and its zero-based index. + * The resulting number is then stored internally, such that the strength of each node is only recomputed when the + * force is initialized or when this method is called with a new strength, and not on every application of the force. + */ + strength(strength: number | ((d: NodeDatum, i: number, data: NodeDatum[]) => number)): this; + + /** + * Return the current value of the Barnes–Hut approximation criterion , which defaults to 0.9 + */ + theta(): number; + /** + * Set the Barnes–Hut approximation criterion to the specified number and returns this force. + * + * To accelerate computation, this force implements the Barnes–Hut approximation which takes O(n log n) per application + * where n is the number of nodes. For each application, a quadtree stores the current node positions; + * then for each node, the combined force of all other nodes on the given node is computed. + * For a cluster of nodes that is far away, the charge force can be approximated by treating the cluster as a single, larger node. + * The theta parameter determines the accuracy of the approximation: + * if the ratio w / l of the width w of the quadtree cell to the distance l from the node to the cell’s center of mass is less than theta, + * all nodes in the given cell are treated as a single node rather than individually. + * + * The default value is 0.9. + * + * @param theta Value for the theta parameter. + */ + theta(theta: number): this; + + /** + * Returns the current minimum distance over which this force is considered, which defaults to 1. + */ + distanceMin(): number; + /** + * Sets the minimum distance between nodes over which this force is considered. + * + * A minimum distance establishes an upper bound on the strength of the force between two nearby nodes, avoiding instability. + * In particular, it avoids an infinitely-strong force if two nodes are exactly coincident; in this case, the direction of the force is random. + * + * The default value is 1. + * + * @param distance The minimum distance between nodes over which this force is considered. + */ + distanceMin(distance: number): this; + + /** + * Returns the current maximum distance over which this force is considered, which defaults to infinity. + */ + distanceMax(): number; + /** + * Sets the maximum distance between nodes over which this force is considered. + * + * Specifying a finite maximum distance improves performance and produces a more localized layout. + * + * The default value is infinity. + * + * @param distance The maximum distance between nodes over which this force is considered. + */ + distanceMax(distance: number): this; +} + +/** + * Creates a new many-body force with the default parameters. + * + * The many-body (or n-body) force applies mutually amongst all nodes. It can be used to simulate gravity (attraction) if the strength is positive, + * or electrostatic charge (repulsion) if the strength is negative. This implementation uses quadtrees and the Barnes–Hut approximation to greatly + * improve performance; the accuracy can be customized using the theta parameter. + * + * Unlike links, which only affect two linked nodes, the charge force is global: every node affects every other node, even if they are on disconnected subgraphs. + * + * The generic refers to the type of data for a node. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function forceManyBody(): ForceManyBody; + +// Positioning ---------------------------------------------------------------- + +/** + * The x-positioning force pushes nodes towards a desired position along the given dimension with a configurable strength. + * The strength of the force is proportional to the one-dimensional distance between the node’s position and the target position. + * While this force can be used to position individual nodes, it is intended primarily for global forces that apply to all (or most) nodes. + * + * The generic refers to the type of data for a node. + */ +export interface ForceX extends Force { + /** + * Supplies the array of nodes and random source to this force. This method is called when a force is bound to a simulation via simulation.force + * and when the simulation’s nodes change via simulation.nodes. + * + * A force may perform necessary work during initialization, such as evaluating per-node parameters, to avoid repeatedly performing work during each application of the force. + */ + initialize(nodes: NodeDatum[], random: () => number): void; + + /** + * Returns the current strength accessor, which defaults to a constant strength for all nodes of 0.1. + */ + strength(): (d: NodeDatum, i: number, data: NodeDatum[]) => number; + /** + * Sets the strength accessor to the specified number or function, re-evaluates the strength accessor for each node, and returns this force. + * The strength determines how much to increment the node’s x-velocity: (x - node.x) × strength. + * For example, a value of 0.1 indicates that the node should move a tenth of the way from its current x-position to the target x-position with each application. + * Higher values moves nodes more quickly to the target position, often at the expense of other forces or constraints. + * A value outside the range [0,1] is not recommended. + * The strength accessor is invoked for each node in the simulation, being passed the node and its zero-based index. + * The resulting number is then stored internally, such that the strength of each node is only recomputed when the + * force is initialized or when this method is called with a new strength, and not on every application of the force. + */ + strength(strength: number | ((d: NodeDatum, i: number, data: NodeDatum[]) => number)): this; + + /** + * Return the current x-accessor, which defaults to a function returning 0 for all nodes. + */ + x(): (d: NodeDatum, i: number, data: NodeDatum[]) => number; + /** + * Sets the x-coordinate accessor to the specified number or function, re-evaluates the x-accessor for each node, and returns this force. + * The x-accessor is invoked for each node in the simulation, being passed the node and its zero-based index. + * The resulting number is then stored internally, such that the target x-coordinate of each node is only recomputed + * when the force is initialized or when this method is called with a new x, and not on every application of the force. + */ + x(x: number | ((d: NodeDatum, i: number, data: NodeDatum[]) => number)): this; +} + +/** + * Creates a new positioning force along the x-axis towards the given position x. + * If x is not specified, it defaults to 0. + */ +export function forceX( + x?: number | ((d: NodeDatum, i: number, data: NodeDatum[]) => number), +): ForceX; + +/** + * The y-positioning force pushes nodes towards a desired position along the given dimension with a configurable strength. + * The strength of the force is proportional to the one-dimensional distance between the node’s position and the target position. + * While this force can be used to position individual nodes, it is intended primarily for global forces that apply to all (or most) nodes. + * + * The generic refers to the type of data for a node. + */ +export interface ForceY extends Force { + /** + * Supplies the array of nodes and random source to this force. This method is called when a force is bound to a simulation via simulation.force + * and when the simulation’s nodes change via simulation.nodes. + * + * A force may perform necessary work during initialization, such as evaluating per-node parameters, to avoid repeatedly performing work during each application of the force. + */ + initialize(nodes: NodeDatum[], random: () => number): void; + + /** + * Returns the current strength accessor, which defaults to a constant strength for all nodes of 0.1. + */ + strength(): (d: NodeDatum, i: number, data: NodeDatum[]) => number; + /** + * Sets the strength accessor to the specified number or function, re-evaluates the strength accessor for each node, and returns this force. + * The strength determines how much to increment the node’s y-velocity: (y - node.y) × strength. + * For example, a value of 0.1 indicates that the node should move a tenth of the way from its current y-position to the target y-position with each application. + * Higher values moves nodes more quickly to the target position, often at the expense of other forces or constraints. + * A value outside the range [0,1] is not recommended. + * The strength accessor is invoked for each node in the simulation, being passed the node and its zero-based index. + * The resulting number is then stored internally, such that the strength of each node is only recomputed when the + * force is initialized or when this method is called with a new strength, and not on every application of the force. + */ + strength(strength: number | ((d: NodeDatum, i: number, data: NodeDatum[]) => number)): this; + + /** + * Return the current y-accessor, which defaults to a function returning 0 for all nodes. + */ + y(): (d: NodeDatum, i: number, data: NodeDatum[]) => number; + /** + * Sets the y-coordinate accessor to the specified number or function, re-evaluates the y-accessor for each node, and returns this force. + * The y-accessor is invoked for each node in the simulation, being passed the node and its zero-based index. + * The resulting number is then stored internally, such that the target y-coordinate of each node is only recomputed + * when the force is initialized or when this method is called with a new y, and not on every application of the force. + */ + y(y: number | ((d: NodeDatum, i: number, data: NodeDatum[]) => number)): this; +} + +/** + * Creates a new positioning force along the y-axis towards the given position y. + * If y is not specified, it defaults to 0. + */ +export function forceY( + y?: number | ((d: NodeDatum, i: number, data: NodeDatum[]) => number), +): ForceY; + +/** + * The radial force is similar to the x- and y-positioning forces, except it pushes nodes towards the closest point on a given circle. + * The circle is of the specified radius centered at ⟨x,y⟩. If x and y are not specified, they default to ⟨0,0⟩. + * The strength of the force is proportional to the one-dimensional distance between the node’s position and the target position. + * While this force can be used to position individual nodes, it is intended primarily for global forces that apply to all (or most) nodes. + * + * The generic refers to the type of data for a node. + */ +export interface ForceRadial extends Force { + /** + * Assigns the array of nodes and random source to this force. This method is called when a force is bound to a simulation via simulation.force + * and when the simulation’s nodes change via simulation.nodes. + * + * A force may perform necessary work during initialization, such as evaluating per-node parameters, to avoid repeatedly performing work during each application of the force. + */ + initialize(nodes: NodeDatum[], random: () => number): void; + + /** + * Returns the current strength accessor, which defaults to a constant strength for all nodes of 0.1. + */ + strength(): (d: NodeDatum, i: number, data: NodeDatum[]) => number; + /** + * Sets the strength accessor to the specified number or function, re-evaluates the strength accessor for each node, and returns this force. + * The strength determines how much to increment the node’s x- and y-velocity. + * For example, a value of 0.1 indicates that the node should move a tenth of the way from its current position to the closest point on the circle with each application. + * Higher values moves nodes more quickly to the target position, often at the expense of other forces or constraints. + * A value outside the range [0,1] is not recommended. + * The strength accessor is invoked for each node in the simulation, being passed the node and its zero-based index. + * The resulting number is then stored internally, such that the strength of each node is only recomputed when the + * force is initialized or when this method is called with a new strength, and not on every application of the force. + */ + strength(strength: number | ((d: NodeDatum, i: number, data: NodeDatum[]) => number)): this; + + /** + * Return the current radius accessor for the circle. + */ + radius(): (d: NodeDatum, i: number, data: NodeDatum[]) => number; + /** + * Sets the circle radius to the specified number or function, re-evaluates the radius accessor for each node, and returns this force. + * The radius accessor is invoked for each node in the simulation, being passed the node and its zero-based index. + * The resulting number is then stored internally, such that the target radius of each node is only recomputed when + * the force is initialized or when this method is called with a new radius, and not on every application of the force. + */ + radius(radius: number | ((d: NodeDatum, i: number, data: NodeDatum[]) => number)): this; + + /** + * Return the current x-accessor for the circle center, which defaults to a function returning 0 for all nodes. + */ + x(): (d: NodeDatum, i: number, data: NodeDatum[]) => number; + /** + * Sets the x-coordinate of the circle center to the specified number and returns this force. + */ + x(x: number | ((d: NodeDatum, i: number, data: NodeDatum[]) => number)): this; + + /** + * Return the current y-accessor for the circle center, which defaults to a function returning 0 for all nodes. + */ + y(): (d: NodeDatum, i: number, data: NodeDatum[]) => number; + /** + * Sets the y-coordinate of the circle center to the specified number and returns this force. + */ + y(y: number | ((d: NodeDatum, i: number, data: NodeDatum[]) => number)): this; +} + +/** + * Create a new radial positioning force towards a circle of the specified radius centered at ⟨x,y⟩. + * If x and y are not specified, they default to ⟨0,0⟩. + * + * The strength of the force is proportional to the one-dimensional distance between the node’s position and the target position. + * While this force can be used to position individual nodes, it is intended primarily for global forces that apply to all (or most) nodes. + * + * The generic refers to the type of data for a node. + */ +export function forceRadial( + radius: number | ((d: NodeDatum, i: number, data: NodeDatum[]) => number), + x?: number | ((d: NodeDatum, i: number, data: NodeDatum[]) => number), + y?: number | ((d: NodeDatum, i: number, data: NodeDatum[]) => number), +): ForceRadial; diff --git a/tools/ui/node_modules/@types/d3-force/package.json b/tools/ui/node_modules/@types/d3-force/package.json new file mode 100644 index 0000000000000000000000000000000000000000..92f25a62d7c630162d3533c5035aa12ab2ba8c27 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-force/package.json @@ -0,0 +1,45 @@ +{ + "name": "@types/d3-force", + "version": "3.0.10", + "description": "TypeScript definitions for d3-force", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-force", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-force" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "e5ee2e6a5e2d4ebb09e2aa2fe683219329b79c33bbd2f7f62e314bf2bcad5083", + "typeScriptVersion": "4.7" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-format/LICENSE b/tools/ui/node_modules/@types/d3-format/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-format/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-format/README.md b/tools/ui/node_modules/@types/d3-format/README.md new file mode 100644 index 0000000000000000000000000000000000000000..02056ecf919637a1d60c22352345a6f2774f9d55 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-format/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-format` + +# Summary +This package contains type definitions for d3-format (https://github.com/d3/d3-format/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-format. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:36 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [denisname](https://github.com/denisname), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-format/index.d.ts b/tools/ui/node_modules/@types/d3-format/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..43e34d29f13135e1a00ea14dc452ccf1a7865d73 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-format/index.d.ts @@ -0,0 +1,337 @@ +// Last module patch version validated against: 3.0.1 + +/** + * Specification of locale to use when creating a new FormatLocaleObject + */ +export interface FormatLocaleDefinition { + /** + * The decimal point (e.g., ".") + */ + decimal: string; + /** + * The group separator (e.g., ","). Note that the thousands property is a misnomer, as + * the grouping definition allows groups other than thousands. + */ + thousands: string; + /** + * The array of group sizes (e.g., [3]), cycled as needed. + */ + grouping: number[]; + /** + * The currency prefix and suffix (e.g., ["$", ""]). + */ + currency: [string, string]; + /** + * An optional array of ten strings to replace the numerals 0-9. + */ + numerals?: string[] | undefined; + /** + * An optional symbol to replace the `percent` suffix; the percent suffix (defaults to "%"). + */ + percent?: string | undefined; + /** + * Optional; the minus sign (defaults to "−"). + */ + minus?: string | undefined; + /** + * Optional; the not-a-number value (defaults "NaN"). + */ + nan?: string | undefined; +} + +/** + * A Format Locale Object + */ +export interface FormatLocaleObject { + /** + * Returns a new format function for the given string specifier. The returned function + * takes a number as the only argument, and returns a string representing the formatted number. + * + * @param specifier A Specifier string. + * @throws Error on invalid format specifier. + */ + format(specifier: string): (n: number | { valueOf(): number }) => string; + + /** + * Returns a new format function for the given string specifier. The returned function + * takes a number as the only argument, and returns a string representing the formatted number. + * The returned function will convert values to the units of the appropriate SI prefix for the + * specified numeric reference value before formatting in fixed point notation. + * + * @param specifier A Specifier string. + * @param value The reference value to determine the appropriate SI prefix. + * @throws Error on invalid format specifier. + */ + formatPrefix(specifier: string, value: number): (n: number | { valueOf(): number }) => string; +} + +/** + * A Format Specifier + * + * For details see: {@link https://github.com/d3/d3-format#locale_format} + */ +export interface FormatSpecifierObject { + /** + * fill can be any character. The presence of a fill character is signaled by the align character following it. + */ + fill?: string | undefined; + /** + * Alignment used for format, as set by choosing one of the following: + * + * '>' - Forces the field to be right-aligned within the available space. (Default behavior). + * '<' - Forces the field to be left-aligned within the available space. + * '^' - Forces the field to be centered within the available space. + * '=' - Like '>', but with any sign and symbol to the left of any padding. + */ + align?: string | undefined; + /** + * The sign can be: + * + * '-' - nothing for positive and a minus sign for negative. (Default behavior.) + * '+' - a plus sign for positive and a minus sign for negative. + * '(' - nothing for positive and parentheses for negative. + * ' ' (space) - a space for positive and a minus sign for negative. + */ + sign?: string | undefined; + /** + * The symbol can be: + * + * '$' - apply currency symbols per the locale definition. + * '#' - for binary, octal, or hexadecimal notation, prefix by 0b, 0o, or 0x, respectively. + * '' (none) - no symbol. (Default behavior.) + */ + symbol?: string | undefined; + /** + * The zero (0) option enables zero-padding; this implicitly sets fill to 0 and align to =. + */ + zero?: string | undefined; + /** + * The width defines the minimum field width; + * if not specified, then the width will be determined by the content. + */ + width?: string | undefined; + /** + * The comma (,) option enables the use of a group separator, such as a comma for thousands. + */ + comma?: string | undefined; + /** + * Depending on the type, the precision either indicates the number of digits that follow the decimal point (types 'f' and '%'), + * or the number of significant digits (types '' (none), 'e', 'g', 'r', 's' and 'p'). If the precision is not specified, + * it defaults to 6 for all types except '' (none), which defaults to 12. + * Precision is ignored for integer formats (types 'b', 'o', 'd', 'x', 'X' and 'c'). + * + * See precisionFixed and precisionRound for help picking an appropriate precision. + */ + precision?: string | undefined; + /** + * The '~' option trims insignificant trailing zeros across all format types. + * This is most commonly used in conjunction with types 'r', 'e', 's' and '%'. + */ + trim?: string | undefined; + /** + * The available type values are: + * + * 'e' - exponent notation. + * 'f' - fixed point notation. + * 'g' - either decimal or exponent notation, rounded to significant digits. + * 'r' - decimal notation, rounded to significant digits. + * 's' - decimal notation with an SI prefix, rounded to significant digits. + * '%' - multiply by 100, and then decimal notation with a percent sign. + * 'p' - multiply by 100, round to significant digits, and then decimal notation with a percent sign. + * 'b' - binary notation, rounded to integer. + * 'o' - octal notation, rounded to integer. + * 'd' - decimal notation, rounded to integer. + * 'x' - hexadecimal notation, using lower-case letters, rounded to integer. + * 'X' - hexadecimal notation, using upper-case letters, rounded to integer. + * 'c' - converts the integer to the corresponding unicode character before printing. + * + * The type '' (none) is also supported as shorthand for '~g' (with a default precision of 12 instead of 6), and + * the type 'n' is shorthand for ',g'. For the 'g', 'n' and '' (none) types, + * decimal notation is used if the resulting string would have precision or fewer digits; otherwise, exponent notation is used. + */ + type?: string | undefined; +} + +/** + * Create a new locale-based object which exposes format(...) and formatPrefix(...) + * methods for the specified locale. + * + * @param locale A Format locale definition. + */ +export function formatLocale(locale: FormatLocaleDefinition): FormatLocaleObject; + +/** + * Create a new locale-based object which exposes format(...) and formatPrefix(...) + * methods for the specified locale definition. The specified locale definition will be + * set as the new default locale definition. + * + * @param defaultLocale A Format locale definition to be used as default. + */ +export function formatDefaultLocale(defaultLocale: FormatLocaleDefinition): FormatLocaleObject; + +/** + * Returns a new format function for the given string specifier. The returned function + * takes a number as the only argument, and returns a string representing the formatted number. + * + * Uses the current default locale. + * + * The general form of a specifier is [[fill]align][sign][symbol][0][width][,][.precision][~][type]. + * For reference, an explanation of the segments of the specifier string, refer to the FormatSpecifier interface properties. + * + * @param specifier A Specifier string. + * @throws Error on invalid format specifier. + */ +export function format(specifier: string): (n: number | { valueOf(): number }) => string; + +/** + * Returns a new format function for the given string specifier. The returned function + * takes a number as the only argument, and returns a string representing the formatted number. + * The returned function will convert values to the units of the appropriate SI prefix for the + * specified numeric reference value before formatting in fixed point notation. + * + * Uses the current default locale. + * + * The general form of a specifier is [[fill]align][sign][symbol][0][width][,][.precision][~][type]. + * For reference, an explanation of the segments of the specifier string, refer to the FormatSpecifier interface properties. + * + * @param specifier A Specifier string. + * @param value The reference value to determine the appropriate SI prefix. + * @throws Error on invalid format specifier. + */ +export function formatPrefix(specifier: string, value: number): (n: number | { valueOf(): number }) => string; + +/** + * A Format Specifier + * + * For details see: {@link https://github.com/d3/d3-format#locale_format} + */ +export class FormatSpecifier { + /** + * Given the specified specifier object, returning an object with exposed fields that correspond to the format specification mini-language and a toString method that reconstructs the specifier. + * @param specifier A specifier object. + */ + constructor(specifier: FormatSpecifierObject); + /** + * fill can be any character. The presence of a fill character is signaled by the align character following it. + */ + fill: string; + /** + * Alignment used for format, as set by choosing one of the following: + * + * '>' - Forces the field to be right-aligned within the available space. (Default behavior). + * '<' - Forces the field to be left-aligned within the available space. + * '^' - Forces the field to be centered within the available space. + * '=' - Like '>', but with any sign and symbol to the left of any padding. + */ + align: ">" | "<" | "^" | "="; + /** + * The sign can be: + * + * '-' - nothing for positive and a minus sign for negative. (Default behavior.) + * '+' - a plus sign for positive and a minus sign for negative. + * '(' - nothing for positive and parentheses for negative. + * ' ' (space) - a space for positive and a minus sign for negative. + */ + sign: "-" | "+" | "(" | " "; + /** + * The symbol can be: + * + * '$' - apply currency symbols per the locale definition. + * '#' - for binary, octal, or hexadecimal notation, prefix by 0b, 0o, or 0x, respectively. + * '' (none) - no symbol. (Default behavior.) + */ + symbol: "$" | "#" | ""; + /** + * The zero (0) option enables zero-padding; this implicitly sets fill to 0 and align to =. + */ + zero: boolean; + /** + * The width defines the minimum field width; + * if not specified, then the width will be determined by the content. + */ + width: number | undefined; + /** + * The comma (,) option enables the use of a group separator, such as a comma for thousands. + */ + comma: boolean; + /** + * Depending on the type, the precision either indicates the number of digits that follow the decimal point (types 'f' and '%'), + * or the number of significant digits (types '' (none), 'e', 'g', 'r', 's' and 'p'). If the precision is not specified, + * it defaults to 6 for all types except '' (none), which defaults to 12. + * Precision is ignored for integer formats (types 'b', 'o', 'd', 'x', 'X' and 'c'). + * + * See precisionFixed and precisionRound for help picking an appropriate precision. + */ + precision: number | undefined; + /** + * The '~' option trims insignificant trailing zeros across all format types. + * This is most commonly used in conjunction with types 'r', 'e', 's' and '%'. + */ + trim: boolean; + /** + * The available type values are: + * + * 'e' - exponent notation. + * 'f' - fixed point notation. + * 'g' - either decimal or exponent notation, rounded to significant digits. + * 'r' - decimal notation, rounded to significant digits. + * 's' - decimal notation with an SI prefix, rounded to significant digits. + * '%' - multiply by 100, and then decimal notation with a percent sign. + * 'p' - multiply by 100, round to significant digits, and then decimal notation with a percent sign. + * 'b' - binary notation, rounded to integer. + * 'o' - octal notation, rounded to integer. + * 'd' - decimal notation, rounded to integer. + * 'x' - hexadecimal notation, using lower-case letters, rounded to integer. + * 'X' - hexadecimal notation, using upper-case letters, rounded to integer. + * 'c' - converts the integer to the corresponding unicode character before printing. + * + * The type '' (none) is also supported as shorthand for '~g' (with a default precision of 12 instead of 6), and + * the type 'n' is shorthand for ',g'. For the 'g', 'n' and '' (none) types, + * decimal notation is used if the resulting string would have precision or fewer digits; otherwise, exponent notation is used. + */ + type: "e" | "f" | "g" | "r" | "s" | "%" | "p" | "b" | "o" | "d" | "x" | "X" | "c" | "" | "n"; + /** + * Return the object as a specifier string. + */ + toString(): string; +} + +/** + * Parses the specified specifier, returning an object with exposed fields that correspond to the + * format specification mini-language and a toString method that reconstructs the specifier. + * + * The general form of a specifier is [[fill]align][sign][symbol][0][width][,][.precision][~][type]. + * For reference, an explanation of the segments of the specifier string, refer to the FormatSpecifier interface properties. + * + * @param specifier A specifier string. + * @throws Error on invalid format specifier. + */ +export function formatSpecifier(specifier: string): FormatSpecifier; + +/** + * Returns a suggested decimal precision for fixed point notation given the specified numeric step value. + * + * @param step The step represents the minimum absolute difference between values that will be formatted. + * (This assumes that the values to be formatted are also multiples of step.) + */ +export function precisionFixed(step: number): number; + +/** + * Returns a suggested decimal precision for use with locale.formatPrefix given the specified + * numeric step and reference value. + * + * @param step The step represents the minimum absolute difference between values that will be formatted. + * (This assumes that the values to be formatted are also multiples of step.) + * @param value Reference value determines which SI prefix will be used. + */ +export function precisionPrefix(step: number, value: number): number; + +/** + * Returns a suggested decimal precision for format types that round to significant digits + * given the specified numeric step and max values. + * + * @param step The step represents the minimum absolute difference between values that will be formatted. + * (This assumes that the values to be formatted are also multiples of step.) + * @param max max represents the largest absolute value that will be formatted. + */ +export function precisionRound(step: number, max: number): number; diff --git a/tools/ui/node_modules/@types/d3-format/package.json b/tools/ui/node_modules/@types/d3-format/package.json new file mode 100644 index 0000000000000000000000000000000000000000..32bf7dc367038816428ad9c6aceb8195c95b7bbd --- /dev/null +++ b/tools/ui/node_modules/@types/d3-format/package.json @@ -0,0 +1,45 @@ +{ + "name": "@types/d3-format", + "version": "3.0.4", + "description": "TypeScript definitions for d3-format", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-format", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-format" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "0b15b96385739bcaef7d24730c61c78f55050d5d6613af26addf38d757a997c4", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-geo/LICENSE b/tools/ui/node_modules/@types/d3-geo/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-geo/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-geo/README.md b/tools/ui/node_modules/@types/d3-geo/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c95dd2c910ab83501dfe4db655a12d177e77db22 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-geo/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-geo` + +# Summary +This package contains type definitions for d3-geo (https://github.com/d3/d3-geo/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-geo. + +### Additional Details + * Last updated: Sun, 12 Nov 2023 19:07:04 GMT + * Dependencies: [@types/geojson](https://npmjs.com/package/@types/geojson) + +# Credits +These definitions were written by [Hugues Stefanski](https://github.com/ledragon), [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-geo/index.d.ts b/tools/ui/node_modules/@types/d3-geo/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c92af5fa1aaeb1612faa433f7b3380885b8fd429 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-geo/index.d.ts @@ -0,0 +1,1371 @@ +// Last module patch version validated against: 3.0.1 + +import * as GeoJSON from "geojson"; + +// ---------------------------------------------------------------------- +// Shared Interfaces and Types +// ---------------------------------------------------------------------- + +/** + * A basic geometry for a sphere, which is supported by d3-geo + * beyond the GeoJSON geometries. + */ +export interface GeoSphere { + /** + * Sphere geometry type + */ + type: "Sphere"; +} + +/** + * Type Alias for GeoJSON Geometry Object and GeoSphere additional + * geometry supported by d3-geo + */ +export type GeoGeometryObjects = GeoJSON.GeometryObject | GeoSphere; + +/** + * A GeoJSON-style GeometryCollection which supports GeoJSON geometry objects + * and additionally GeoSphere. + * + * The generic refers to the type(s) of d3-geo geometry objects contained in the collection. + */ +export interface ExtendedGeometryCollection { + type: string; + bbox?: number[] | undefined; + crs?: { + type: string; + properties: any; + } | undefined; + geometries: GeometryType[]; +} + +/** + * A GeoJSON-style Feature which support features built on GeoJSON GeometryObjects + * or GeoSphere. + * + * The first generic refers to the type(s) of d3-geo geometry objects underlying the ExtendedFeature. + * Unless explicitly ruled out, the geometry value is nullable. + * + * The second generic refers to the data type of the properties of the ExtendedFeature. Unless explicitly ruled out, + * the properties value is nullable. + */ +export interface ExtendedFeature< + GeometryType extends GeoGeometryObjects | null = GeoGeometryObjects | null, + Properties extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties, +> extends GeoJSON.GeoJsonObject { + geometry: GeometryType; + properties: Properties; + id?: string | number | undefined; +} + +/** + * A GeoJSON-style FeatureCollection which supports GeoJSON features + * and features built on GeoSphere + * + * The generic refers to the type of ExtendedFeature contained in the ExtendedFeatureCollection. + */ +export interface ExtendedFeatureCollection + extends GeoJSON.GeoJsonObject +{ + features: FeatureType[]; +} + +/** + * Type Alias for permissible objects which can be used with d3-geo + * methods + */ +export type GeoPermissibleObjects = + | GeoGeometryObjects + | ExtendedGeometryCollection + | ExtendedFeature + | ExtendedFeatureCollection; + +// ---------------------------------------------------------------------- +// Spherical Math +// ---------------------------------------------------------------------- + +/** + * Returns the spherical area of the specified GeoJSON object in steradians. + * This is the spherical equivalent of path.area. + */ +export function geoArea( + object: ExtendedFeature | ExtendedFeatureCollection | GeoGeometryObjects | ExtendedGeometryCollection, +): number; + +/** + * Returns the spherical bounding box for the specified GeoJSON object. + * The bounding box is represented by a two-dimensional array: [[left, bottom], [right, top]], + * where left is the minimum longitude, bottom is the minimum latitude, right is maximum longitude, and top is the maximum latitude. + * All coordinates are given in degrees. + * (Note that in projected planar coordinates, the minimum latitude is typically the maximum y-value, and the maximum latitude is typically the minimum y-value.) + * This is the spherical equivalent of path.bounds. + */ +export function geoBounds( + object: ExtendedFeature | ExtendedFeatureCollection | GeoGeometryObjects | ExtendedGeometryCollection, +): [[number, number], [number, number]]; + +/** + * Returns the spherical centroid of the specified GeoJSON object. + * This is the spherical equivalent of path.centroid. + */ +export function geoCentroid( + object: ExtendedFeature | ExtendedFeatureCollection | GeoGeometryObjects | ExtendedGeometryCollection, +): [number, number]; + +/** + * Returns true if and only if the specified GeoJSON object contains the specified point, or false if the object does not contain the point. + * The point must be specified as a two-element array [longitude, latitude] in degrees. + * For Point and MultiPoint geometries, an exact test is used; for a Sphere, true is always returned; for other geometries, an epsilon threshold is applied. + */ +export function geoContains( + object: ExtendedFeature | ExtendedFeatureCollection | GeoGeometryObjects | ExtendedGeometryCollection, + point: [number, number], +): boolean; + +/** + * Returns the great-arc distance in radians between the two points a and b. + * Each point must be specified as a two-element array [longitude, latitude] in degrees. + * + * @param a Point specified as a two-element array [longitude, latitude] in degrees. + * @param b Point specified as a two-element array [longitude, latitude] in degrees. + */ +export function geoDistance(a: [number, number], b: [number, number]): number; + +/** + * Returns the great-arc length of the specified GeoJSON object in radians. + * For polygons, returns the perimeter of the exterior ring plus that of any interior rings. + * This is the spherical equivalent of path.measure. + */ +export function geoLength( + object: ExtendedFeature | ExtendedFeatureCollection | GeoGeometryObjects | ExtendedGeometryCollection, +): number; + +/** + * Returns an interpolator function given two points a and b. + * Each point must be specified as a two-element array [longitude, latitude] in degrees. + * + * @param a Point specified as a two-element array [longitude, latitude] in degrees. + * @param b Point specified as a two-element array [longitude, latitude] in degrees. + */ +export function geoInterpolate(a: [number, number], b: [number, number]): (t: number) => [number, number]; + +/** + * A Geo Rotation + */ +export interface GeoRotation { + /** + * Returns a new array [longitude, latitude] in degrees representing the rotated point of the given point. + * + * @param point The point must be specified as a two-element array [longitude, latitude] in degrees. + */ + (point: [number, number]): [number, number]; + + /** + * Returns a new array [longitude, latitude] in degrees representing the point of the given rotated point; the inverse of rotation. + * + * @param point The rotated point must be specified as a two-element array [longitude, latitude] in degrees. + */ + invert(point: [number, number]): [number, number]; +} + +/** + * Returns a rotation function for the given angles. + * + * @param angles A two- or three-element array of numbers [lambda, phi, gamma] specifying the rotation angles in degrees about each spherical axis. + * (These correspond to yaw, pitch and roll.) If the rotation angle gamma is omitted, it defaults to 0. + */ +export function geoRotation(angles: [number, number] | [number, number, number]): GeoRotation; + +// ---------------------------------------------------------------------- +// Spherical Shapes +// ---------------------------------------------------------------------- + +// geoCircle ============================================================ + +/** + * A new circle generator + * + * The first generic corresponds to the "this"-context within which the geo circle generator will be invoked. + * + * The second generic corresponds to the type of the Datum which will be passed into the geo circle generator. + */ +export interface GeoCircleGenerator { + /** + * Returns a new GeoJSON geometry object of type “Polygon” approximating a circle on the surface of a sphere, + * with the current center, radius and precision. Any arguments are passed to the accessors. + */ + (this: This, d?: Datum, ...args: any[]): GeoJSON.Polygon; + + /** + * Returns the current center accessor, which defaults to a function returning [0, 0]. + */ + center(): (this: This, d: Datum, ...args: any[]) => [number, number]; + /** + * Sets the circle center to the specified point [longitude, latitude] in degrees, and returns this circle generator. + * The center may also be specified as a function; this function will be invoked whenever a circle is generated, being passed any arguments passed to the circle generator. + */ + center(center: [number, number] | ((this: This, d: Datum, ...args: any[]) => [number, number])): this; + + /** + * Returns the current radius accessor, which defaults to a function returning 90. + */ + radius(): (this: This, d: Datum, ...args: any[]) => number; + /** + * Sets the circle radius to the specified angle in degrees, and returns this circle generator. + * The radius may also be specified as a function; this function will be invoked whenever a circle is generated, being passed any arguments passed to the circle generator. + */ + radius(radius: number | ((this: This, d: Datum, ...args: any[]) => number)): this; + + /** + * Returns the current precision accessor, which defaults to a function returning 6. + */ + precision(): (this: This, d: Datum, ...args: any[]) => number; + /** + * Sets the circle precision to the specified angle in degrees, and returns this circle generator. + * The precision may also be specified as a function; this function will be invoked whenever a circle is generated, being passed any arguments passed to the circle generator. + */ + precision(precision: number | ((this: This, d: Datum, ...args: any[]) => number)): this; +} + +/** + * Returns a new geo circle generator + */ +export function geoCircle(): GeoCircleGenerator; +/** + * Returns a new geo circle generator + * + * The generic corresponds to the data type of the first argument passed into the geo circle generator and its accessor functions. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function geoCircle(): GeoCircleGenerator; +/** + * Returns a new geo circle generator + * + * The first generic corresponds to the "this" context within which the geo circle generator and its accessors will be invoked. + * + * The second generic corresponds to the data type of the first argument passed into the geo circle generator and its accessor functions. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function geoCircle(): GeoCircleGenerator; + +// geoGraticule ============================================================ + +/** + * A Feature generator for graticules: a uniform grid of meridians and parallels for showing projection distortion. + * The default graticule has meridians and parallels every 10° between ±80° latitude; for the polar regions, there are meridians every 90°. + */ +export interface GeoGraticuleGenerator { + /** + * Returns a GeoJSON MultiLineString geometry object representing all meridians and parallels for this graticule. + */ + (): GeoJSON.MultiLineString; + + /** + * Returns an array of GeoJSON LineString geometry objects, one for each meridian or parallel for this graticule. + */ + lines(): GeoJSON.LineString[]; + + /** + * Returns a GeoJSON Polygon geometry object representing the outline of this graticule, i.e. along the meridians and parallels defining its extent. + */ + outline(): GeoJSON.Polygon; + + /** + * Returns the current minor extent, which defaults to ⟨⟨-180°, -80° - ε⟩, ⟨180°, 80° + ε⟩⟩. + */ + extent(): [[number, number], [number, number]]; + /** + * Sets the major and minor extents of this graticule. + * + * @param extent Extent to use for major and minor extent of graticule. + */ + extent(extent: [[number, number], [number, number]]): this; + + /** + * Returns the current major extent, which defaults to ⟨⟨-180°, -90° + ε⟩, ⟨180°, 90° - ε⟩⟩. + */ + extentMajor(): [[number, number], [number, number]]; + /** + * Sets the major extent of this graticule. + * + * @param extent Major extent of graticule. + */ + extentMajor(extent: [[number, number], [number, number]]): this; + + /** + * Returns the current minor extent, which defaults to ⟨⟨-180°, -80° - ε⟩, ⟨180°, 80° + ε⟩⟩. + */ + extentMinor(): [[number, number], [number, number]]; + /** + * Sets the minor extent of this graticule. + * + * @param extent Minor extent of graticule. + */ + extentMinor(extent: [[number, number], [number, number]]): this; + + /** + * Returns the current minor step, which defaults to ⟨10°, 10°⟩. + */ + step(): [number, number]; + /** + * Sets the major and minor step for this graticule + * + * @param step Major and minor step to use for this graticule. + */ + step(step: [number, number]): this; + + /** + * Returns the current major step, which defaults to ⟨90°, 360°⟩. + */ + stepMajor(): [number, number]; + /** + * Sets the major step for this graticule. + * + * @param step Major step. + */ + stepMajor(step: [number, number]): this; + + /** + * Returns the current major step, which defaults to ⟨10°, 10°⟩. + */ + stepMinor(): [number, number]; + /** + * Sets the minor step for this graticule. + * + * @param step Minor step. + */ + stepMinor(step: [number, number]): this; + + /** + * Returns the current precision, which defaults to 2.5°. + */ + precision(): number; + /** + * Sets the precision for this graticule, in degrees. + * + * @param angle Precision in degrees. + */ + precision(angle: number): this; +} + +/** + * Constructs a feature generator for creating graticules: a uniform grid of meridians and parallels for showing projection distortion. + * The default graticule has meridians and parallels every 10° between ±80° latitude; for the polar regions, there are meridians every 90°. + */ +export function geoGraticule(): GeoGraticuleGenerator; + +/** + * A convenience method for directly generating the default 10° global graticule as a GeoJSON MultiLineString geometry object. + */ +export function geoGraticule10(): GeoJSON.MultiLineString; + +// ---------------------------------------------------------------------- +// Projections +// ---------------------------------------------------------------------- + +/** + * A D3 geo stream. D3 transforms geometry using a sequence of function calls, rather than materializing intermediate representations, to minimize overhead. + * Streams must implement several methods to receive input geometry. Streams are inherently stateful; the meaning of a point depends on whether the point is inside of a line, + * and likewise a line is distinguished from a ring by a polygon. Despite the name “stream”, these method calls are currently synchronous. + */ +export interface GeoStream { + /** + * Indicates the end of a line or ring. Within a polygon, indicates the end of a ring. + * Unlike GeoJSON, the redundant closing coordinate of a ring is not indicated via point, and instead is implied via lineEnd within a polygon. + */ + lineEnd(): void; + + /** + * Indicates the start of a line or ring. Within a polygon, indicates the start of a ring. The first ring of a polygon is the exterior ring, and is typically clockwise. + * Any subsequent rings indicate holes in the polygon, and are typically counterclockwise. + */ + lineStart(): void; + + /** + * Indicates a point with the specified coordinates x and y (and optionally z). The coordinate system is unspecified and implementation-dependent; + * for example, projection streams require spherical coordinates in degrees as input. Outside the context of a polygon or line, + * a point indicates a point geometry object (Point or MultiPoint). Within a line or polygon ring, the point indicates a control point. + * + * @param x x-coordinate of point. + * @param y y-coordinate of point. + * @param z Optional z-coordinate of point. + */ + point(x: number, y: number, z?: number): void; + + /** + * Indicates the end of a polygon. + */ + polygonEnd(): void; + + /** + * Indicates the start of a polygon. The first line of a polygon indicates the exterior ring, and any subsequent lines indicate interior holes. + */ + polygonStart(): void; + + /** + * Indicates the sphere (the globe; the unit sphere centered at ⟨0,0,0⟩). + */ + sphere?(): void; +} + +// geoStream(...) ======================================================= + +/** + * Streams the specified GeoJSON object to the specified projection stream. + * While both features and geometry objects are supported as input, the stream interface only describes the geometry, and thus additional feature properties are not visible to streams. + */ +export function geoStream( + object: ExtendedFeature | ExtendedFeatureCollection | GeoGeometryObjects | ExtendedGeometryCollection, + stream: GeoStream, +): void; + +// ---------------------------------------------------------------------- +// Projections +// ---------------------------------------------------------------------- + +/** + * Raw projections are point transformation functions that are used to implement custom projections; they typically passed to d3.geoProjection or d3.geoProjectionMutator. + * They are exposed here to facilitate the derivation of related projections. + * Raw projections take spherical coordinates [lambda, phi] in radians (not degrees!) and return a point [x, y], typically in the unit square centered around the origin. + */ +export interface GeoRawProjection { + /** + * Projects the specified point [lambda, phi] in radians, returning a new point [x, y] in unitless coordinates. + * @param lambda Spherical lambda coordinate in radians. + * @param phi Spherical phi coordinate in radians. + */ + (lambda: number, phi: number): [number, number]; + + /** + * Inverts the projected point [x, y] in unitless coordinates, returning an unprojected point in spherical coordinates [lambda, phi] in radians. + * @param x x-coordinate (unitless). + * @param y y-coordinate (unitless). + */ + invert?(x: number, y: number): [number, number]; +} + +/** + * An object implementing a stream method + */ +export interface GeoStreamWrapper { + /** + * Returns a projection stream for the specified output stream. Any input geometry is projected before being streamed to the output stream. + * A typical projection involves several geometry transformations: the input geometry is first converted to radians, rotated on three axes, + * clipped to the small circle or cut along the antimeridian, and lastly projected to the plane with adaptive resampling, scale and translation. + * + * @param stream An input stream + */ + stream(stream: GeoStream): GeoStream; +} + +/** + * A Geographic Projection to transform spherical polygonal geometry to planar polygonal geometry. + * D3 provides implementations of several classes of standard projections: + * + * - Azimuthal + * - Composite + * - Conic + * - Cylindrical + * + * For many more projections, see d3-geo-projection. You can implement custom projections using d3.geoProjection or d3.geoProjectionMutator. + */ +export interface GeoProjection extends GeoStreamWrapper { + /** + * Returns a new array [x, y] (typically in pixels) representing the projected point of the given point. + * The point must be specified as a two-element array [longitude, latitude] in degrees. + * May return null if the specified point has no defined projected position, such as when the point is outside the clipping bounds of the projection. + * + * @param point A point specified as a two-dimensional array [longitude, latitude] in degrees. + */ + (point: [number, number]): [number, number] | null; + + /** + * Returns a new array [longitude, latitude] in degrees representing the unprojected point of the given projected point. + * May return null if the specified point has no defined projected position, such as when the point is outside the clipping bounds of the projection. + * + * @param point The projected point, specified as a two-element array [x, y] (typically in pixels). + */ + invert?(point: [number, number]): [number, number] | null; + + /** + * Returns the current spherical clipping function. + * Pre-clipping occurs in geographic coordinates. Cutting along the antimeridian line, + * or clipping along a small circle are the most common strategies. + */ + preclip(): (stream: GeoStream) => GeoStream; + /** + * Sets the projection’s spherical clipping to the specified function and returns the projection. + * Pre-clipping occurs in geographic coordinates. Cutting along the antimeridian line, or clipping along a small circle are the most common strategies. + * + * @param preclip A spherical clipping function. Clipping functions are implemented as transformations of a projection stream. + * Pre-clipping operates on spherical coordinates, in radians. + */ + preclip(preclip: (stream: GeoStream) => GeoStream): this; + + /** + * Returns the current cartesian clipping function. + * Post-clipping occurs on the plane, when a projection is bounded to a certain extent such as a rectangle. + */ + postclip(): (stream: GeoStream) => GeoStream; + /** + * Sets the projection’s cartesian clipping to the specified function and returns the projection. + * + * @param postclip A cartesian clipping function. Clipping functions are implemented as transformations of a projection stream. + * Post-clipping operates on planar coordinates, in pixels. + */ + postclip(postclip: (stream: GeoStream) => GeoStream): this; + + /** + * Returns the current clip angle which defaults to null. + * + * null switches to antimeridian cutting rather than small-circle clipping. + */ + clipAngle(): number | null; + /** + * Sets the projection’s clipping circle radius to the specified angle in degrees and returns the projection. + * If angle is null, switches to antimeridian cutting rather than small-circle clipping. + */ + clipAngle(angle: null | number): this; + + /** + * Returns the current viewport clip extent which defaults to null. + */ + clipExtent(): [[number, number], [number, number]] | null; + /** + * Sets the projection’s viewport clip extent to the specified bounds in pixels and returns the projection. + * The extent bounds are specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left-side of the viewport, y₀ is the top, x₁ is the right and y₁ is the bottom. + * If extent is null, no viewport clipping is performed. + */ + clipExtent(extent: null | [[number, number], [number, number]]): this; + + /** + * Returns the current scale factor; the default scale is projection-specific. + * + * The scale factor corresponds linearly to the distance between projected points; however, absolute scale factors are not equivalent across projections. + */ + scale(): number; + /** + * Sets the projection’s scale factor to the specified value and returns the projection. + * The scale factor corresponds linearly to the distance between projected points; however, absolute scale factors are not equivalent across projections. + * + * @param scale Scale factor to be used for the projection; the default scale is projection-specific. + */ + scale(scale: number): this; + + /** + * Returns the current translation offset which defaults to [480, 250] and places ⟨0°,0°⟩ at the center of a 960×500 area. + * The translation offset determines the pixel coordinates of the projection’s center. + */ + translate(): [number, number]; + /** + * Sets the projection’s translation offset to the specified two-element array [tx, ty] and returns the projection. + * The translation offset determines the pixel coordinates of the projection’s center. The default translation offset places ⟨0°,0°⟩ at the center of a 960×500 area. + * + * @param point A two-element array [tx, ty] specifying the translation offset. The default translation offset of defaults to [480, 250] places ⟨0°,0°⟩ at the center of a 960×500 area. + */ + translate(point: [number, number]): this; + + /** + * Returns the current center of the projection, which defaults to ⟨0°,0°⟩. + */ + center(): [number, number]; + /** + * Sets the projection’s center to the specified center, + * a two-element array of longitude and latitude in degrees and returns the projection. + * The default is ⟨0°,0°⟩. + * + * @param point A point specified as a two-dimensional array [longitude, latitude] in degrees. + */ + center(point: [number, number]): this; + + /** + * Returns the projection’s current angle, which defaults to 0°. + */ + angle(): number; + /** + * Sets the projection’s post-projection planar rotation angle to the specified angle in degrees and returns the projection. + * @param angle The new rotation angle of the projection. + */ + angle(angle: number): this; + + /** + * Returns true if x-reflection is enabled, which defaults to false. + */ + reflectX(): boolean; + /** + * Sets whether or not the x-dimension is reflected (negated) in the output. + * @param reflect Whether or not the x-dimension is reflected (negated) in the output. + */ + reflectX(reflect: boolean): this; + + /** + * Returns true if y-reflection is enabled, which defaults to false. + */ + reflectY(): boolean; + /** + * Sets whether or not the y-dimension is reflected (negated) in the output. + * @param reflect Whether or not the y-dimension is reflected (negated) in the output. + */ + reflectY(reflect: boolean): this; + + /** + * Returns the current rotation [lambda, phi, gamma] specifying the rotation angles in degrees about each spherical axis. + * (These correspond to yaw, pitch and roll.) which defaults [0, 0, 0]. + */ + rotate(): [number, number, number]; + + /** + * Sets the projection’s three-axis rotation to the specified angles, which must be a two- or three-element array of numbers. + * + * @param angles A two- or three-element array of numbers [lambda, phi, gamma] specifying the rotation angles in degrees about each spherical axis. + * (These correspond to yaw, pitch and roll.) If the rotation angle gamma is omitted, it defaults to 0. + */ + rotate(angles: [number, number] | [number, number, number]): this; + + /** + * Returns the projection’s current resampling precision which defaults to square root of 0.5. + * This value corresponds to the Douglas–Peucker distance. + */ + precision(): number; + /** + * Sets the threshold for the projection’s adaptive resampling to the specified value in pixels and returns the projection. + * This value corresponds to the Douglas–Peucker distance. + * + * @param precision A numeric value in pixels to use as the threshold for the projection’s adaptive resampling. + */ + precision(precision: number): this; + + /** + * Sets the projection’s scale and translate to fit the specified GeoJSON object in the center of the given extent. + * The extent is specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. + * Returns the projection. + */ + fitExtent( + extent: [[number, number], [number, number]], + object: ExtendedFeature | ExtendedFeatureCollection | GeoGeometryObjects | ExtendedGeometryCollection, + ): this; + + /** + * A convenience method for projection.fitExtent where the top-left corner of the extent is [0, 0]. + */ + fitSize( + size: [number, number], + object: ExtendedFeature | ExtendedFeatureCollection | GeoGeometryObjects | ExtendedGeometryCollection, + ): this; + + /** + * A convenience method for projection.fitSize where the height is automatically chosen from the aspect ratio of object and the given constraint on width. + */ + fitWidth( + width: number, + object: ExtendedFeature | ExtendedFeatureCollection | GeoGeometryObjects | ExtendedGeometryCollection, + ): this; + + /** + * A convenience method for projection.fitSize where the width is automatically chosen from the aspect ratio of object and the given constraint on height. + */ + fitHeight( + height: number, + object: ExtendedFeature | ExtendedFeatureCollection | GeoGeometryObjects | ExtendedGeometryCollection, + ): this; +} + +/** + * A Conic Projection + */ +export interface GeoConicProjection extends GeoProjection { + /** + * Return the standard parallels for the conic projection in degrees. + */ + parallels(): [number, number]; + /** + * Set the standard parallels for the conic projection in degrees and return the projection. + * + * @param value A two-dimensional array representing the standard parallels in degrees. + */ + parallels(value: [number, number]): this; +} + +// geoPath ============================================================== + +/** + * A minimal rendering context for a GeoPath generator. The minimum implemented + * methods are a subset of the CanvasRenderingContext2D API. + * + * For reference to the CanvasRenderingContext2D see https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D + */ +export interface GeoContext { + /** + * Adds an arc to the path with center point (x, y) and radius r starting at startAngle and ending at endAngle. + * The arc is drawn in clockwise direction by default. + * + * @param x x-coordinate of arc center point. + * @param y y-coordinate of arc center point. + * @param radius Radius of arc. + * @param startAngle The starting angle of the arc, measured clockwise from the positive x axis and expressed in radians. + * @param endAngle The end angle of the arc, measured clockwise from the positive x axis and expressed in radians. + * @param anticlockwise Optional boolean flag, if true the arc is drawn counter-clockwise between the two angles. + */ + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + + /** + * Start a new path by emptying the list of sub-paths. + */ + beginPath(): void; + + /** + * Causes the point of the pen to move back to the start of the current sub-path. + * It tries to draw a straight line from the current point to the start. + * If the shape has already been closed or has only one point, this function does nothing. + */ + closePath(): void; + + /** + * Connects the last point in the sub-path to the x, y coordinates with a straight line (but does not actually draw it). + * + * @param x The x-coordinate for the end of the line. + * @param y The y-coordinate for the end of the line. + */ + lineTo(x: number, y: number): void; + + /** + * Move the starting point of a new sub-path to the (x, y) coordinates. + * + * @param x The x-coordinate for the new starting point. + * @param y The y-coordinate for the new starting point. + */ + moveTo(x: number, y: number): void; +} + +/** + * A Geo Path generator + * + * The first generic corresponds to the "this"-context within which the geo path generator will be invoked. + * This could be e.g. the DOMElement bound to "this" when using selection.attr("d", ...) with the path generator. + * + * The second generic corresponds to the type of the DatumObject which will be passed into the geo path generator for rendering. + */ +export interface GeoPath { + /** + * Renders the given object, which may be any GeoJSON feature or geometry object: + * + * + Point - a single position. + * + MultiPoint - an array of positions. + * + LineString - an array of positions forming a continuous line. + * + MultiLineString - an array of arrays of positions forming several lines. + * + Polygon - an array of arrays of positions forming a polygon (possibly with holes). + * + MultiPolygon - a multidimensional array of positions forming multiple polygons. + * + GeometryCollection - an array of geometry objects. + * + Feature - a feature containing one of the above geometry objects. + * + FeatureCollection - an array of feature objects. + * + * The type Sphere is also supported, which is useful for rendering the outline of the globe; a sphere has no coordinates. + * + * Any additional arguments are passed along to the pointRadius accessor. + * + * IMPORTANT: If the rendering context of the geoPath generator is null, + * then the geoPath is returned as an SVG path data string. + * + * Separate path elements are typically slower than a single path element. However, distinct path elements are useful for styling and interaction (e.g., click or mouseover). + * Canvas rendering (see path.context) is typically faster than SVG, but requires more effort to implement styling and interaction. + * + * The first generic type of the GeoPath generator used, must correspond to the "this" context bound to the function upon invocation. + * + * @param object An object to be rendered. + */ + (this: This, object: DatumObject, ...args: any[]): string | null; + /** + * Renders the given object, which may be any GeoJSON feature or geometry object: + * + * + Point - a single position. + * + MultiPoint - an array of positions. + * + LineString - an array of positions forming a continuous line. + * + MultiLineString - an array of arrays of positions forming several lines. + * + Polygon - an array of arrays of positions forming a polygon (possibly with holes). + * + MultiPolygon - a multidimensional array of positions forming multiple polygons. + * + GeometryCollection - an array of geometry objects. + * + Feature - a feature containing one of the above geometry objects. + * + FeatureCollection - an array of feature objects. + * + * The type Sphere is also supported, which is useful for rendering the outline of the globe; a sphere has no coordinates. + * + * Any additional arguments are passed along to the pointRadius accessor. + * + * IMPORTANT: If the geoPath generator has been configured with a rendering context, + * then the geoPath is rendered to this context as a sequence of path method calls and this function returns void. + * + * Separate path elements are typically slower than a single path element. However, distinct path elements are useful for styling and interaction (e.g., click or mouseover). + * Canvas rendering (see path.context) is typically faster than SVG, but requires more effort to implement styling and interaction. + * + * The first generic type of the GeoPath generator used, must correspond to the "this" context bound to the function upon invocation. + * + * @param object An object to be rendered. + */ + (this: This, object: DatumObject, ...args: any[]): void; + + /** + * Returns the projected planar area (typically in square pixels) for the specified GeoJSON object. + * Point, MultiPoint, LineString and MultiLineString geometries have zero area. For Polygon and MultiPolygon geometries, + * this method first computes the area of the exterior ring, and then subtracts the area of any interior holes. + * This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent. This is the planar equivalent of d3.geoArea. + * + * @param object An object for which the area is to be calculated. + */ + area(object: DatumObject): number; + + /** + * Returns the projected planar bounding box (typically in pixels) for the specified GeoJSON object. + * The bounding box is represented by a two-dimensional array: [[x₀, y₀], [x₁, y₁]], where x₀ is the minimum x-coordinate, y₀ is the minimum y-coordinate, + * x₁ is maximum x-coordinate, and y₁ is the maximum y-coordinate. + * + * This is handy for, say, zooming in to a particular feature. (Note that in projected planar coordinates, + * the minimum latitude is typically the maximum y-value, and the maximum latitude is typically the minimum y-value.) + * This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent. This is the planar equivalent of d3.geoBounds. + * + * @param object An object for which the bounds are to be calculated. + */ + bounds(object: DatumObject): [[number, number], [number, number]]; + + /** + * Returns the projected planar centroid (typically in pixels) for the specified GeoJSON object. + * This is handy for, say, labeling state or county boundaries, or displaying a symbol map. + * For example, a noncontiguous cartogram might scale each state around its centroid. + * This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent. This is the planar equivalent of d3.geoCentroid. + * + * @param object An object for which the centroid is to be calculated. + */ + centroid(object: DatumObject): [number, number]; + + /** + * Returns the projected planar length (typically in pixels) for the specified GeoJSON object. + * Point and MultiPoint geometries have zero length. For Polygon and MultiPolygon geometries, this method computes the summed length of all rings. + * + * This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent. This is the planar equivalent of d3.geoLength. + * + * @param object An object for which the measure is to be calculated. + */ + measure(object: DatumObject): number; + + /** + * Returns the current render context which defaults to null. + * + * Use the generic to cast the return type of the rendering context, if it is known for a specific application. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + context(): C; + + /** + * sets the current render context and returns the path generator. + * If the context is null, then the path generator will return an SVG path string; + * if the context is non-null, the path generator will instead call methods on the specified context to render geometry. + */ + context(context: null | GeoContext): this; + + /** + * Get the current projection. The generic parameter can be used to cast the result to the + * correct, known type of the projection, e.g. GeoProjection or GeoConicProjection. Otherwise, + * the return type defaults to the minimum type requirement for a projection which + * can be passed into a GeoPath. + * + * Use the generic to cast the return type of the projection, if it is known for a specific application. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + projection

(): P; + + /** + * Sets the current projection to the specified projection. + * The null projection represents the identity transformation: the input geometry is not projected and is instead rendered directly in raw coordinates. + * This can be useful for fast rendering of pre-projected geometry, or for fast rendering of the equirectangular projection. + */ + projection(projection: null | GeoProjection | GeoStreamWrapper): this; + + /** + * Returns the current radius or radius accessor used to determine the radius for the display of Point and MultiPoint geometries. + * The default is a constant radius of 4.5. + */ + pointRadius(): ((this: This, object: DatumObject, ...args: any[]) => number) | number; + + /** + * Sets the radius used to display Point and MultiPoint geometries to the specified number. + * While the radius is commonly specified as a number constant, it may also be specified as a function which is computed per feature, being passed the any arguments passed to the path generator. + * For example, if your GeoJSON data has additional properties, you might access those properties inside the radius function to vary the point size; + * alternatively, you could d3.symbol and a projection for greater flexibility. + */ + pointRadius(value: number | ((this: This, object: DatumObject, ...args: any[]) => number)): this; + + /** + * Returns the current number of digits, which defaults to 3. + */ + digits(): number; + /** + * Sets the number of fractional digits for coordinates generated in SVG path strings. + * @param digits New amount of digits + */ + digits(digits: number): this; +} + +/** + * Creates a new geographic path generator. + * + * The default projection is the null projection. The null projection represents the identity transformation, i.e. + * the input geometry is not projected and is instead rendered directly in raw coordinates. + * This can be useful for fast rendering of pre-projected geometry, or for fast rendering of the equirectangular projection. + * + * The default context is null, which implies that the path generator will return an SVG path string. + * + * @param projection An (optional) current projection to be used. Typically this is one of D3’s built-in geographic projections; + * however, any object that exposes a projection.stream function can be used, enabling the use of custom projections. + * See D3’s transforms for more examples of arbitrary geometric transformations. Setting the projection to "null" uses the identity projection. The default value is "null", the identity projection. + * @param context An (optional) rendering context to be used. If a context is provided, it must at least implement the interface described by GeoContext, a subset of the CanvasRenderingContext2D API. + * Setting the context to "null" means that the path generator will return an SVG path string representing the to be rendered object. The default is "null". + */ +export function geoPath(projection?: GeoProjection | GeoStreamWrapper | null, context?: GeoContext | null): GeoPath; +/** + * Creates a new geographic path generator with the default settings. + * + * The default projection is the null projection. The null projection represents the identity transformation: + * the input geometry is not projected and is instead rendered directly in raw coordinates. + * This can be useful for fast rendering of pre-projected geometry, or for fast rendering of the equirectangular projection. + * + * The default context is null, which implies that the path generator will return an SVG path string. + * + * The generic corresponds to the type of the DatumObject which will be passed into the geo path generator for rendering + * + * @param projection An (optional) current projection to be used. Typically this is one of D3’s built-in geographic projections; + * however, any object that exposes a projection.stream function can be used, enabling the use of custom projections. + * See D3’s transforms for more examples of arbitrary geometric transformations. Setting the projection to "null" uses the identity projection. The default value is "null", the identity projection. + * @param context An (optional) rendering context to be used. If a context is provided, it must at least implement the interface described by GeoContext, a subset of the CanvasRenderingContext2D API. + * Setting the context to "null" means that the path generator will return an SVG path string representing the to be rendered object. The default is "null". + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function geoPath( + projection?: GeoProjection | GeoStreamWrapper | null, + context?: GeoContext | null, +): GeoPath; +/** + * Creates a new geographic path generator with the default settings. + * + * The default projection is the null projection. The null projection represents the identity transformation: + * the input geometry is not projected and is instead rendered directly in raw coordinates. + * This can be useful for fast rendering of pre-projected geometry, or for fast rendering of the equirectangular projection. + * + * The default context is null, which implies that the path generator will return an SVG path string. + * + * The first generic corresponds to the "this"-context within which the geo path generator will be invoked. + * This could be e.g. the DOMElement bound to "this" when using selection.attr("d", ...) with the path generator. + * + * The second generic corresponds to the type of the DatumObject which will be passed into the geo path generator for rendering. + * + * @param projection An (optional) current projection to be used. Typically this is one of D3’s built-in geographic projections; + * however, any object that exposes a projection.stream function can be used, enabling the use of custom projections. + * See D3’s transforms for more examples of arbitrary geometric transformations. Setting the projection to "null" uses the identity projection. The default value is "null", the identity projection. + * @param context An (optional) rendering context to be used. If a context is provided, it must at least implement the interface described by GeoContext, a subset of the CanvasRenderingContext2D API. + * Setting the context to "null" means that the path generator will return an SVG path string representing the to be rendered object. The default is "null". + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function geoPath( + projection?: GeoProjection | GeoStreamWrapper | null, + context?: GeoContext | null, +): GeoPath; + +// geoProjection ========================================================== + +/** + * Constructs a new projection from the specified raw projection, project. + * The project function takes the longitude and latitude of a given point in radians, + * often referred to as lambda (λ) and phi (φ), and returns a two-element array [x, y] representing its unit projection. + * The project function does not need to scale or translate the point, as these are applied automatically by projection.scale, projection.translate, and projection.center. + * Likewise, the project function does not need to perform any spherical rotation, as projection.rotate is applied prior to projection. + * + * If the project function exposes an invert method, the returned projection will also expose projection.invert. + */ +export function geoProjection(project: GeoRawProjection): GeoProjection; + +// geoProjectionMutator ==================================================== + +/** + * Constructs a new projection from the specified raw projection factory and returns a mutate function to call whenever the raw projection changes. + * The factory must return a raw projection. The returned mutate function returns the wrapped projection. + * + * When creating a mutable projection, the mutate function is typically not exposed. + */ +export function geoProjectionMutator(factory: (...args: any[]) => GeoRawProjection): () => GeoProjection; + +// Pre-Defined Projections and Raw Projections ============================= + +// Azimuthal Projections --------------------------------------------------- + +/** + * The azimuthal equal-area projection. + */ +export function geoAzimuthalEqualArea(): GeoProjection; + +/** + * The raw azimuthal equal-area projection. + */ +export function geoAzimuthalEqualAreaRaw(): GeoRawProjection; + +/** + * The azimuthal equidistant projection. + */ +export function geoAzimuthalEquidistant(): GeoProjection; +/** + * The raw azimuthal equidistant projection. + */ +export function geoAzimuthalEquidistantRaw(): GeoRawProjection; + +/** + * The gnomonic projection. + */ +export function geoGnomonic(): GeoProjection; + +/** + * The raw gnomonic projection. + */ +export function geoGnomonicRaw(): GeoRawProjection; + +/** + * The orthographic projection. + */ +export function geoOrthographic(): GeoProjection; + +/** + * The raw orthographic projection. + */ +export function geoOrthographicRaw(): GeoRawProjection; + +/** + * The stereographic projection. + */ +export function geoStereographic(): GeoProjection; + +/** + * The raw stereographic projection. + */ +export function geoStereographicRaw(): GeoRawProjection; + +/** + * The Equal Eartch projection, by Bojan Šavrič et al., 2018. + */ +export function geoEqualEarth(): GeoProjection; + +/** + * The raw Equal Earth projection, by Bojan Šavrič et al., 2018. + */ +export function geoEqualEarthRaw(): GeoRawProjection; + +// Composite Projections --------------------------------------------------- + +/** + * A U.S.-centric composite projection of three d3.geoConicEqualArea projections: d3.geoAlbers is used for the lower forty-eight states, + * and separate conic equal-area projections are used for Alaska and Hawaii. Note that the scale for Alaska is diminished: it is projected at 0.35× its true relative area. + * + * Composite consist of several projections that are composed into a single display. The constituent projections have fixed clip, center and rotation, + * and thus composite projections do not support projection.center, projection.rotate, projection.clipAngle, or projection.clipExtent. + */ +export function geoAlbersUsa(): GeoProjection; + +// Conic Projections ------------------------------------------------------- + +/** + * The Albers’ equal area-conic projection. This is a U.S.-centric configuration of d3.geoConicEqualArea. + */ +export function geoAlbers(): GeoConicProjection; + +/** + * The conic conformal projection. The parallels default to [30°, 30°] resulting in flat top. + */ +export function geoConicConformal(): GeoConicProjection; + +/** + * The raw conic conformal projection. + */ +export function geoConicConformalRaw(phi0: number, phi1: number): GeoRawProjection; + +/** + * The Albers’ equal-area conic projection. + */ +export function geoConicEqualArea(): GeoConicProjection; + +/** + * The raw Albers’ equal-area conic projection. + */ +export function geoConicEqualAreaRaw(phi0: number, phi1: number): GeoRawProjection; + +/** + * The conic equidistant projection. + */ +export function geoConicEquidistant(): GeoConicProjection; + +/** + * The raw conic equidistant projection. + */ +export function geoConicEquidistantRaw(phi0: number, phi1: number): GeoRawProjection; + +// Cylindrical Projections ------------------------------------------------ + +/** + * The equirectangular (plate carrée) projection. + */ +export function geoEquirectangular(): GeoProjection; + +/** + * The raw equirectangular (plate carrée) projection. + */ +export function geoEquirectangularRaw(): GeoRawProjection; + +/** + * The spherical Mercator projection. + * Defines a default projection.clipExtent such that the world is projected to a square, clipped to approximately ±85° latitude. + */ +export function geoMercator(): GeoProjection; +/** + * The raw spherical Mercator projection. + */ +export function geoMercatorRaw(): GeoRawProjection; + +/** + * The transverse spherical Mercator projection. + * Defines a default projection.clipExtent such that the world is projected to a square, clipped to approximately ±85° latitude. + */ +export function geoTransverseMercator(): GeoProjection; + +/** + * The raw transverse spherical Mercator projection. + */ +export function geoTransverseMercatorRaw(): GeoRawProjection; + +/** + * The Natural Earth projection is a pseudocylindrical projection designed by Tom Patterson. It is neither conformal nor equal-area, but appealing to the eye for small-scale maps of the whole world. + */ +export function geoNaturalEarth1(): GeoProjection; + +/** + * The raw pseudo-cylindircal Natural Earth projection. + */ +export function geoNaturalEarth1Raw(): GeoRawProjection; + +// ---------------------------------------------------------------------- +// Projection Transforms +// ---------------------------------------------------------------------- + +// geoTransform(...) ==================================================== + +/** + * A Prototype interface which serves as a template for the implementation of a geometric transform using geoTransform(...) + * It serves as a reference for the custom methods which can be passed into geoTransform as argument to crete a generalized + * transform projection. + */ +export interface GeoTransformPrototype { + /** + * Indicates the end of a line or ring. Within a polygon, indicates the end of a ring. + * Unlike GeoJSON, the redundant closing coordinate of a ring is not indicated via point, and instead is implied via lineEnd within a polygon. + */ + lineEnd?(this: this & { stream: GeoStream }): void; + /** + * Indicates the start of a line or ring. Within a polygon, indicates the start of a ring. The first ring of a polygon is the exterior ring, and is typically clockwise. + * Any subsequent rings indicate holes in the polygon, and are typically counterclockwise. + */ + lineStart?(this: this & { stream: GeoStream }): void; + /** + * Indicates a point with the specified coordinates x and y (and optionally z). The coordinate system is unspecified and implementation-dependent; + * for example, projection streams require spherical coordinates in degrees as input. Outside the context of a polygon or line, + * a point indicates a point geometry object (Point or MultiPoint). Within a line or polygon ring, the point indicates a control point. + * + * @param x x-coordinate of point. + * @param y y-coordinate of point. + * @param z Optional z-coordinate of point. + */ + point?(this: this & { stream: GeoStream }, x: number, y: number, z?: number): void; + /** + * Indicates the end of a polygon. + */ + polygonEnd?(this: this & { stream: GeoStream }): void; + /** + * Indicates the start of a polygon. The first line of a polygon indicates the exterior ring, and any subsequent lines indicate interior holes. + */ + polygonStart?(this: this & { stream: GeoStream }): void; + /** + * Indicates the sphere (the globe; the unit sphere centered at ⟨0,0,0⟩). + */ + sphere?(this: this & { stream: GeoStream }): void; +} + +// TODO: Review whether GeoStreamWrapper should be included into return value union type, i.e. ({ stream: (s: GeoStream) => (T & GeoStream & GeoStreamWrapper)})? +// It probably should be omitted for purposes of this API. The stream method added to (T & GeoStream) is more of a private member used internally to +// implement the Transform factory + +/** + * Defines an arbitrary transform using the methods defined on the specified methods object. + * Any undefined methods will use pass-through methods that propagate inputs to the output stream. + * + * @param methods An object with custom method implementations, which are used to create a transform projection. + */ +export function geoTransform(methods: T): { stream(s: GeoStream): T & GeoStream }; + +// geoIdentity() ================================================================= + +/** + * @deprecated Misspelled name. Use GeoIdentityTransform. + */ +export type GeoIdentityTranform = GeoIdentityTransform; + +/** + * Geo Identity Transform + */ +export interface GeoIdentityTransform extends GeoStreamWrapper { + /** + * Returns a new array [x, y] (typically in pixels) representing the projected point of the given point. + * The point must be specified as a two-element array [longitude, latitude] in degrees. + * May return null if the specified point has no defined projected position, such as when the point is outside the clipping bounds of the projection. + * + * @param point A point specified as a two-dimensional array [longitude, latitude] in degrees. + */ + (point: [number, number]): [number, number] | null; + + /** + * Returns a new array [longitude, latitude] in degrees representing the unprojected point of the given projected point. + * May return null if the specified point has no defined projected position, such as when the point is outside the clipping bounds of the projection. + * + * @param point The projected point, specified as a two-element array [x, y] (typically in pixels). + */ + invert(point: [number, number]): [number, number] | null; + + /** + * Returns the current cartesian clipping function. + * Post-clipping occurs on the plane, when a projection is bounded to a certain extent such as a rectangle. + */ + postclip(): (stream: GeoStream) => GeoStream; + /** + * Sets the projection’s cartesian clipping to the specified function and returns the projection. + * + * @param postclip A cartesian clipping function. Clipping functions are implemented as transformations of a projection stream. + * Post-clipping operates on planar coordinates, in pixels. + */ + postclip(postclip: (stream: GeoStream) => GeoStream): this; + + /** + * Returns the current scale factor. + * + * The scale factor corresponds linearly to the distance between projected points; however, absolute scale factors are not equivalent across projections. + */ + scale(): number; + /** + * Sets the projection’s scale factor to the specified value and returns the projection. + * The scale factor corresponds linearly to the distance between projected points; however, absolute scale factors are not equivalent across projections. + * + * @param scale Scale factor to be used for the projection. + */ + scale(scale: number): this; + + /** + * Returns the current translation offset. + * The translation offset determines the pixel coordinates of the projection’s center. + */ + translate(): [number, number]; + /** + * Sets the projection’s translation offset to the specified two-element array [tx, ty] and returns the projection. + * The translation offset determines the pixel coordinates of the projection’s center. + * + * @param point A two-element array [tx, ty] specifying the translation offset. + */ + translate(point: [number, number]): this; + + /** + * Returns the projection’s current angle, which defaults to 0°. + */ + angle(): number; + /** + * Sets the projection’s post-projection planar rotation angle to the specified angle in degrees and returns the projection. + * @param angle The new rotation angle of the projection. + */ + angle(angle: number): this; + + /** + * Sets the projection’s scale and translate to fit the specified GeoJSON object in the center of the given extent. + * The extent is specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. Returns the projection. + */ + fitExtent( + extent: [[number, number], [number, number]], + object: ExtendedFeature | ExtendedFeatureCollection | GeoGeometryObjects | ExtendedGeometryCollection, + ): this; + + /** + * A convenience method for projection.fitExtent where the top-left corner of the extent is [0, 0]. + */ + fitSize( + size: [number, number], + object: ExtendedFeature | ExtendedFeatureCollection | GeoGeometryObjects | ExtendedGeometryCollection, + ): this; + + /** + * Returns the current viewport clip extent which defaults to null. + */ + clipExtent(): [[number, number], [number, number]] | null; + /** + * Sets the projection’s viewport clip extent to the specified bounds in pixels and returns the projection. + * The extent bounds are specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left-side of the viewport, y₀ is the top, x₁ is the right and y₁ is the bottom. + * If extent is null, no viewport clipping is performed. + */ + clipExtent(extent: null | [[number, number], [number, number]]): this; + + /** + * Returns true if x-reflection is enabled, which defaults to false. + */ + reflectX(): boolean; + /** + * Sets whether or not the x-dimension is reflected (negated) in the output. + * + * @param reflect true = reflect x-dimension, false = do not reflect x-dimension. + */ + reflectX(reflect: boolean): this; + + /** + * Returns true if y-reflection is enabled, which defaults to false. + */ + reflectY(): boolean; + /** + * Sets whether or not the y-dimension is reflected (negated) in the output. + * + * This is especially useful for transforming from standard spatial reference systems, + * which treat positive y as pointing up, to display coordinate systems such as Canvas and SVG, + * which treat positive y as pointing down. + * + * @param reflect true = reflect y-dimension, false = do not reflect y-dimension. + */ + reflectY(reflect: boolean): this; +} + +/** + * Returns the identity transform which can be used to scale, translate and clip planar geometry. + */ +export function geoIdentity(): GeoIdentityTransform; + +// ---------------------------------------------------------------------- +// Clipping Functions +// ---------------------------------------------------------------------- + +/** + * A clipping function transforming a stream such that geometries (lines or polygons) that cross the antimeridian line are cut in two, one on each side. + * Typically used for pre-clipping. + */ +export function geoClipAntimeridian(stream: GeoStream): GeoStream; + +/** + * Generates a clipping function transforming a stream such that geometries are bounded by a small circle of radius angle around the projection’s center. + * Typically used for pre-clipping. + * + * @param angle A clipping angle. + */ +export function geoClipCircle(angle: number): (stream: GeoStream) => GeoStream; + +/** + * Generates a clipping function transforming a stream such that geometries are bounded by a rectangle of coordinates [[x0, y0], [x1, y1]]. + * Typically used for post-clipping. + * + * @param x0 x0 coordinate. + * @param y0 y0 coordinate. + * @param x1 x1 coordinate. + * @param y1 y1 coordinate. + */ +export function geoClipRectangle(x0: number, y0: number, x1: number, y1: number): (stream: GeoStream) => GeoStream; diff --git a/tools/ui/node_modules/@types/d3-geo/package.json b/tools/ui/node_modules/@types/d3-geo/package.json new file mode 100644 index 0000000000000000000000000000000000000000..583badb62e508d5771182a778d5b592935877122 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-geo/package.json @@ -0,0 +1,47 @@ +{ + "name": "@types/d3-geo", + "version": "3.1.0", + "description": "TypeScript definitions for d3-geo", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-geo", + "license": "MIT", + "contributors": [ + { + "name": "Hugues Stefanski", + "githubUsername": "ledragon", + "url": "https://github.com/ledragon" + }, + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-geo" + }, + "scripts": {}, + "dependencies": { + "@types/geojson": "*" + }, + "typesPublisherContentHash": "4d55e51247e0d5b1a39b6f087c57085a6ebca17b764aab81b7f1d2087dadb39a", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-hierarchy/LICENSE b/tools/ui/node_modules/@types/d3-hierarchy/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-hierarchy/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-hierarchy/README.md b/tools/ui/node_modules/@types/d3-hierarchy/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0b6094fffe8e9488ffb3a922da5d4667fab8f0f7 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-hierarchy/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-hierarchy` + +# Summary +This package contains type definitions for d3-hierarchy (https://github.com/d3/d3-hierarchy/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-hierarchy. + +### Additional Details + * Last updated: Mon, 18 Mar 2024 18:36:06 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [denisname](https://github.com/denisname), [Nathan Bierema](https://github.com/Methuselah96), and [Fil](https://github.com/Fil). diff --git a/tools/ui/node_modules/@types/d3-hierarchy/index.d.ts b/tools/ui/node_modules/@types/d3-hierarchy/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3de051bbc9cbe8d98d79e34e91646b6ee266befd --- /dev/null +++ b/tools/ui/node_modules/@types/d3-hierarchy/index.d.ts @@ -0,0 +1,928 @@ +// Last module patch version validated against: 3.1.2 + +// ----------------------------------------------------------------------- +// Hierarchy +// ----------------------------------------------------------------------- + +export interface HierarchyLink { + /** + * The source of the link. + */ + source: HierarchyNode; + + /** + * The target of the link. + */ + target: HierarchyNode; +} + +export interface HierarchyNode { + new(data: Datum): this; + + /** + * The associated data, as specified to the constructor. + */ + data: Datum; + + /** + * Zero for the root node, and increasing by one for each descendant generation. + */ + readonly depth: number; + + /** + * Zero for leaf nodes, and the greatest distance from any descendant leaf for internal nodes. + */ + readonly height: number; + + /** + * The parent node, or null for the root node. + */ + parent: this | null; + + /** + * An array of child nodes, if any; undefined for leaf nodes. + */ + children?: this[] | undefined; + + /** + * Aggregated numeric value as calculated by `sum(value)` or `count()`, if previously invoked. + */ + readonly value?: number | undefined; + + /** + * Optional node id string set by `StratifyOperator`, if hierarchical data was created from tabular data using stratify(). + */ + readonly id?: string | undefined; + + /** + * The x position of this node. Set after a tree has been laid out by `tree` or `cluster`. + * + * ``` + * const root = d3.hierarchy(datum); + * const treeLayout = d3.tree(); + * treeLayout(root); + * // x and y are now set on root and its descendants + * ``` + */ + x?: number | undefined; + + /** + * The y position of this node. Set after a tree has been laid out by `tree` or `cluster`. + * + * ``` + * const root = d3.hierarchy(datum); + * const treeLayout = d3.tree(); + * treeLayout(root); + * // x and y are now set on root and its descendants + * ``` + */ + y?: number | undefined; + + /** + * Returns the array of ancestors nodes, starting with this node, then followed by each parent up to the root. + */ + ancestors(): this[]; + + /** + * Returns the array of descendant nodes, starting with this node, then followed by each child in topological order. + */ + descendants(): this[]; + + /** + * Returns the array of leaf nodes in traversal order; leaves are nodes with no children. + */ + leaves(): this[]; + + /** + * Returns the first node in the hierarchy from this node for which the specified filter returns a truthy value. undefined if no such node is found. + * @param filter Filter. + */ + find(filter: (node: this) => boolean): this | undefined; + + /** + * Returns the shortest path through the hierarchy from this node to the specified target node. + * The path starts at this node, ascends to the least common ancestor of this node and the target node, and then descends to the target node. + * + * @param target The target node. + */ + path(target: this): this[]; + + /** + * Returns an array of links for this node, where each link is an object that defines source and target properties. + * The source of each link is the parent node, and the target is a child node. + */ + links(): Array>; + + /** + * Evaluates the specified value function for this node and each descendant in post-order traversal, and returns this node. + * The `node.value` property of each node is set to the numeric value returned by the specified function plus the combined value of all descendants. + * + * @param value The value function is passed the node’s data, and must return a non-negative number. + */ + sum(value: (d: Datum) => number): this; + + /** + * Computes the number of leaves under this node and assigns it to `node.value`, and similarly for every descendant of node. + * If this node is a leaf, its count is one. Returns this node. + */ + count(): this; + + /** + * Sorts the children of this node, if any, and each of this node’s descendants’ children, + * in pre-order traversal using the specified compare function, and returns this node. + * + * @param compare The compare function is passed two nodes a and b to compare. + * If a should be before b, the function must return a value less than zero; + * if b should be before a, the function must return a value greater than zero; + * otherwise, the relative order of a and b are not specified. See `array.sort` for more. + */ + sort(compare: (a: this, b: this) => number): this; + + /** + * Returns an iterator over the node’s descendants in breadth-first order. + */ + [Symbol.iterator](): Iterator; + + /** + * Invokes the specified function for node and each descendant in breadth-first order, + * such that a given node is only visited if all nodes of lesser depth have already been visited, + * as well as all preceding nodes of the same depth. + * + * @param func The specified function is passed the current descendant, the zero-based traversal index, and this node. + * @param that If that is specified, it is the this context of the callback. + */ + each(func: (this: T, node: this, index: number, thisNode: this) => void, that?: T): this; + + /** + * Invokes the specified function for node and each descendant in post-order traversal, + * such that a given node is only visited after all of its descendants have already been visited. + * + * @param func The specified function is passed the current descendant, the zero-based traversal index, and this node. + * @param that If that is specified, it is the this context of the callback. + */ + eachAfter(func: (this: T, node: this, index: number, thisNode: this) => void, that?: T): this; + + /** + * Invokes the specified function for node and each descendant in pre-order traversal, + * such that a given node is only visited after all of its ancestors have already been visited. + * + * @param func The specified function is passed the current descendant, the zero-based traversal index, and this node. + * @param that If that is specified, it is the this context of the callback. + */ + eachBefore(func: (this: T, node: this, index: number, thisNode: this) => void, that?: T): this; + + /** + * Return a deep copy of the subtree starting at this node. The returned deep copy shares the same data, however. + * The returned node is the root of a new tree; the returned node’s parent is always null and its depth is always zero. + */ + copy(): this; +} + +/** + * Constructs a root node from the specified hierarchical data. + * + * @param data The root specified data. + * If *data* is a Map, it is implicitly converted to the entry [undefined, *data*], + * and the children accessor instead defaults to `(d) => Array.isArray(d) ? d[1] : null;`. + * @param children The specified children accessor function is invoked for each datum, starting with the root data, + * and must return an iterable of data representing the children, if any. + * If children is not specified, it defaults to: `(d) => d.children`. + */ +export function hierarchy( + data: Datum, + children?: (d: Datum) => Iterable | null | undefined, +): HierarchyNode; + +// ----------------------------------------------------------------------- +// Stratify +// ----------------------------------------------------------------------- + +export interface StratifyOperator { + /** + * Generates a new hierarchy from the specified tabular data. Each node in the returned object has a shallow copy of the properties + * from the corresponding data object, excluding the following reserved properties: id, parentId, children. + * + * @param data The root specified data. + * @throws Error on missing id, ambiguous id, cycle, multiple roots or no root. + */ + (data: Datum[]): HierarchyNode; + + /** + * Returns the current id accessor, which defaults to: `(d) => d.id`. + */ + id(): (d: Datum, i: number, data: Datum[]) => string | null | "" | undefined; + /** + * Sets the id accessor to the given function. + * The id accessor is invoked for each element in the input data passed to the stratify operator. + * The returned string is then used to identify the node's relationships in conjunction with the parent id. + * For leaf nodes, the id may be undefined, null or the empty string; otherwise, the id must be unique. + * + * @param id The id accessor. + */ + id(id: (d: Datum, i: number, data: Datum[]) => string | null | "" | undefined): this; + + /** + * Returns the current parent id accessor, which defaults to: `(d) => d.parentId`. + */ + parentId(): (d: Datum, i: number, data: Datum[]) => string | null | "" | undefined; + /** + * Sets the parent id accessor to the given function. + * The parent id accessor is invoked for each element in the input data passed to the stratify operator. + * The returned string is then used to identify the node's relationships in conjunction with the id. + * For the root node, the parent id should be undefined, null or the empty string. + * There must be exactly one root node in the input data, and no circular relationships. + * + * @param parentId The parent id accessor. + */ + parentId(parentId: (d: Datum, i: number, data: Datum[]) => string | null | "" | undefined): this; + + /** + * Returns the current path accessor, which defaults to undefined. + */ + path(): ((d: Datum, i: number, data: Datum[]) => string) | null | undefined; + /** + * If path is specified, sets the path accessor to the given function and returns this stratify operator. + * Otherwise, returns the current path accessor, which defaults to undefined. + * If a path accessor is set, the id and parentId arguments are ignored, + * and a unix-like hierarchy is computed on the slash-delimited strings + * returned by the path accessor, imputing parent nodes and ids as necessary. + * + * @param path The path accessor. + */ + path(path: ((d: Datum, i: number, data: Datum[]) => string) | null | undefined): this; +} + +/** + * Constructs a new stratify operator with the default settings. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function stratify(): StratifyOperator; + +// ----------------------------------------------------------------------- +// Cluster +// ----------------------------------------------------------------------- + +export interface HierarchyPointLink { + /** + * The source of the link. + */ + source: HierarchyPointNode; + + /** + * The target of the link. + */ + target: HierarchyPointNode; +} + +export interface HierarchyPointNode extends HierarchyNode { + /** + * The x-coordinate of the node. + */ + x: number; + + /** + * The y-coordinate of the node. + */ + y: number; + + /** + * Returns an array of links for this node, where each link is an object that defines source and target properties. + * The source of each link is the parent node, and the target is a child node. + */ + links(): Array>; +} + +export interface ClusterLayout { + /** + * Lays out the specified root hierarchy. + * You may want to call `root.sort` before passing the hierarchy to the cluster layout. + * + * @param root The specified root hierarchy. + */ + (root: HierarchyNode): HierarchyPointNode; + + /** + * Returns the current layout size, which defaults to [1, 1]. A layout size of null indicates that a node size will be used instead. + */ + size(): [number, number] | null; + /** + * Sets this cluster layout’s size to the specified [width, height] array and returns the cluster layout. + * The size represent an arbitrary coordinate system; for example, to produce a radial layout, + * a size of [360, radius] corresponds to a breadth of 360° and a depth of radius. + * + * @param size The specified two-element size array. + */ + size(size: [number, number]): this; + + /** + * Returns the current node size, which defaults to null. A node size of null indicates that a layout size will be used instead. + */ + nodeSize(): [number, number] | null; + /** + * Sets this cluster layout’s node size to the specified [width, height] array and returns this cluster layout. + * When a node size is specified, the root node is always positioned at <0, 0>. + * + * @param size The specified two-element size array. + */ + nodeSize(size: [number, number]): this; + + /** + * Returns the current separation accessor, which defaults to: `(a, b) => a.parent == b.parent ? 1 : 2`. + */ + separation(): (a: HierarchyPointNode, b: HierarchyPointNode) => number; + /** + * Sets the separation accessor to the specified function and returns this cluster layout. + * The separation accessor is used to separate neighboring leaves. + * + * @param separation The separation function is passed two leaves a and b, and must return the desired separation. + * The nodes are typically siblings, though the nodes may be more distantly related if the layout decides to place such nodes adjacent. + */ + separation(separation: (a: HierarchyPointNode, b: HierarchyPointNode) => number): this; +} + +/** + * Creates a new cluster layout with default settings. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function cluster(): ClusterLayout; + +// ----------------------------------------------------------------------- +// Tree +// ----------------------------------------------------------------------- + +export interface TreeLayout { + /** + * Lays out the specified root hierarchy. + * You may want to call `root.sort` before passing the hierarchy to the tree layout. + * + * @param root The specified root hierarchy. + */ + (root: HierarchyNode): HierarchyPointNode; + + /** + * Returns the current layout size, which defaults to [1, 1]. A layout size of null indicates that a node size will be used instead. + */ + size(): [number, number] | null; + /** + * Sets this tree layout’s size to the specified [width, height] array and returns the tree layout. + * The size represent an arbitrary coordinate system; for example, to produce a radial layout, + * a size of [360, radius] corresponds to a breadth of 360° and a depth of radius. + * + * @param size The specified two-element size array. + */ + size(size: [number, number]): this; + + /** + * Returns the current node size, which defaults to null. A node size of null indicates that a layout size will be used instead. + */ + nodeSize(): [number, number] | null; + /** + * Sets this tree layout’s node size to the specified [width, height] array and returns this tree layout. + * When a node size is specified, the root node is always positioned at <0, 0>. + * + * @param size The specified two-element size array. + */ + nodeSize(size: [number, number]): this; + + /** + * Returns the current separation accessor, which defaults to: `(a, b) => a.parent == b.parent ? 1 : 2`. + */ + separation(): (a: HierarchyPointNode, b: HierarchyPointNode) => number; + /** + * Sets the separation accessor to the specified function and returns this tree layout. + * The separation accessor is used to separate neighboring nodes. + * + * @param separation The separation function is passed two nodes a and b, and must return the desired separation. + * The nodes are typically siblings, though the nodes may be more distantly related if the layout decides to place such nodes adjacent. + */ + separation(separation: (a: HierarchyPointNode, b: HierarchyPointNode) => number): this; +} + +/** + * Creates a new tree layout with default settings. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function tree(): TreeLayout; + +// ----------------------------------------------------------------------- +// Treemap +// ----------------------------------------------------------------------- + +export interface HierarchyRectangularLink { + /** + * The source of the link. + */ + source: HierarchyRectangularNode; + + /** + * The target of the link. + */ + target: HierarchyRectangularNode; +} + +export interface HierarchyRectangularNode extends HierarchyNode { + /** + * The left edge of the rectangle. + */ + x0: number; + + /** + * The top edge of the rectangle + */ + y0: number; + + /** + * The right edge of the rectangle. + */ + x1: number; + + /** + * The bottom edge of the rectangle. + */ + y1: number; + + /** + * Returns an array of links for this node, where each link is an object that defines source and target properties. + * The source of each link is the parent node, and the target is a child node. + */ + links(): Array>; +} + +export interface TreemapLayout { + /** + * Lays out the specified root hierarchy. + * You must call `root.sum` before passing the hierarchy to the treemap layout. + * You probably also want to call `root.sort` to order the hierarchy before computing the layout. + * + * @param root The specified root hierarchy. + */ + (root: HierarchyNode): HierarchyRectangularNode; + + /** + * Returns the current tiling method, which defaults to `d3.treemapSquarify` with the golden ratio. + */ + tile(): (node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number) => void; + /** + * Sets the tiling method to the specified function and returns this treemap layout. + * + * @param tile The specified tiling function. + */ + tile(tile: (node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number) => void): this; + + /** + * Returns the current size, which defaults to [1, 1]. + */ + size(): [number, number]; + /** + * Sets this treemap layout’s size to the specified [width, height] array and returns this treemap layout. + * + * @param size The specified two-element size array. + */ + size(size: [number, number]): this; + + /** + * Returns the current rounding state, which defaults to false. + */ + round(): boolean; + /** + * Enables or disables rounding according to the given boolean and returns this treemap layout. + * + * @param round The specified boolean flag. + */ + round(round: boolean): this; + + /** + * Returns the current inner padding function. + */ + padding(): (node: HierarchyRectangularNode) => number; + /** + * Sets the inner and outer padding to the specified number and returns this treemap layout. + * + * @param padding The specified padding value. + */ + padding(padding: number): this; + /** + * Sets the inner and outer padding to the specified function and returns this treemap layout. + * + * @param padding The specified padding function. + */ + padding(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current inner padding function, which defaults to the constant zero. + */ + paddingInner(): (node: HierarchyRectangularNode) => number; + /** + * Sets the inner padding to the specified number and returns this treemap layout. + * The inner padding is used to separate a node’s adjacent children. + * + * @param padding The specified inner padding value. + */ + paddingInner(padding: number): this; + /** + * Sets the inner padding to the specified function and returns this treemap layout. + * The function is invoked for each node with children, being passed the current node. + * The inner padding is used to separate a node’s adjacent children. + * + * @param padding The specified inner padding function. + */ + paddingInner(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current top padding function. + */ + paddingOuter(): (node: HierarchyRectangularNode) => number; + /** + * Sets the top, right, bottom and left padding to the specified function and returns this treemap layout. + * + * @param padding The specified padding outer value. + */ + paddingOuter(padding: number): this; + /** + * Sets the top, right, bottom and left padding to the specified function and returns this treemap layout. + * + * @param padding The specified padding outer function. + */ + paddingOuter(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current top padding function, which defaults to the constant zero. + */ + paddingTop(): (node: HierarchyRectangularNode) => number; + /** + * Sets the top padding to the specified number and returns this treemap layout. + * The top padding is used to separate the top edge of a node from its children. + * + * @param padding The specified top padding value. + */ + paddingTop(padding: number): this; + /** + * Sets the top padding to the specified function and returns this treemap layout. + * The function is invoked for each node with children, being passed the current node. + * The top padding is used to separate the top edge of a node from its children. + * + * @param padding The specified top padding function. + */ + paddingTop(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current right padding function, which defaults to the constant zero. + */ + paddingRight(): (node: HierarchyRectangularNode) => number; + /** + * Sets the right padding to the specified number and returns this treemap layout. + * The right padding is used to separate the right edge of a node from its children. + * + * @param padding The specified right padding value. + */ + paddingRight(padding: number): this; + /** + * Sets the right padding to the specified function and returns this treemap layout. + * The function is invoked for each node with children, being passed the current node. + * The right padding is used to separate the right edge of a node from its children. + * + * @param padding The specified right padding function. + */ + paddingRight(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current bottom padding function, which defaults to the constant zero. + */ + paddingBottom(): (node: HierarchyRectangularNode) => number; + /** + * Sets the bottom padding to the specified number and returns this treemap layout. + * The bottom padding is used to separate the bottom edge of a node from its children. + * + * @param padding The specified bottom padding value. + */ + paddingBottom(padding: number): this; + /** + * Sets the bottom padding to the specified function and returns this treemap layout. + * The function is invoked for each node with children, being passed the current node. + * The bottom padding is used to separate the bottom edge of a node from its children. + * + * @param padding The specified bottom padding function. + */ + paddingBottom(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current left padding function, which defaults to the constant zero. + */ + paddingLeft(): (node: HierarchyRectangularNode) => number; + /** + * Sets the left padding to the specified number and returns this treemap layout. + * The left padding is used to separate the left edge of a node from its children. + * + * @param padding The specified left padding value. + */ + paddingLeft(padding: number): this; + /** + * Sets the left padding to the specified function and returns this treemap layout. + * The function is invoked for each node with children, being passed the current node. + * The left padding is used to separate the left edge of a node from its children. + * + * @param padding The specified left padding function. + */ + paddingLeft(padding: (node: HierarchyRectangularNode) => number): this; +} + +/** + * Creates a new treemap layout with default settings. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function treemap(): TreemapLayout; + +// Tiling functions ------------------------------------------------------ + +/** + * Recursively partitions the specified nodes into an approximately-balanced binary tree, + * choosing horizontal partitioning for wide rectangles and vertical partitioning for tall rectangles. + */ +export function treemapBinary( + node: HierarchyRectangularNode, + x0: number, + y0: number, + x1: number, + y1: number, +): void; + +/** + * Divides the rectangular area specified by x0, y0, x1, y1 horizontally according the value of each of the specified node’s children. + * The children are positioned in order, starting with the left edge (x0) of the given rectangle. + * If the sum of the children’s values is less than the specified node’s value (i.e., if the specified node has a non-zero internal value), + * the remaining empty space will be positioned on the right edge (x1) of the given rectangle. + */ +export function treemapDice(node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void; + +/** + * Divides the rectangular area specified by x0, y0, x1, y1 vertically according the value of each of the specified node’s children. + * The children are positioned in order, starting with the top edge (y0) of the given rectangle. + * If the sum of the children’s values is less than the specified node’s value (i.e., if the specified node has a non-zero internal value), + * the remaining empty space will be positioned on the bottom edge (y1) of the given rectangle. + */ +export function treemapSlice(node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void; + +/** + * If the specified node has odd depth, delegates to treemapSlice; otherwise delegates to treemapDice. + */ +export function treemapSliceDice( + node: HierarchyRectangularNode, + x0: number, + y0: number, + x1: number, + y1: number, +): void; + +// TODO: Test Factory code +export interface RatioSquarifyTilingFactory { + (node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void; + + /** + * Specifies the desired aspect ratio of the generated rectangles. + * Note that the orientation of the generated rectangles (tall or wide) is not implied by the ratio. + * Furthermore, the rectangles ratio are not guaranteed to have the exact specified aspect ratio. + * If not specified, the aspect ratio defaults to the golden ratio, φ = (1 + sqrt(5)) / 2, per Kong et al. + * + * @param ratio The specified ratio value greater than or equal to one. + */ + ratio(ratio: number): RatioSquarifyTilingFactory; +} + +/** + * Implements the squarified treemap algorithm by Bruls et al., which seeks to produce rectangles of a given aspect ratio. + */ +export const treemapSquarify: RatioSquarifyTilingFactory; + +/** + * Like `d3.treemapSquarify`, except preserves the topology (node adjacencies) of the previous layout computed by `d3.treemapResquarify`, + * if there is one and it used the same target aspect ratio. This tiling method is good for animating changes to treemaps because + * it only changes node sizes and not their relative positions, thus avoiding distracting shuffling and occlusion. + * The downside of a stable update, however, is a suboptimal layout for subsequent updates: only the first layout uses the Bruls et al. squarified algorithm. + */ +export const treemapResquarify: RatioSquarifyTilingFactory; + +// ----------------------------------------------------------------------- +// Partition +// ----------------------------------------------------------------------- + +export interface PartitionLayout { + /** + * Lays out the specified root hierarchy. + * You must call `root.sum` before passing the hierarchy to the partition layout. + * You probably also want to call `root.sort` to order the hierarchy before computing the layout. + * + * @param root The specified root hierarchy. + */ + (root: HierarchyNode): HierarchyRectangularNode; + + /** + * Returns the current size, which defaults to [1, 1]. + */ + size(): [number, number]; + /** + * Sets this partition layout’s size to the specified [width, height] array and returns this partition layout. + * + * @param size The specified two-element size array. + */ + size(size: [number, number]): this; + + /** + * Returns the current rounding state, which defaults to false. + */ + round(): boolean; + /** + * Enables or disables rounding according to the given boolean and returns this partition layout. + * + * @param round The specified boolean flag. + */ + round(round: boolean): this; + + /** + * Returns the current padding, which defaults to zero. + */ + padding(): number; + /** + * Sets the padding to the specified number and returns this partition layout. + * The padding is used to separate a node’s adjacent children. + * + * @param padding The specified padding value. + */ + padding(padding: number): this; +} + +/** + * Creates a new partition layout with the default settings. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function partition(): PartitionLayout; + +// ----------------------------------------------------------------------- +// Pack +// ----------------------------------------------------------------------- + +export interface HierarchyCircularLink { + /** + * The source of the link. + */ + source: HierarchyCircularNode; + + /** + * The target of the link. + */ + target: HierarchyCircularNode; +} + +export interface HierarchyCircularNode extends HierarchyNode { + /** + * The x-coordinate of the circle’s center. + */ + x: number; + + /** + * The y-coordinate of the circle’s center. + */ + y: number; + + /** + * The radius of the circle. + */ + r: number; + + /** + * Returns an array of links for this node, where each link is an object that defines source and target properties. + * The source of each link is the parent node, and the target is a child node. + */ + links(): Array>; +} + +export interface PackLayout { + /** + * Lays out the specified root hierarchy. + * You must call `root.sum` before passing the hierarchy to the pack layout. + * You probably also want to call `root.sort` to order the hierarchy before computing the layout. + * + * @param root The specified root hierarchy. + */ + (root: HierarchyNode): HierarchyCircularNode; + + /** + * Returns the current radius accessor, which defaults to null. + */ + radius(): null | ((node: HierarchyCircularNode) => number); + /** + * Sets the pack layout’s radius accessor to the specified function and returns this pack layout. + * If the radius accessor is null, the radius of each leaf circle is derived from the leaf `node.value` (computed by `node.sum`); + * the radii are then scaled proportionally to fit the layout size. + * If the radius accessor is not null, the radius of each leaf circle is specified exactly by the function. + * + * @param radius The specified radius accessor. + */ + radius(radius: null | ((node: HierarchyCircularNode) => number)): this; + + /** + * Returns the current size, which defaults to [1, 1]. + */ + size(): [number, number]; + /** + * Sets this pack layout’s size to the specified [width, height] array and returns this pack layout. + * + * @param size The specified two-element size array. + */ + size(size: [number, number]): this; + + /** + * Returns the current padding accessor, which defaults to the constant zero. + */ + padding(): (node: HierarchyCircularNode) => number; + /** + * Sets this pack layout’s padding accessor to the specified number and returns this pack layout. + * Returns the current padding accessor, which defaults to the constant zero. + * + * When siblings are packed, tangent siblings will be separated by approximately the specified padding; + * the enclosing parent circle will also be separated from its children by approximately the specified padding. + * If an explicit radius is not specified, the padding is approximate because a two-pass algorithm + * is needed to fit within the layout size: the circles are first packed without padding; + * a scaling factor is computed and applied to the specified padding; and lastly the circles are re-packed with padding. + * + * @param padding The specified padding value. + */ + padding(padding: number): this; + /** + * Sets this pack layout’s padding accessor to the specified function and returns this pack layout. + * Returns the current padding accessor, which defaults to the constant zero. + * + * When siblings are packed, tangent siblings will be separated by approximately the specified padding; + * the enclosing parent circle will also be separated from its children by approximately the specified padding. + * If an explicit radius is not specified, the padding is approximate because a two-pass algorithm + * is needed to fit within the layout size: the circles are first packed without padding; + * a scaling factor is computed and applied to the specified padding; and lastly the circles are re-packed with padding. + * + * @param padding The specified padding function. + */ + padding(padding: (node: HierarchyCircularNode) => number): this; +} + +/** + * Creates a new pack layout with the default settings. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function pack(): PackLayout; + +// ----------------------------------------------------------------------- +// Pack Siblings and Enclosure +// ----------------------------------------------------------------------- + +export interface PackRadius { + /** + * The radius of the circle. + */ + r: number; + + /** + * The x-coordinate of the circle’s center. + */ + x?: number | undefined; + + /** + * The y-coordinate of the circle’s center. + */ + y?: number | undefined; +} + +export interface PackCircle { + /** + * The radius of the circle. + */ + r: number; + + /** + * The x-coordinate of the circle’s center. + */ + x: number; + + /** + * The y-coordinate of the circle’s center. + */ + y: number; +} + +// TODO: Since packSiblings manipulates the circles array in place, technically the x and y properties +// are optional on invocation, but will be created after execution for each entry. + +/** + * Packs the specified array of circles, each of which must have a `circle.r` property specifying the circle’s radius. + * The circles are positioned according to the front-chain packing algorithm by Wang et al. + * + * @param circles The specified array of circles to pack. + */ +export function packSiblings(circles: Datum[]): Array; + +/** + * Computes the smallest circle that encloses the specified array of circles, each of which must have + * a `circle.r` property specifying the circle’s radius, and `circle.x` and `circle.y` properties specifying the circle’s center. + * The enclosing circle is computed using the Matoušek-Sharir-Welzl algorithm. (See also Apollonius’ Problem.) + * + * @param circles The specified array of circles to pack. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function packEnclose(circles: Datum[]): PackCircle; diff --git a/tools/ui/node_modules/@types/d3-hierarchy/package.json b/tools/ui/node_modules/@types/d3-hierarchy/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a7c4f95b2e32347bd9805e49af998a99a34ed9e6 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-hierarchy/package.json @@ -0,0 +1,50 @@ +{ + "name": "@types/d3-hierarchy", + "version": "3.1.7", + "description": "TypeScript definitions for d3-hierarchy", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-hierarchy", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + }, + { + "name": "Fil", + "githubUsername": "Fil", + "url": "https://github.com/Fil" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-hierarchy" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "30b5aaa4063194f57da2717775cb8f9f5dc675a0ec72d6ed619f7b87ad0baa40", + "typeScriptVersion": "4.7" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-interpolate/LICENSE b/tools/ui/node_modules/@types/d3-interpolate/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-interpolate/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-interpolate/README.md b/tools/ui/node_modules/@types/d3-interpolate/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b57b552a607a28684d0dcf059f6bf17c3055dd34 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-interpolate/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-interpolate` + +# Summary +This package contains type definitions for d3-interpolate (https://github.com/d3/d3-interpolate/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-interpolate. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:37 GMT + * Dependencies: [@types/d3-color](https://npmjs.com/package/@types/d3-color) + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [denisname](https://github.com/denisname), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-interpolate/index.d.ts b/tools/ui/node_modules/@types/d3-interpolate/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cbb655be6681b6653cec5a3edd4e7f6cbcb88406 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-interpolate/index.d.ts @@ -0,0 +1,387 @@ +// Last module patch version validated against: 3.0.1 + +import { ColorCommonInstance } from "d3-color"; + +// --------------------------------------------------------------------------- +// Shared Type Definitions and Interfaces +// --------------------------------------------------------------------------- + +export interface ZoomInterpolator extends Function { + (t: number): ZoomView; + /** + * Recommended duration of zoom transition in milliseconds. + */ + duration: number; + + /** + * Given a zoom interpolator, returns a new zoom interpolator using the specified curvature rho. + * When rho is close to 0, the interpolator is almost linear. + * The default curvature is sqrt(2). + * @param rho + */ + rho(rho: number): this; +} + +export interface ColorGammaInterpolationFactory extends Function { + (a: string | ColorCommonInstance, b: string | ColorCommonInstance): (t: number) => string; + /** + * Returns a new interpolator factory of the same type using the specified *gamma*. + * For example, to interpolate from purple to orange with a gamma of 2.2 in RGB space: `d3.interpolateRgb.gamma(2.2)("purple", "orange")`. + * See Eric Brasseur’s article, [Gamma error in picture scaling](https://web.archive.org/web/20160112115812/http://www.4p8.com/eric.brasseur/gamma.html), for more on gamma correction. + */ + gamma(g: number): ColorGammaInterpolationFactory; +} + +/** + * Type zoomView is used to represent a numeric array with three elements. + * In order of appearance the elements correspond to: + * - cx: *x*-coordinate of the center of the viewport + * - cy: *y*-coordinate of the center of the viewport + * - width: size of the viewport + */ +export type ZoomView = [number, number, number]; + +export type TypedArray = + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Uint8ClampedArray + | Float32Array + | Float64Array; + +export type NumberArray = TypedArray | DataView; + +// --------------------------------------------------------------------------- +// Interpolation Function Factories +// --------------------------------------------------------------------------- + +/** + * Returns an `null` constant interpolator. + */ +export function interpolate(a: any, b: null): (t: number) => null; +/** + * Returns an boolean constant interpolator of value `b`. + */ +export function interpolate(a: any, b: boolean): (t: number) => boolean; +/** + * Returns a `interpolateRgb` interpolator. + */ +export function interpolate(a: string | ColorCommonInstance, b: ColorCommonInstance): (t: number) => string; +/** + * Returns a `interpolateDate` interpolator. + */ +export function interpolate(a: Date, b: Date): (t: number) => Date; +/** + * Returns a `interpolateNumber` interpolator. + */ +export function interpolate( + a: number | { valueOf(): number }, + b: number | { valueOf(): number }, +): (t: number) => number; +/** + * Returns a `interpolateNumberArray` interpolator. + */ +export function interpolate(a: NumberArray | number[], b: T): (t: number) => T; +/** + * Returns a `interpolateString` interpolator. If `b` is a string coercible to a color use use `interpolateRgb`. + */ +export function interpolate(a: string | { toString(): string }, b: string): (t: number) => string; +/** + * Returns a `interpolateArray` interpolator. + */ +export function interpolate(a: any[], b: U): (t: number) => U; +/** + * Returns a `interpolateObject` interpolator. + */ +export function interpolate(a: any, b: U): (t: number) => U; + +/** + * Returns an interpolator between the two numbers `a` and `b`. + * The returned interpolator is equivalent to: `(t) => a * (1 - t) + b * t`. + */ +export function interpolateNumber( + a: number | { valueOf(): number }, + b: number | { valueOf(): number }, +): (t: number) => number; + +/** + * Returns an interpolator between the two numbers `a` and `b`; the interpolator is similar to `interpolateNumber`, + * except it will round the resulting value to the nearest integer. + */ +export function interpolateRound( + a: number | { valueOf(): number }, + b: number | { valueOf(): number }, +): (t: number) => number; + +/** + * Returns an interpolator between the two strings `a` and `b`. + * The string interpolator finds numbers embedded in `a` and `b`, where each number is of the form understood by JavaScript. + * A few examples of numbers that will be detected within a string: `-1`, `42`, `3.14159`, and `6.0221413e+23`. + * + * For each number embedded in `b`, the interpolator will attempt to find a corresponding number in `a`. + * If a corresponding number is found, a numeric interpolator is created using `interpolateNumber`. + * The remaining parts of the string `b` are used as a template. + * + * For example, if `a` is `"300 12px sans-serif"`, and `b` is `"500 36px Comic-Sans"`, two embedded numbers are found. + * The remaining static parts (of string `b`) are a space between the two numbers (`" "`), and the suffix (`"px Comic-Sans"`). + * The result of the interpolator at `t` = 0.5 is `"400 24px Comic-Sans"`. + */ +export function interpolateString( + a: string | { toString(): string }, + b: string | { toString(): string }, +): (t: number) => string; + +/** + * Returns an interpolator between the two dates `a` and `b`. + * + * Note: *no defensive copy* of the returned date is created; the same Date instance is returned for every evaluation of the interpolator. + * No copy is made for performance reasons; interpolators are often part of the inner loop of animated transitions. + */ +export function interpolateDate(a: Date, b: Date): (t: number) => Date; + +export type ArrayInterpolator = (t: number) => A; + +/** + * Returns an interpolator between the two arrays `a` and `b`. Internally, an array template is created that is the same length in `b`. + * For each element in `b`, if there exists a corresponding element in `a`, a generic interpolator is created for the two elements using `interpolate`. + * If there is no such element, the static value from `b` is used in the template. + * Then, for the given parameter `t`, the template’s embedded interpolators are evaluated. The updated array template is then returned. + * + * For example, if `a` is the array `[0, 1]` and `b` is the array `[1, 10, 100]`, then the result of the interpolator for `t = 0.5` is the array `[0.5, 5.5, 100]`. + * + * Note: *no defensive copy* of the template array is created; modifications of the returned array may adversely affect subsequent evaluation of the interpolator. + * No copy is made for performance reasons; interpolators are often part of the inner loop of animated transitions. + */ +export function interpolateArray(a: any[], b: A): ArrayInterpolator; +/** + * interpolateNumberArray is called + */ +export function interpolateArray(a: NumberArray | number[], b: T): (t: number) => T; + +/** + * Returns an interpolator between the two arrays of numbers a and b. + * Internally, an array template is created that is the same type and length as b. + * For each element in b, if there exists a corresponding element in a, the values are directly interpolated in the array template. + * If there is no such element, the static value from b is copied. + * The updated array template is then returned. + * + * Note: For performance reasons, no defensive copy is made of the template array and the arguments a and b; modifications of these arrays may affect subsequent evaluation of the interpolator. + */ +export function interpolateNumberArray( + a: NumberArray | number[], + b: T, +): (t: number) => T; + +/** + * Returns an interpolator between the two objects `a` and `b`. Internally, an object template is created that has the same properties as `b`. + * For each property in `b`, if there exists a corresponding property in `a`, a generic interpolator is created for the two elements using `interpolate`. + * If there is no such property, the static value from `b` is used in the template. + * Then, for the given parameter `t`, the template's embedded interpolators are evaluated and the updated object template is then returned. + * + * For example, if `a` is the object `{x: 0, y: 1}` and `b` is the object `{x: 1, y: 10, z: 100}`, the result of the interpolator for `t = 0.5` is the object `{x: 0.5, y: 5.5, z: 100}`. + * + * Note: *no defensive copy* of the template object is created; modifications of the returned object may adversely affect subsequent evaluation of the interpolator. + * No copy is made for performance reasons; interpolators are often part of the inner loop of animated transitions. + */ +export function interpolateObject(a: any, b: U): (t: number) => U; + +/** + * Returns an interpolator between the two 2D CSS transforms represented by `a` and `b`. + * Each transform is decomposed to a standard representation of translate, rotate, *x*-skew and scale; these component transformations are then interpolated. + * This behavior is standardized by CSS: see [matrix decomposition for animation](http://www.w3.org/TR/css3-2d-transforms/#matrix-decomposition). + */ +export function interpolateTransformCss(a: string, b: string): (t: number) => string; + +/** + * Returns an interpolator between the two 2D SVG transforms represented by `a` and `b`. + * Each transform is decomposed to a standard representation of translate, rotate, *x*-skew and scale; these component transformations are then interpolated. + * This behavior is standardized by CSS: see [matrix decomposition for animation](http://www.w3.org/TR/css3-2d-transforms/#matrix-decomposition). + */ +export function interpolateTransformSvg(a: string, b: string): (t: number) => string; + +/** + * Returns an interpolator between the two views `a` and `b` of a two-dimensional plane, + * based on [“Smooth and efficient zooming and panning”](http://www.win.tue.nl/~vanwijk/zoompan.pdf). + * Each view is defined as an array of three numbers: *cx*, *cy* and *width*. + * The first two coordinates *cx*, *cy* represent the center of the viewport; the last coordinate *width* represents the size of the viewport. + * + * The returned interpolator exposes a *duration* property which encodes the recommended transition duration in milliseconds. + * This duration is based on the path length of the curved trajectory through *x,y* space. + * If you want to a slower or faster transition, multiply this by an arbitrary scale factor (*V* as described in the original paper). + */ +export function interpolateZoom(a: ZoomView, b: ZoomView): ZoomInterpolator; + +/** + * Returns a discrete interpolator for the given array of values. The returned interpolator maps `t` in `[0, 1 / n)` to values[0], + * `t` in `[1 / n, 2 / n)` to `values[1]`, and so on, where `n = values.length`. In effect, this is a lightweight quantize scale with a fixed domain of [0, 1]. + */ +export function interpolateDiscrete(values: T[]): (t: number) => T; + +// Sampling ------------------------------------------------------------------ + +/** + * Returns `n` uniformly-spaced samples from the specified `interpolator`, where `n` is an integer greater than one. + * The first sample is always at `t = 0`, and the last sample is always at `t = 1`. + * This can be useful in generating a fixed number of samples from a given interpolator, + * such as to derive the range of a [quantize scale](https://github.com/d3/d3-scale#quantize-scales) from a [continuous interpolator](https://github.com/d3/d3-scale#interpolateWarm). + * + * Caution: this method will not work with interpolators that do not return defensive copies of their output, + * such as `d3.interpolateArray`, `d3.interpolateDate` and `d3.interpolateObject`. For those interpolators, you must wrap the interpolator and create a copy for each returned value. + */ +export function quantize(interpolator: (t: number) => T, n: number): T[]; + +// Color Spaces + +/** + * Returns an RGB color space interpolator between the two colors `a` and `b` with a configurable gamma. If the gamma is not specified, it defaults to 1.0. + * The colors `a` and `b` need not be in RGB; they will be converted to RGB using [`d3.rgb`](https://github.com/d3/d3-color#rgb). The return value of the interpolator is an RGB string. + */ +export const interpolateRgb: ColorGammaInterpolationFactory; + +/** + * Returns a uniform nonrational B-spline interpolator through the specified array of *colors*, which are converted to RGB color space. + * Implicit control points are generated such that the interpolator returns `colors[0]` at `t = 0` and `colors[colors.length - 1]` at `t = 1`. + * Opacity interpolation is not currently supported. See also `d3.interpolateBasis`, and see [d3-scale-chromatic](https://github.com/d3/d3-scale-chromatic) for examples. + */ +export function interpolateRgbBasis(colors: Array): (t: number) => string; + +/** + * Returns a uniform nonrational B-spline interpolator through the specified array of colors, which are converted to RGB color space. + * The control points are implicitly repeated such that the resulting spline has cyclical C² continuity when repeated around `t` in [0,1]; + * this is useful, for example, to create cyclical color scales. Opacity interpolation is not currently supported. + * See also `d3.interpolateBasisClosed, and see [d3-scale-chromatic](https://github.com/d3/d3-scale-chromatic) for examples. + */ +export function interpolateRgbBasisClosed(colors: Array): (t: number) => string; + +/** + * Returns an HSL color space interpolator between the two colors *a* and *b*. The colors *a* and *b* need not be in HSL; + * they will be converted to HSL using `d3.hsl`. If either color’s hue or saturation is NaN, the opposing color’s channel value is used. + * The shortest path between hues is used. The return value of the interpolator is an RGB string. + */ +export function interpolateHsl(a: string | ColorCommonInstance, b: string | ColorCommonInstance): (t: number) => string; + +/** + * Like `interpolateHsl`, but does not use the shortest path between hues. + */ +export function interpolateHslLong( + a: string | ColorCommonInstance, + b: string | ColorCommonInstance, +): (t: number) => string; + +/** + * Returns a Lab color space interpolator between the two colors *a* and *b*. The colors *a* and *b* need not be in Lab; + * they will be converted to Lab using `d3.lab`. The return value of the interpolator is an RGB string. + */ +export function interpolateLab(a: string | ColorCommonInstance, b: string | ColorCommonInstance): (t: number) => string; + +/** + * Returns an HCL color space interpolator between the two colors `a` and `b`. The colors `a` and `b` need not be in HCL; + * they will be converted to HCL using `d3.hcl`. If either color’s hue or chroma is NaN, the opposing color’s channel value is used. + * The shortest path between hues is used. The return value of the interpolator is an RGB string. + */ +export function interpolateHcl(a: string | ColorCommonInstance, b: string | ColorCommonInstance): (t: number) => string; + +/** + * Like `interpolateHcl`, but does not use the shortest path between hues. + */ +export function interpolateHclLong( + a: string | ColorCommonInstance, + b: string | ColorCommonInstance, +): (t: number) => string; + +/** + * Returns a Cubehelix color space interpolator between the two colors `a` and `b` using a configurable `gamma`. + * If the gamma is not specified, it defaults to 1.0. The colors `a` and `b` need not be in Cubehelix; + * they will be converted to Cubehelix using [`d3.cubehelix`](https://github.com/d3/d3-color#cubehelix). + * If either color’s hue or saturation is NaN, the opposing color’s channel value is used. The shortest path between hues is used. The return value of the interpolator is an RGB string. + */ +export const interpolateCubehelix: ColorGammaInterpolationFactory; + +/** + * Like `interpolateCubehelix`, but does not use the shortest path between hues. + */ +export const interpolateCubehelixLong: ColorGammaInterpolationFactory; + +/** + * Returns an interpolator between the two hue angles `a` and `b`. If either hue is NaN, the opposing value is used. + * The shortest path between hues is used. The return value of the interpolator is a number in `[0, 360)`. + */ +export function interpolateHue(a: number, b: number): (t: number) => number; + +// Splines ------------------------------------------------------------------- + +/** + * Returns a uniform nonrational B-spline interpolator through the specified array of `values`, which must be numbers. + * Implicit control points are generated such that the interpolator returns `values[0]` at `t` = 0 and `values[values.length - 1]` at `t` = 1. + * See also [`d3.curveBasis`](https://github.com/d3/d3-shape#curveBasis). + */ +export function interpolateBasis(splineNodes: number[]): (t: number) => number; + +/** + * Returns a uniform nonrational B-spline interpolator through the specified array of `values`, which must be numbers. + * The control points are implicitly repeated such that the resulting one-dimensional spline has cyclical C² continuity when repeated around `t` in [0,1]. + * See also [`d3.curveBasisClosed`](https://github.com/d3/d3-shape#curveBasisClosed). + */ +export function interpolateBasisClosed(splineNodes: number[]): (t: number) => number; + +// Piecewise ----------------------------------------------------------------- + +/** + * Returns a piecewise zoom interpolator, composing zoom interpolators for each adjacent pair of zoom view. + * The returned interpolator maps `t` in `[0, 1 / (n - 1)]` to `interpolate(values[0], values[1])`, `t` in `[1 / (n - 1), 2 / (n - 1)]` to `interpolate(values[1], values[2])`, + * and so on, where `n = values.length`. In effect, this is a lightweight linear scale. + * For example, to blend through three different zoom views: `d3.piecewise(d3.interpolateZoom, [[0, 0, 1], [0, 0, 10], [0, 0, 15]])`. + * + * interpolate defaults to d3.interpolate. + */ +export function piecewise(values: ZoomView[]): ZoomInterpolator; +/** + * Returns a piecewise zoom interpolator, composing zoom interpolators for each adjacent pair of zoom view. + * The returned interpolator maps `t` in `[0, 1 / (n - 1)]` to `interpolate(values[0], values[1])`, `t` in `[1 / (n - 1), 2 / (n - 1)]` to `interpolate(values[1], values[2])`, + * and so on, where `n = values.length`. In effect, this is a lightweight linear scale. + * For example, to blend through three different zoom views: `d3.piecewise(d3.interpolateZoom, [[0, 0, 1], [0, 0, 10], [0, 0, 15]])`. + */ +export function piecewise( + interpolate: (a: ZoomView, b: ZoomView) => ZoomInterpolator, + values: ZoomView[], +): ZoomInterpolator; + +/** + * Returns a piecewise array interpolator, composing array interpolators for each adjacent pair of arrays. + * The returned interpolator maps `t` in `[0, 1 / (n - 1)]` to `interpolate(values[0], values[1])`, `t` in `[1 / (n - 1), 2 / (n - 1)]` to `interpolate(values[1], values[2])`, + * and so on, where `n = values.length`. In effect, this is a lightweight linear scale. + * For example, to blend through three different arrays: `d3.piecewise(d3.interpolateArray, [[0, 0, 1], [0, 0, 10], [0, 0, 15]])`. + * + * interpolate defaults to d3.interpolate. + */ +export function piecewise(values: A[]): ArrayInterpolator; +/** + * Returns a piecewise array interpolator, composing array interpolators for each adjacent pair of arrays. + * The returned interpolator maps `t` in `[0, 1 / (n - 1)]` to `interpolate(values[0], values[1])`, `t` in `[1 / (n - 1), 2 / (n - 1)]` to `interpolate(values[1], values[2])`, + * and so on, where `n = values.length`. In effect, this is a lightweight linear scale. + * For example, to blend through three different arrays: `d3.piecewise(d3.interpolateArray, [[0, 0, 1], [0, 0, 10], [0, 0, 15]])`. + */ +export function piecewise( + interpolate: (a: any[], b: A) => ArrayInterpolator, + values: A[], +): ArrayInterpolator; + +/** + * Returns a piecewise interpolator, composing interpolators for each adjacent pair of values. + * The returned interpolator maps `t` in `[0, 1 / (n - 1)]` to `interpolate(values[0], values[1])`, `t` in `[1 / (n - 1), 2 / (n - 1)]` to `interpolate(values[1], values[2])`, + * and so on, where `n = values.length`. In effect, this is a lightweight linear scale. + * For example, to blend through red, green and blue: `d3.piecewise(d3.interpolateRgb.gamma(2.2), ["red", "green", "blue"])`. + * + * interpolate defaults to d3.interpolate. + */ +export function piecewise(values: unknown[]): (t: number) => any; +/** + * Returns a piecewise interpolator, composing interpolators for each adjacent pair of values. + * The returned interpolator maps `t` in `[0, 1 / (n - 1)]` to `interpolate(values[0], values[1])`, `t` in `[1 / (n - 1), 2 / (n - 1)]` to `interpolate(values[1], values[2])`, + * and so on, where `n = values.length`. In effect, this is a lightweight linear scale. + * For example, to blend through red, green and blue: `d3.piecewise(d3.interpolateRgb.gamma(2.2), ["red", "green", "blue"])`. + */ +export function piecewise(interpolate: (a: TData, b: TData) => unknown, values: TData[]): (t: number) => any; diff --git a/tools/ui/node_modules/@types/d3-interpolate/package.json b/tools/ui/node_modules/@types/d3-interpolate/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9d687bb3179e525e0bc60f2ee926593f542fa2a6 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-interpolate/package.json @@ -0,0 +1,47 @@ +{ + "name": "@types/d3-interpolate", + "version": "3.0.4", + "description": "TypeScript definitions for d3-interpolate", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-interpolate", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-interpolate" + }, + "scripts": {}, + "dependencies": { + "@types/d3-color": "*" + }, + "typesPublisherContentHash": "d315fc677144695b44f1447ef7429c9ff248886716c2e9f742d031abcb319115", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-path/LICENSE b/tools/ui/node_modules/@types/d3-path/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-path/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-path/README.md b/tools/ui/node_modules/@types/d3-path/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3352a58cff08b1f5f4306ae703ebb69e3bb8f7de --- /dev/null +++ b/tools/ui/node_modules/@types/d3-path/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-path` + +# Summary +This package contains type definitions for d3-path (https://github.com/d3/d3-path/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-path. + +### Additional Details + * Last updated: Tue, 04 Feb 2025 22:02:37 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-path/index.d.ts b/tools/ui/node_modules/@types/d3-path/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b64b707bf4583f21f77893b52ea9488822b4ee0 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-path/index.d.ts @@ -0,0 +1,108 @@ +// Last module patch version validated against: 3.1.0 + +/** + * A D3 path serializer implementing CanvasPathMethods + */ +export interface Path { + /** + * Move to the specified point ⟨x, y⟩. Equivalent to context.moveTo and SVG’s “moveto” command. + * + * @param x x-Coordinate of point to move to + * @param y y-Coordinate of point to move to + */ + moveTo(x: number, y: number): void; + + /** + * Ends the current subpath and causes an automatic straight line to be drawn from the current point to the initial point of the current subpath. + * Equivalent to context.closePath and SVG’s “closepath” command. + */ + closePath(): void; + + /** + * Draws a straight line from the current point to the specified point ⟨x, y⟩. + * Equivalent to context.lineTo and SVG’s “lineto” command. + * + * @param x x-Coordinate of point to draw the line to + * @param y y-Coordinate of point to draw the line to + */ + lineTo(x: number, y: number): void; + + /** + * Draws a quadratic Bézier segment from the current point to the specified point ⟨x, y⟩, with the specified control point ⟨cpx, cpy⟩. + * Equivalent to context.quadraticCurveTo and SVG’s quadratic Bézier curve commands. + * + * @param cpx x-Coordinate of the control point for the quadratic Bézier curve + * @param cpy y-Coordinate of the control point for the quadratic Bézier curve + * @param x x-Coordinate of point to draw the curve to + * @param y y-Coordinate of point to draw the curve to + */ + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + + /** + * Draws a cubic Bézier segment from the current point to the specified point ⟨x, y⟩, with the specified control points ⟨cpx1, cpy1⟩ and ⟨cpx2, cpy2⟩. + * Equivalent to context.bezierCurveTo and SVG’s cubic Bézier curve commands. + * + * @param cpx1 x-Coordinate of the first control point for the Bézier curve + * @param cpy1 y-Coordinate of the first control point for the Bézier curve + * @param cpx2 x-Coordinate of the second control point for the Bézier curve + * @param cpy2 y-Coordinate of the second control point for the Bézier curve + * @param x x-Coordinate of point to draw the curve to + * @param y y-Coordinate of point to draw the curve to + */ + bezierCurveTo(cpx1: number, cpy1: number, cpx2: number, cpy2: number, x: number, y: number): void; + + /** + * Draws a circular arc segment with the specified radius that starts tangent to the line between the current point and the specified point ⟨x1, y1⟩ + * and ends tangent to the line between the specified points ⟨x1, y1⟩ and ⟨x2, y2⟩. If the first tangent point is not equal to the current point, + * a straight line is drawn between the current point and the first tangent point. Equivalent to context.arcTo and uses SVG’s elliptical arc curve commands. + * + * @param x1 x-Coordinate of the first tangent point + * @param y1 y-Coordinate of the first tangent point + * @param x2 x-Coordinate of the second tangent point + * @param y2 y-Coordinate of the second tangent point + * @param radius Radius of the arc segment + */ + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; + + /** + * Draws a circular arc segment with the specified center ⟨x, y⟩, radius, startAngle and endAngle. If anticlockwise is true, + * the arc is drawn in the anticlockwise direction; otherwise, it is drawn in the clockwise direction. + * If the current point is not equal to the starting point of the arc, a straight line is drawn from the current point to the start of the arc. + * Equivalent to context.arc and uses SVG’s elliptical arc curve commands. + * + * @param x x-Coordinate of the center point of the arc segment + * @param y y-Coordinate of the center point of the arc segment + * @param radius Radius of the arc segment + * @param startAngle Start angle of arc segment + * @param endAngle End angle of arc segment + * @param anticlockwise Flag indicating directionality (true = anti-clockwise, false = clockwise) + */ + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + + /** + * Creates a new subpath containing just the four points ⟨x, y⟩, ⟨x + w, y⟩, ⟨x + w, y + h⟩, ⟨x, y + h⟩, + * with those four points connected by straight lines, and then marks the subpath as closed. Equivalent to context.rect and uses SVG’s “lineto” commands. + * + * @param x x-Coordinate of starting point for drawing the rectangle + * @param y y-Coordinate of starting point for drawing the rectangle + * @param w Width of rectangle + * @param h Height of rectangle + */ + rect(x: number, y: number, w: number, h: number): void; + + /** + * Returns the string representation of this path according to SVG’s path data specification. + */ + toString(): string; +} + +/** + * Construct a D3 Path serializer + */ +export function path(): Path; + +/** + * Like {@link path}, except limits the digits after the decimal to the specified number of digits. + * Useful for reducing the size of generated SVG path data. + */ +export function pathRound(digits?: number): Path; diff --git a/tools/ui/node_modules/@types/d3-path/package.json b/tools/ui/node_modules/@types/d3-path/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4861a7f6744371f1b19053c23191c222d2e677d8 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-path/package.json @@ -0,0 +1,41 @@ +{ + "name": "@types/d3-path", + "version": "3.1.1", + "description": "TypeScript definitions for d3-path", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-path", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-path" + }, + "scripts": {}, + "dependencies": {}, + "peerDependencies": {}, + "typesPublisherContentHash": "a49fc946781c1138c0dd932ed2a34ea60587bcc0b39790e4eb9a51cb32aaa90b", + "typeScriptVersion": "5.0" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-polygon/LICENSE b/tools/ui/node_modules/@types/d3-polygon/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-polygon/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-polygon/README.md b/tools/ui/node_modules/@types/d3-polygon/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f0d8ea6ddb3efbe7c576a6405bbc5dd604210449 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-polygon/README.md @@ -0,0 +1,60 @@ +# Installation +> `npm install --save @types/d3-polygon` + +# Summary +This package contains type definitions for d3-polygon (https://github.com/d3/d3-polygon/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-polygon. +## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-polygon/index.d.ts) +````ts +// Last module patch version validated against: 3.0.1 + +/** + * Returns the signed area of the specified polygon. If the vertices of the polygon are in counterclockwise order + * (assuming a coordinate system where the origin <0,0> is in the top-left corner), the returned area is positive; + * otherwise it is negative, or zero. + * + * @param polygon Array of coordinates , and so on. + */ +export function polygonArea(polygon: Array<[number, number]>): number; + +/** + * Returns the centroid of the specified polygon. + * + * @param polygon Array of coordinates , and so on. + */ +export function polygonCentroid(polygon: Array<[number, number]>): [number, number]; + +/** + * Returns the convex hull of the specified points using Andrew’s monotone chain algorithm. + * The returned hull is represented as an array containing a subset of the input points arranged in + * counterclockwise order. Returns null if points has fewer than three elements. + * + * @param points Array of coordinates , and so on. + */ +export function polygonHull(points: Array<[number, number]>): Array<[number, number]> | null; + +/** + * Returns true if and only if the specified point is inside the specified polygon. + * + * @param polygon Array of coordinates , and so on. + * @param point Coordinates of point . + */ +export function polygonContains(polygon: Array<[number, number]>, point: [number, number]): boolean; + +/** + * Returns the length of the perimeter of the specified polygon. + * + * @param polygon Array of coordinates , and so on. + */ +export function polygonLength(polygon: Array<[number, number]>): number; + +```` + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:37 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-polygon/index.d.ts b/tools/ui/node_modules/@types/d3-polygon/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..56bacdac33e2f1545b93dc02c2dae89e3a66f69a --- /dev/null +++ b/tools/ui/node_modules/@types/d3-polygon/index.d.ts @@ -0,0 +1,41 @@ +// Last module patch version validated against: 3.0.1 + +/** + * Returns the signed area of the specified polygon. If the vertices of the polygon are in counterclockwise order + * (assuming a coordinate system where the origin <0,0> is in the top-left corner), the returned area is positive; + * otherwise it is negative, or zero. + * + * @param polygon Array of coordinates , and so on. + */ +export function polygonArea(polygon: Array<[number, number]>): number; + +/** + * Returns the centroid of the specified polygon. + * + * @param polygon Array of coordinates , and so on. + */ +export function polygonCentroid(polygon: Array<[number, number]>): [number, number]; + +/** + * Returns the convex hull of the specified points using Andrew’s monotone chain algorithm. + * The returned hull is represented as an array containing a subset of the input points arranged in + * counterclockwise order. Returns null if points has fewer than three elements. + * + * @param points Array of coordinates , and so on. + */ +export function polygonHull(points: Array<[number, number]>): Array<[number, number]> | null; + +/** + * Returns true if and only if the specified point is inside the specified polygon. + * + * @param polygon Array of coordinates , and so on. + * @param point Coordinates of point . + */ +export function polygonContains(polygon: Array<[number, number]>, point: [number, number]): boolean; + +/** + * Returns the length of the perimeter of the specified polygon. + * + * @param polygon Array of coordinates , and so on. + */ +export function polygonLength(polygon: Array<[number, number]>): number; diff --git a/tools/ui/node_modules/@types/d3-polygon/package.json b/tools/ui/node_modules/@types/d3-polygon/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bf38832713250f6e858210cfd8a3970228348f1b --- /dev/null +++ b/tools/ui/node_modules/@types/d3-polygon/package.json @@ -0,0 +1,40 @@ +{ + "name": "@types/d3-polygon", + "version": "3.0.2", + "description": "TypeScript definitions for d3-polygon", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-polygon", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-polygon" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "5ed7378dfcd7812d13bc6d39c8ecab60a450c834f215daa96507f03327bc7ca1", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-quadtree/LICENSE b/tools/ui/node_modules/@types/d3-quadtree/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-quadtree/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-quadtree/README.md b/tools/ui/node_modules/@types/d3-quadtree/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a34715e4b1f95353bcea82fc0b82cf730f67b6b1 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-quadtree/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-quadtree` + +# Summary +This package contains type definitions for d3-quadtree (https://github.com/d3/d3-quadtree/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-quadtree. + +### Additional Details + * Last updated: Wed, 22 Nov 2023 00:24:48 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [denisname](https://github.com/denisname), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-quadtree/index.d.ts b/tools/ui/node_modules/@types/d3-quadtree/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..48c9c88b7d7dd9e8892ac399a6f2b1e5804c9ba7 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-quadtree/index.d.ts @@ -0,0 +1,204 @@ +// Last module patch version validated against: 3.0.1 + +/** + * Leaf node of the quadtree. + */ +export interface QuadtreeLeaf { + /** + * The data associated with this point, as passed to quadtree.add. + */ + data: T; + + /** + * The next datum in this leaf, if any. + */ + next?: QuadtreeLeaf | undefined; + + /** + * The length property may be used to distinguish leaf nodes from internal nodes: it is undefined for leaf nodes, and 4 for internal nodes. + */ + length?: undefined; +} + +/** + * Internal nodes of the quadtree are represented as four-element arrays in left-to-right, top-to-bottom order: + * + * 0 - the top-left quadrant, if any. + * 1 - the top-right quadrant, if any. + * 2 - the bottom-left quadrant, if any. + * 3 - the bottom-right quadrant, if any. + * + * A child quadrant may be undefined if it is empty. + */ +export interface QuadtreeInternalNode extends Array | QuadtreeLeaf | undefined> { + /** + * The length property may be used to distinguish leaf nodes from internal nodes: it is undefined for leaf nodes, and 4 for internal nodes. + */ + length: 4; +} + +export interface Quadtree { + /** + * Returns the current x-accessor, which defaults to: `x(d) => d[0]`. + */ + x(): (d: T) => number; + /** + * Sets the current x-coordinate accessor and returns the quadtree. + * The x-accessors must be consistent, returning the same value given the same input. + * + * @param x The x-coordinate accessor. + */ + x(x: (d: T) => number): this; + + /** + * Returns the current y-accessor, which defaults to: `y(d) => d[1]`. + */ + y(): (d: T) => number; + /** + * Sets the current y-coordinate accessor and returns the quadtree. + * The y-accessors must be consistent, returning the same value given the same input. + * + * @param y The y-coordinate accessor. + */ + y(y: (d: T) => number): this; + + /** + * Returns the quadtree's current extent `[[x0, y0], [x1, y1]]`, + * where `x0` and `y0` are the inclusive lower bounds and `x1` and `y1` are the inclusive upper bounds, + * or `undefined` if the quadtree has no extent. + */ + extent(): [[number, number], [number, number]] | undefined; + /** + * Expands the quadtree to cover the specified points `[[x0, y0], [x1, y1]]` and returns the quadtree. + * The extent may also be expanded by calling `quadtree.cover` or `quadtree.add`. + * + * @param extend The specified points to cover. + */ + extent(extend: [[number, number], [number, number]]): this; + + /** + * Expands the quadtree to cover the specified point ⟨x,y⟩, and returns the quadtree. + * * If the quadtree’s extent already covers the specified point, this method does nothing. + * * If the quadtree has an extent, the extent is repeatedly doubled to cover the specified point, wrapping the root node as necessary. + * * If the quadtree is empty, the extent is initialized to the extent `[[⌊x⌋, ⌊y⌋], [⌈x⌉, ⌈y⌉]]`. + * Rounding is necessary such that if the extent is later doubled, the boundaries of existing quadrants do not change due to floating point error. + * + * @param x The x-coordinate for the specified point to cover. + * @param y The y-coordinate for the specified point to cover. + */ + cover(x: number, y: number): this; + + /** + * Adds the specified datum to the quadtree, deriving its coordinates ⟨x,y⟩ using the current x- and y-accessors, and returns the quadtree. + * If the new point is outside the current extent of the quadtree, the quadtree is automatically expanded to cover the new point. + * + * @param datum The specified datum to add. + */ + add(datum: T): this; + + /** + * Adds the specified array of data to the quadtree, deriving each element’s coordinates ⟨x,y⟩ using the current x- and y-accessors, and return this quadtree. + * This is approximately equivalent to calling quadtree.add repeatedly. + * However, this method results in a more compact quadtree because the extent of the data is computed first before adding the data. + * + * @param data The specified array of data to add. + */ + addAll(data: T[]): this; + + /** + * Removes the specified datum to the quadtree, deriving its coordinates ⟨x,y⟩ using the current x- and y-accessors, and returns the quadtree. + * If the specified datum does not exist in this quadtree, this method does nothing. + * + * @param datum The specified datum to remove. + */ + remove(datum: T): this; + + /** + * Removes the specified data to the quadtree, deriving their coordinates ⟨x,y⟩ using the current x- and y-accessors, and returns the quadtree. + * If a specified datum does not exist in this quadtree, it is ignored. + * + * @param data The specified array of data to remove. + */ + removeAll(data: T[]): this; + + /** + * Returns a copy of the quadtree. All nodes in the returned quadtree are identical copies of the corresponding node in the quadtree; + * however, any data in the quadtree is shared by reference and not copied. + */ + copy(): Quadtree; + + /** + * Returns the root node of the quadtree. + */ + root(): QuadtreeInternalNode | QuadtreeLeaf; + + /** + * Returns an array of all data in the quadtree. + */ + data(): T[]; + + /** + * Returns the total number of data in the quadtree. + */ + size(): number; + + /** + * Returns the datum closest to the position ⟨x,y⟩ with the given search radius. If radius is not specified, it defaults to infinity. + * If there is no datum within the search area, returns undefined. + * + * @param x The x-coordinate for the search position. + * @param y The y-coordinate for the search position. + * @param radius The optional search radius. + */ + find(x: number, y: number, radius?: number): T | undefined; + + /** + * Visits each node in the quadtree in pre-order traversal, invoking the specified callback with arguments `node`, `x0`, `y0`, `x1`, `y1` for each node, + * where `node` is the node being visited, ⟨x0, y0⟩ are the lower bounds of the node, and ⟨x1, y1⟩ are the upper bounds, and returns the quadtree. + * + * If the callback returns true for a given node, then the children of that node are not visited; otherwise, all child nodes are visited. + * This can be used to quickly visit only parts of the tree. + * Note, however, that child quadrants are always visited in sibling order: top-left, top-right, bottom-left, bottom-right. + * In cases such as search, visiting siblings in a specific order may be faster. + * + * @param callback The callback invoked for each node. + */ + visit( + callback: ( + node: QuadtreeInternalNode | QuadtreeLeaf, + x0: number, + y0: number, + x1: number, + y1: number, + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + ) => void | boolean, + ): this; + + /** + * Visits each node in the quadtree in post-order traversal, invoking the specified callback with arguments `node`, `x0`, `y0`, `x1`, `y1` for each node, + * where `node` is the node being visited, ⟨x0, y0⟩ are the lower bounds of the node, and ⟨x1, y1⟩ are the upper bounds, and returns the quadtree. + * + * @param callback The callback invoked for each node. + */ + visitAfter( + callback: ( + node: QuadtreeInternalNode | QuadtreeLeaf, + x0: number, + y0: number, + x1: number, + y1: number, + ) => void, + ): this; +} + +/** + * Creates a new, empty quadtree with an empty extent and the default x- and y-accessors. + * If data is specified, adds the specified array of data to the quadtree. + */ +export function quadtree(data?: T[]): Quadtree; +/** + * Creates a new, empty quadtree with an empty extent and the default x- and y-accessors. + * Adds the specified array of data to the quadtree. + * Sets the x- and y- accessors to the specified functions before adding the specified array of data to the quadtree. + */ +export function quadtree(data: T[], x: (d: T) => number, y: (d: T) => number): Quadtree; diff --git a/tools/ui/node_modules/@types/d3-quadtree/package.json b/tools/ui/node_modules/@types/d3-quadtree/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6114c4f2c523a6c53b83f19c91e59451dc8aa84a --- /dev/null +++ b/tools/ui/node_modules/@types/d3-quadtree/package.json @@ -0,0 +1,45 @@ +{ + "name": "@types/d3-quadtree", + "version": "3.0.6", + "description": "TypeScript definitions for d3-quadtree", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-quadtree", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-quadtree" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "25e9fdfd9eb37b9d2cbd957331386544f3b889a4ec48a1c166416492df440709", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-random/LICENSE b/tools/ui/node_modules/@types/d3-random/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-random/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-random/README.md b/tools/ui/node_modules/@types/d3-random/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8bff1b5f82fabfd1c9e4efefc1c5f9899405f153 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-random/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-random` + +# Summary +This package contains type definitions for d3-random (https://github.com/d3/d3-random/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-random. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:37 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-random/index.d.ts b/tools/ui/node_modules/@types/d3-random/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..62eaf44b5c3daf7f4382dfd5d36fd780bc2025d0 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-random/index.d.ts @@ -0,0 +1,312 @@ +// Last module patch version validated against: 3.0.1 + +export interface RandomNumberGenerationSource { + /** + * Returns the same type of function for generating random numbers but where the given random number + * generator source is used as the source of randomness instead of Math.random. + * This is useful when a seeded random number generator is preferable to Math.random. + * + * @param source Source (pseudo-)random number generator implementing the Math.random interface. + * The given random number generator must implement the same interface as Math.random and + * only return values in the range [0, 1). + */ + source(source: () => number): this; +} + +/** + * A configurable random number generator for the uniform distribution. + */ +export interface RandomUniform extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with a uniform distribution. + * The minimum allowed value of a returned number is min (inclusive), and the maximum is max (exclusive). + * Min defaults to 0; if max is not specified, it defaults to 1. + * + * @param max The maximum allowed value of a returned number, defaults to 1. + */ + (max?: number): () => number; + /** + * Returns a function for generating random numbers with a uniform distribution. + * The minimum allowed value of a returned number is min (inclusive), and the maximum is max (exclusive). + * + * @param min The minimum allowed value of a returned number. + * @param max The maximum allowed value of a returned number. + */ + // tslint:disable-next-line:unified-signatures + (min: number, max: number): () => number; +} + +export const randomUniform: RandomUniform; + +/** + * A configurable random integer generator for the uniform distribution. + */ +export interface RandomInt extends RandomNumberGenerationSource { + /** + * Returns a function for generating random integers with a uniform distribution. + * The minimum allowed value of a returned number is ⌊min⌋ (inclusive), and the maximum is ⌊max - 1⌋ (inclusive) + * Min defaults to 0. + * + * @param max The maximum allowed value of a returned number. + */ + (max: number): () => number; + /** + * Returns a function for generating random integers with a uniform distribution. + * The minimum allowed value of a returned number is ⌊min⌋ (inclusive), and the maximum is ⌊max - 1⌋ (inclusive) + * + * @param min The minimum allowed value of a returned number. + * @param max The maximum allowed value of a returned number. + */ + // tslint:disable-next-line:unified-signatures + (min: number, max: number): () => number; +} + +export const randomInt: RandomInt; + +/** + * A configurable random number generator for the normal (Gaussian) distribution. + */ +export interface RandomNormal extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with a normal (Gaussian) distribution. + * The expected value of the generated numbers is mu, with the given standard deviation sigma. + * If mu is not specified, it defaults to 0; if sigma is not specified, it defaults to 1. + * + * @param mu Expected value, defaults to 0. + * @param sigma Standard deviation, defaults to 1. + */ + (mu?: number, sigma?: number): () => number; +} + +export const randomNormal: RandomNormal; + +/** + * A configurable random number generator for the log-normal distribution. + */ +export interface RandomLogNormal extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with a log-normal distribution. The expected value of the random variable’s natural logarithm is mu, + * with the given standard deviation sigma. If mu is not specified, it defaults to 0; if sigma is not specified, it defaults to 1. + * + * @param mu Expected value, defaults to 0. + * @param sigma Standard deviation, defaults to 1. + */ + (mu?: number, sigma?: number): () => number; +} + +export const randomLogNormal: RandomLogNormal; + +/** + * A configurable random number generator for the Bates distribution. + */ +export interface RandomBates extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with a Bates distribution with n independent variables. + * The case of fractional n is handled as with d3.randomIrwinHall, and d3.randomBates(0) is equivalent to d3.randomUniform(). + * + * @param n Number of independent random variables to use. + */ + (n: number): () => number; +} + +export const randomBates: RandomBates; + +/** + * A configurable random number generator for the Irwin–Hall distribution. + */ +export interface RandomIrwinHall extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with an Irwin–Hall distribution with n independent variables. + * If the fractional part of n is non-zero, this is treated as adding d3.randomUniform() times that fractional part to the integral part. + * + * @param n Number of independent random variables to use. + */ + (n: number): () => number; +} + +export const randomIrwinHall: RandomIrwinHall; + +/** + * A configurable random number generator for the exponential distribution. + */ +export interface RandomExponential extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with an exponential distribution with the rate lambda; + * equivalent to time between events in a Poisson process with a mean of 1 / lambda. + * + * @param lambda Expected time between events. + */ + (lambda: number): () => number; +} + +export const randomExponential: RandomExponential; + +/** + * A configurable random number generator with an Pareto distribution. + */ +export interface RandomPareto extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with a Pareto distribution with the shape alpha. + * The value alpha must be a positive value. + * + * @param alpha alpha + */ + (alpha: number): () => number; +} + +export const randomPareto: RandomPareto; + +/** + * A configurable random 0 or 1 generator according to a Bernoulli distribution. + */ +export interface RandomBernoulli extends RandomNumberGenerationSource { + /** + * Returns a function for generating either 1 or 0 according to a Bernoulli distribution with 1 being returned with success probability p and 0 with failure probability q = 1 - p. + * The value p is in the range [0, 1]. + * + * @param p p + */ + (p: number): () => number; +} + +export const randomBernoulli: RandomBernoulli; + +/** + * A configurable random number generator with a geometric distribution. + */ +export interface RandomGeometric extends RandomNumberGenerationSource { + /** + * Returns a function for generating numbers with a geometric distribution with success probability p. + * The value p is in the range [0, 1]. + * + * @param p Success probability + */ + (p: number): () => number; +} + +export const randomGeometric: RandomGeometric; + +/** + * A configurable random number generator with a binomial distribution. + */ +export interface RandomBinomial extends RandomNumberGenerationSource { + /** + * Returns a function for generating numbers with a geometric distribution with success probability p. + * The value p is in the range (0, 1]. + * + * @param p Success probability + */ + (p: number): () => number; +} + +export const randomBinomial: RandomBinomial; + +/** + * A configurable random number generator with a gamma distribution. + */ +export interface RandomGamma extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with a gamma distribution with k the shape parameter and theta the scale parameter. + * The value k must be a positive value; if theta is not specified, it defaults to 1. + * + * @param k Shape parameter + * @param theta Scale paramter + */ + (k: number, theta?: number): () => number; +} + +export const randomGamma: RandomGamma; + +/** + * A configurable random number generator with a beta distribution. + */ +export interface RandomBeta extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with a beta distribution with alpha and beta shape parameters, which must both be positive. + * + * @param alpha Shape parameter + * @param beta Shape paramter + */ + (alpha: number, beta: number): () => number; +} + +export const randomBeta: RandomBeta; + +/** + * A configurable random number generator with one of the generalized extreme value distributions. + */ +export interface RandomWeibull extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with one of the generalized extreme value distributions, depending on k: + * If k is positive, the Weibull distribution with shape parameter k + * If k is zero, the Gumbel distribution + * If k is negative, the Fréchet distribution with shape parameter −k + * In all three cases, a is the location parameter and b is the scale parameter. + * If a is not specified, it defaults to 0; if b is not specified, it defaults to 1. + * + * @param k Shape parameter + * @param a Location parameter + * @param b Scale parameter + */ + (k: number, a?: number, b?: number): () => number; +} + +export const randomWeibull: RandomWeibull; + +/** + * A configurable random number generator with a Cauchy distribution. + */ +export interface RandomCauchy extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with a Cauchy distribution. + * a and b have the same meanings and default values as in d3.randomWeibull. + * + * @param a Location parameter + * @param b Scale parameter + */ + (a?: number, b?: number): () => number; +} + +export const randomCauchy: RandomCauchy; + +/** + * A configurable random number generator with a logistic distribution. + */ +export interface RandomLogistic extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with a logistic distribution. + * a and b have the same meanings and default values as in d3.randomWeibull. + * + * @param a Location parameter + * @param b Scale parameter + */ + (a?: number, b?: number): () => number; +} + +export const randomLogistic: RandomLogistic; + +/** + * A configurable random number generator with a Poisson distribution. + */ +export interface RandomPoisson extends RandomNumberGenerationSource { + /** + * Returns a function for generating random numbers with a Poisson distribution with mean lambda. + * + * @param lambda Mean + */ + (lambda: number): () => number; +} + +export const randomPoisson: RandomPoisson; + +/** + * Returns a linear congruential generator; + * this function can be called repeatedly to obtain pseudorandom values well-distributed on the interval [0,1) and with a long period (up to 1 billion numbers), similar to Math.random. + * A seed can be specified as a real number in the interval [0,1) or as any integer. + * In the latter case, only the lower 32 bits are considered. + * Two generators instanced with the same seed generate the same sequence, allowing to create reproducible pseudo-random experiments. + * If the seed is not specified, one is chosen using Math.random. + * + * @param seed A seed that is either a real number in the interval [0,1) or any integer. + */ +export function randomLcg(seed?: number): () => number; diff --git a/tools/ui/node_modules/@types/d3-random/package.json b/tools/ui/node_modules/@types/d3-random/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9c7efbc5424a3e6756220ea298ea76dc06e726f9 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-random/package.json @@ -0,0 +1,40 @@ +{ + "name": "@types/d3-random", + "version": "3.0.3", + "description": "TypeScript definitions for d3-random", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-random", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-random" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "3804fff17d4569fb17e042ed259189e65562b47c2c7ae06a03ce9c2a9b482c74", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-scale-chromatic/LICENSE b/tools/ui/node_modules/@types/d3-scale-chromatic/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-scale-chromatic/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-scale-chromatic/README.md b/tools/ui/node_modules/@types/d3-scale-chromatic/README.md new file mode 100644 index 0000000000000000000000000000000000000000..76f6e721204b463676d1d1a989503a33219cc308 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-scale-chromatic/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-scale-chromatic` + +# Summary +This package contains type definitions for d3-scale-chromatic (https://github.com/d3/d3-scale-chromatic/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-scale-chromatic. + +### Additional Details + * Last updated: Wed, 27 Nov 2024 21:33:23 GMT + * Dependencies: none + +# Credits +These definitions were written by [Hugues Stefanski](https://github.com/Ledragon), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [Henrique Machado](https://github.com/henriquefm), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-scale-chromatic/index.d.ts b/tools/ui/node_modules/@types/d3-scale-chromatic/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c68f47970c11f6b5ebcef89fe1f5136502e9454a --- /dev/null +++ b/tools/ui/node_modules/@types/d3-scale-chromatic/index.d.ts @@ -0,0 +1,520 @@ +// Last module patch version validated against: 3.0.0 + +// ----------------------------------------------------------------------- +// Categorical +// ----------------------------------------------------------------------- +/** + * An array of ten categorical colors represented as RGB hexadecimal strings. + */ +export const schemeCategory10: readonly string[]; +/** + * An array of eight categorical colors represented as RGB hexadecimal strings. + */ +export const schemeAccent: readonly string[]; +/** + * An array of eight categorical colors represented as RGB hexadecimal strings. + */ +export const schemeDark2: readonly string[]; +/** + * An array of ten categorical colors represented as RGB hexadecimal strings. + */ +export const schemeObservable10: readonly string[]; +/** + * An array of twelve categorical colors represented as RGB hexadecimal strings. + */ +export const schemePaired: readonly string[]; +/** + * An array of nine categorical colors represented as RGB hexadecimal strings. + */ +export const schemePastel1: readonly string[]; +/** + * An array of eight categorical colors represented as RGB hexadecimal strings. + */ +export const schemePastel2: readonly string[]; +/** + * An array of nine categorical colors represented as RGB hexadecimal strings. + */ +export const schemeSet1: readonly string[]; +/** + * An array of eight categorical colors represented as RGB hexadecimal strings. + */ +export const schemeSet2: readonly string[]; +/** + * An array of twelve categorical colors represented as RGB hexadecimal strings. + */ +export const schemeSet3: readonly string[]; +/** + * An array of ten categorical colors authored by Tableau as part of Tableau 10 represented as RGB hexadecimal strings. + */ +export const schemeTableau10: readonly string[]; + +// ----------------------------------------------------------------------- +// Diverging +// ----------------------------------------------------------------------- +/** + * Given a number t in the range [0,1], returns the corresponding color from the “BrBG” diverging color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateBrBG(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “BrBG” diverging color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeBrBG[9] contains an array of nine strings representing the nine colors of the + * brown-blue-green diverging color scheme. Diverging color schemes support a size k ranging from 3 to 11. + */ +export const schemeBrBG: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “PRGn” diverging color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolatePRGn(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “PRGn” diverging color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemePRGn[9] contains an array of nine strings representing the nine colors of the + * purple-green diverging color scheme. Diverging color schemes support a size k ranging from 3 to 11. + */ +export const schemePRGn: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “PiYG” diverging color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolatePiYG(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “PiYG” diverging color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemePiYG[9] contains an array of nine strings representing the nine colors of the + * pink-yellow-green diverging color scheme. Diverging color schemes support a size k ranging from 3 to 11. + */ +export const schemePiYG: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “PuOr” diverging color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolatePuOr(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “PuOr” diverging color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemePuOr[9] contains an array of nine strings representing the nine colors of the + * purple-orange diverging color scheme. Diverging color schemes support a size k ranging from 3 to 11. + */ +export const schemePuOr: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “RdBu” diverging color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateRdBu(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “RdBu” diverging color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeRdBu[9] contains an array of nine strings representing the nine colors of the + * red-blue diverging color scheme. Diverging color schemes support a size k ranging from 3 to 11. + */ +export const schemeRdBu: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “RdGy” diverging color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateRdGy(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “RdGy” diverging color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeRdGy[9] contains an array of nine strings representing the nine colors of the + * red-grey diverging color scheme. Diverging color schemes support a size k ranging from 3 to 11. + */ +export const schemeRdGy: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “RdYlBu” diverging color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateRdYlBu(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “RdYlBu” diverging color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeRdYlBu[9] contains an array of nine strings representing the nine colors of the + * red-yellow-blue diverging color scheme. Diverging color schemes support a size k ranging from 3 to 11. + */ +export const schemeRdYlBu: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “RdYlGn” diverging color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateRdYlGn(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “RdYlGn” diverging color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeRdYlGn[9] contains an array of nine strings representing the nine colors of the + * red-yellow-green diverging color scheme. Diverging color schemes support a size k ranging from 3 to 11. + */ +export const schemeRdYlGn: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “Spectral” diverging color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateSpectral(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “Spectral” diverging color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeSpectral[9] contains an array of nine strings representing the nine colors of the + * spectral diverging color scheme. Diverging color schemes support a size k ranging from 3 to 11. + */ +export const schemeSpectral: ReadonlyArray; + +// ----------------------------------------------------------------------- +// Sequential +// ----------------------------------------------------------------------- +/** + * Given a number t in the range [0,1], returns the corresponding color from the “Blues” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateBlues(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “Blues” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeBlues[9] contains an array of nine strings representing the nine colors of the + * blue sequential color scheme. Sequential, single-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemeBlues: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “Greens” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateGreens(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “Greens” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeGreens[9] contains an array of nine strings representing the nine colors of the + * green sequential color scheme. Sequential, single-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemeGreens: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “Greys” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateGreys(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “Greys” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeGreys[9] contains an array of nine strings representing the nine colors of the + * grey sequential color scheme. Sequential, single-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemeGreys: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “Oranges” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateOranges(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “Oranges” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeOranges[9] contains an array of nine strings representing the nine colors of the + * orange sequential color scheme. Sequential, single-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemeOranges: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “Purples” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolatePurples(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “Purples” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemePurples[9] contains an array of nine strings representing the nine colors of the + * purple sequential color scheme. Sequential, single-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemePurples: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “Reds” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateReds(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “Reds” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeReds[9] contains an array of nine strings representing the nine colors of the + * red sequential color scheme. Sequential, single-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemeReds: ReadonlyArray; + +// ----------------------------------------------------------------------- +// Sequential(Multi-Hue) +// ----------------------------------------------------------------------- + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “turbo” color scheme by Anton Mikhailov. + * + * @param t A number in the interval [0, 1]. + */ +export function interpolateTurbo(t: number): string; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “viridis” perceptually-uniform color scheme designed by van der Walt, Smith and Firing for matplotlib, + * represented as an RGB string. + * + * @param t A number in the interval [0, 1]. + */ +export function interpolateViridis(t: number): string; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “inferno” perceptually-uniform color scheme designed by van der Walt and Smith for matplotlib, + * represented as an RGB string. + * + * @param t A number in the interval [0, 1]. + */ +export function interpolateInferno(t: number): string; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “magma” perceptually-uniform color scheme designed by van der Walt and Smith for matplotlib, + * represented as an RGB string. + * + * @param t A number in the interval [0, 1]. + */ +export function interpolateMagma(t: number): string; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “plasma” perceptually-uniform color scheme designed by van der Walt and Smith for matplotlib, + * represented as an RGB string. + * + * @param t A number in the interval [0, 1]. + */ +export function interpolatePlasma(t: number): string; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “plasma” perceptually-uniform color scheme designed by van der Walt and Smith for matplotlib, + * represented as an RGB string. + * + * @param t A number in the interval [0, 1]. + */ +export function interpolateCividis(t: number): string; + +/** + * Given a number t in the range [0,1], returns the corresponding color from a 180° rotation of Niccoli’s perceptual rainbow, represented as an RGB string. + * + * @param t A number in the interval [0, 1]. + */ +export function interpolateWarm(t: number): string; + +/** + * Given a number t in the range [0,1], returns the corresponding color from Niccoli’s perceptual rainbow, represented as an RGB string. + * + * @param t A number in the interval [0, 1]. + */ +export function interpolateCool(t: number): string; + +/** + * Given a number t in the range [0,1], returns the corresponding color from d3.interpolateWarm scale from [0.0, 0.5] followed by the d3.interpolateCool scale from [0.5, 1.0], + * thus implementing the cyclical less-angry rainbow color scheme. + * + * @param t A number in the interval [0, 1]. + */ +export function interpolateRainbow(t: number): string; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “sinebow” color scheme by Jim Bumgardner and Charlie Loyd. + * + * @param t A number in the interval [0, 1]. + */ +export function interpolateSinebow(t: number): string; + +/** + * Given a number t in the range [0,1], returns the corresponding color from Green’s default Cubehelix represented as an RGB string. + * + * @param t A number in the interval [0, 1]. + */ +export function interpolateCubehelixDefault(t: number): string; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “BuGn” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateBuGn(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “BuGn” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeBuGn[9] contains an array of nine strings representing the nine colors of the + * blue-green sequential color scheme. Sequential, multi-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemeBuGn: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “BuPu” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateBuPu(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “BuPu” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeBuPu[9] contains an array of nine strings representing the nine colors of the + * blue-purple sequential color scheme. Sequential, multi-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemeBuPu: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “GnBu” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateGnBu(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “GnBu” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeGnBu[9] contains an array of nine strings representing the nine colors of the + * green-blue sequential color scheme. Sequential, multi-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemeGnBu: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “OrRd” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateOrRd(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “OrRd” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeOrRd[9] contains an array of nine strings representing the nine colors of the + * orange-red sequential color scheme. Sequential, multi-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemeOrRd: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “PuBuGn” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolatePuBuGn(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “PuBuGn” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemePuBuGn[9] contains an array of nine strings representing the nine colors of the + * purple-blue-green sequential color scheme. Sequential, multi-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemePuBuGn: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “PuBu” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolatePuBu(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “PuBu” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemePuBu[9] contains an array of nine strings representing the nine colors of the + * purple-blue sequential color scheme. Sequential, multi-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemePuBu: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “PuRd” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolatePuRd(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “PuRd” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemePuRd[9] contains an array of nine strings representing the nine colors of the + * purple-red sequential color scheme. Sequential, multi-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemePuRd: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “RdPu” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateRdPu(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “RdPu” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeRdPu[9] contains an array of nine strings representing the nine colors of the + * red-purple sequential color scheme. Sequential, multi-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemeRdPu: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “YlGnBu” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateYlGnBu(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “YlGnBu” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeYlGnBu[9] contains an array of nine strings representing the nine colors of the + * yellow-green-blue sequential color scheme. Sequential, multi-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemeYlGnBu: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “YlGn” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateYlGn(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “YlGn” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeYlGn[9] contains an array of nine strings representing the nine colors of the + * yellow-green sequential color scheme. Sequential, multi-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemeYlGn: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “YlOrBr” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateYlOrBr(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “YlOrBr” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeYlOrBr[9] contains an array of nine strings representing the nine colors of the + * yellow-orange-brown sequential color scheme. Sequential, multi-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemeYlOrBr: ReadonlyArray; + +/** + * Given a number t in the range [0,1], returns the corresponding color from the “YlOrRd” sequential color scheme represented as an RGB string. + * + * @param t Number in the range [0, 1]. + */ +export function interpolateYlOrRd(t: number): string; + +/** + * An array of arrays of hexadecimal color strings from the “YlOrRd” sequential color scheme. The kth element of this array contains + * the color scheme of size k; for example, d3.schemeYlOrRd[9] contains an array of nine strings representing the nine colors of the + * yellow-orange-red sequential color scheme. Sequential, multi-hue color schemes support a size k ranging from 3 to 9. + */ +export const schemeYlOrRd: ReadonlyArray; diff --git a/tools/ui/node_modules/@types/d3-scale-chromatic/package.json b/tools/ui/node_modules/@types/d3-scale-chromatic/package.json new file mode 100644 index 0000000000000000000000000000000000000000..51ea7c2c474189539f5286c1e00b88fac70ce829 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-scale-chromatic/package.json @@ -0,0 +1,46 @@ +{ + "name": "@types/d3-scale-chromatic", + "version": "3.1.0", + "description": "TypeScript definitions for d3-scale-chromatic", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-scale-chromatic", + "license": "MIT", + "contributors": [ + { + "name": "Hugues Stefanski", + "githubUsername": "Ledragon", + "url": "https://github.com/Ledragon" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "Henrique Machado", + "githubUsername": "henriquefm", + "url": "https://github.com/henriquefm" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-scale-chromatic" + }, + "scripts": {}, + "dependencies": {}, + "peerDependencies": {}, + "typesPublisherContentHash": "5f5a24a3b0c02b7fa88b0169f2a5e3b4f87588aaa6adfeeec24625d740748355", + "typeScriptVersion": "5.0" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-scale/LICENSE b/tools/ui/node_modules/@types/d3-scale/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-scale/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-scale/README.md b/tools/ui/node_modules/@types/d3-scale/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f462893cac76bae7c99457c950852da380bff99e --- /dev/null +++ b/tools/ui/node_modules/@types/d3-scale/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-scale` + +# Summary +This package contains type definitions for d3-scale (https://github.com/d3/d3-scale/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-scale. + +### Additional Details + * Last updated: Wed, 05 Feb 2025 00:46:59 GMT + * Dependencies: [@types/d3-time](https://npmjs.com/package/@types/d3-time) + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [denisname](https://github.com/denisname), [rulonder](https://github.com/rulonder), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-scale/index.d.ts b/tools/ui/node_modules/@types/d3-scale/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f0bc6fe45e40ba7879374488bf335ed30a3d2b6b --- /dev/null +++ b/tools/ui/node_modules/@types/d3-scale/index.d.ts @@ -0,0 +1,2669 @@ +// Last module patch version validated against: 4.0.2 + +import { CountableTimeInterval, TimeInterval } from "d3-time"; + +// ------------------------------------------------------------------------------- +// Shared Types and Interfaces +// ------------------------------------------------------------------------------- + +/** + * An Interpolator factory returns an interpolator function. + * + * The first generic corresponds to the data type of the interpolation boundaries. + * The second generic corresponds to the data type of the return type of the interpolator. + */ +export interface InterpolatorFactory { + /** + * Construct a new interpolator function, based on the provided interpolation boundaries. + * + * @param a Start boundary of the interpolation interval. + * @param b End boundary of the interpolation interval. + */ + (a: T, b: T): (t: number) => U; +} + +export type NumberValue = number | { valueOf(): number }; + +export type UnknownReturnType = [Unknown] extends [never] ? DefaultUnknown : Unknown; + +/** + * A helper interface for a continuous scale defined over a numeric domain. + */ +export interface ScaleContinuousNumeric { + /** + * Given a value from the domain, returns the corresponding value from the range, subject to interpolation, if any. + * + * If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range. + * + * Note: The interpolation function applied by the scale may change the output type from the range type as part of the interpolation. + * + * @param value A numeric value from the domain. + */ + (value: NumberValue): Output | Unknown; + + /** + * Given a value from the range, returns the corresponding value from the domain. Inversion is useful for interaction, + * say to determine the data value corresponding to the position of the mouse. + * + * If the given value is outside the range, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the domain. + * + * IMPORTANT: This method is only supported if the range is numeric. If the range is not numeric, returns NaN. + * + * For a valid value y in the range, continuous(continuous.invert(y)) approximately equals y; + * similarly, for a valid value x in the domain, continuous.invert(continuous(x)) approximately equals x. + * The scale and its inverse may not be exact due to the limitations of floating point precision. + * + * @param value A numeric value from the range. + */ + invert(value: NumberValue): number; + + /** + * Returns a copy of the scale’s current domain. + */ + domain(): number[]; + /** + * Sets the scale’s domain to the specified array of numbers. The array must contain two or more elements. + * If the elements in the given array are not numbers, they will be coerced to numbers + * + * Although continuous scales typically have two values each in their domain and range, specifying more than two values produces a piecewise scale. + * + * Internally, a piecewise scale performs a binary search for the range interpolator corresponding to the given domain value. + * Thus, the domain must be in ascending or descending order. If the domain and range have different lengths N and M, only the first min(N,M) elements in each are observed. + * + * @param domain Array of numeric domain values. + */ + domain(domain: Iterable): this; + + /** + * Returns a copy of the scale’s current range. + */ + range(): Range[]; + /** + * Sets the scale’s range to the specified array of values. + * + * The array must contain two or more elements. Unlike the domain, elements in the given array need not be numbers; + * any value that is supported by the underlying interpolator will work, though note that numeric ranges are required for invert. + * + * @param range Array of range values. + */ + range(range: Iterable): this; + + /** + * Sets the scale’s range to the specified array of values while also setting the scale’s interpolator to interpolateRound. + * + * The rounding interpolator is sometimes useful for avoiding antialiasing artifacts, + * though also consider the shape-rendering “crispEdges” styles. Note that this interpolator can only be used with numeric ranges. + * + * The array must contain two or more elements. Unlike the domain, elements in the given array need not be numbers; + * any value that is supported by the underlying interpolator will work, though note that numeric ranges are required for invert. + * + * @param range Array of range values. + */ + rangeRound(range: Iterable): this; + + /** + * Returns whether or not the scale currently clamps values to within the range. + */ + clamp(): boolean; + /** + * Enables or disables clamping, respectively. If clamping is disabled and the scale is passed a value outside the domain, + * the scale may return a value outside the range through extrapolation. + * + * If clamping is enabled, the return value of the scale is always within the scale’s range. Clamping similarly applies to the "invert" method. + * + * @param clamp A flag to enable (true) or disable (false) clamping. + */ + clamp(clamp: boolean): this; + + /** + * Returns approximately count representative values from the scale’s domain. + * + * If count is not specified, it defaults to 10. + * + * The returned tick values are uniformly spaced, have human-readable values (such as multiples of powers of 10), + * and are guaranteed to be within the extent of the domain. Ticks are often used to display reference lines, or tick marks, in conjunction with the visualized data. + * The specified count is only a hint; the scale may return more or fewer values depending on the domain. See also d3-array’s ticks. + * + * @param count Optional approximate number of ticks to be returned. If count is not specified, it defaults to 10. + */ + ticks(count?: number): number[]; + + /** + * Returns a number format function suitable for displaying a tick value, automatically computing the appropriate precision based on the fixed interval between tick values. + * The specified count should have the same value as the count that is used to generate the tick values. + * + * @param count Approximate number of ticks to be used when calculating precision for the number format function. + * @param specifier An optional valid format specifier string which allows a custom format where the precision of the format is automatically set by the scale as appropriate for the tick interval. + * If specifier uses the format type "s", the scale will return a SI-prefix format based on the largest value in the domain. + * If the specifier already specifies a precision, this method is equivalent to locale.format. + */ + tickFormat(count?: number, specifier?: string): (d: NumberValue) => string; + + /** + * Extends the domain so that it starts and ends on nice round values. + * This method typically modifies the scale’s domain, and may only extend the bounds to the nearest round value. + * An optional tick count argument allows greater control over the step size used to extend the bounds, + * guaranteeing that the returned ticks will exactly cover the domain. + * Nicing is useful if the domain is computed from data, say using extent, and may be irregular. + * For example, for a domain of [0.201479…, 0.996679…], a nice domain might be [0.2, 1.0]. + * If the domain has more than two values, nicing the domain only affects the first and last value. + * + * Nicing a scale only modifies the current domain; it does not automatically nice domains that are subsequently set using continuous.domain. + * You must re-nice the scale after setting the new domain, if desired. + * + * @param count An optional number of ticks expected to be used. + */ + nice(count?: number): this; + + /** + * Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa. + */ + copy(): this; +} + +/** + * Returns a number format function suitable for displaying a tick value, + * automatically computing the appropriate precision based on the fixed interval between tick values, as determined by d3.tickStep. + * + * @param start Start + * @param stop Stop + * @param count Approximate number of ticks to be used when calculating precision for the number format function. + * @param specifier An optional specifier allows a custom format where the precision of the format is automatically set by the scale as appropriate for the tick interval. + * If specifier uses the format type s, the scale will return a SI-prefix format based on the larger absolute value of start and stop. + * If the specifier already specifies a precision, this method is equivalent to locale.format. + */ +export function tickFormat(start: number, stop: number, count: number, specifier?: string): (d: NumberValue) => string; + +// ------------------------------------------------------------------------------- +// Linear Scale Factory +// ------------------------------------------------------------------------------- + +/** + * A linear continuous scale defined over a numeric domain. + * + * Continuous scales map a continuous, quantitative input domain to a continuous output range. + * Each range value y can be expressed as a function of the domain value x: y = mx + b. + * + * If the range is also numeric, the mapping may be inverted. + * + * Note that the data types of the range and output of the scale must be compatible with the interpolator applied by the scale. + * + * The first generic corresponds to the data type of the range elements. + * + * The second generic corresponds to the data type of the output elements generated by the scale. + * + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + */ +export interface ScaleLinear extends ScaleContinuousNumeric { + /** + * Returns the scale’s current interpolator factory, which defaults to interpolate. + */ + interpolate(): InterpolatorFactory; + + /** + * Sets the scale’s range interpolator factory. This interpolator factory is used to create interpolators for each adjacent pair of values from the range; + * these interpolators then map a normalized domain parameter t in [0, 1] to the corresponding value in the range. + * + * Note: the default interpolator may reuse return values. For example, if the range values are objects, then the value interpolator always returns the same object, modifying it in-place. + * If the scale is used to set an attribute or style, this is typically acceptable (and desirable for performance); + * however, if you need to store the scale’s return value, you must specify your own interpolator or make a copy as appropriate. + * + * As part of the interpolation process the interpolated value from the range may be converted to a corresponding output value. + * + * @param interpolate An interpolation factory. The generics for Range and Output of the scale must correspond to the interpolation factory applied to the scale. + */ + interpolate(interpolate: InterpolatorFactory): this; + /** + * Sets the scale’s range interpolator factory. This interpolator factory is used to create interpolators for each adjacent pair of values from the range; + * these interpolators then map a normalized domain parameter t in [0, 1] to the corresponding value in the range. + * + * Note: the default interpolator may reuse return values. For example, if the range values are objects, then the value interpolator always returns the same object, modifying it in-place. + * If the scale is used to set an attribute or style, this is typically acceptable (and desirable for performance); + * however, if you need to store the scale’s return value, you must specify your own interpolator or make a copy as appropriate. + * + * As part of the interpolation process the interpolated value from the range may be converted to a corresponding output value. + * + * The generic "NewOutput" can be used to change the scale to have a different output element type corresponding to the new interpolation factory. + * + * @param interpolate An interpolation factory. The generics for Range and Output of the scale must correspond to the interpolation factory applied to the scale. + */ + interpolate(interpolate: InterpolatorFactory): ScaleLinear; + + /** + * Returns the current unknown value, which defaults to undefined. + */ + unknown(): UnknownReturnType; + /** + * Sets the output value of the scale for undefined (or NaN) input values and returns this scale. + * + * @param value The output value of the scale for undefined (or NaN) input values. + */ + unknown(value: NewUnknown): ScaleLinear; +} + +/** + * Constructs a new continuous scale with the specified range, the default interpolator and clamping disabled. + * The domain defaults to [0, 1]. + * If range is not specified, it defaults to [0, 1]. + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the output elements generated by the scale. + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + * + * The range must be set in accordance with the range element type. + * + * The interpolator factory may be set using the interpolate(...) method of the scale. + * + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleLinear( + range?: Iterable, +): ScaleLinear; +/** + * Constructs a new continuous scale with the specified domain and range, the default interpolator and clamping disabled. + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the output elements generated by the scale. + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + * + * The range must be set in accordance with the range element type. + * + * The interpolator factory may be set using the interpolate(...) method of the scale. + * + * @param domain Array of numeric domain values. + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleLinear( + domain: Iterable, + range: Iterable, +): ScaleLinear; + +// ------------------------------------------------------------------------------- +// Power Scale Factories +// ------------------------------------------------------------------------------- + +/** + * A continuous power scale defined over a numeric domain. + * + * Continuous scales map a continuous, quantitative input domain to a continuous output range. + * + * Each range value y can be expressed as a function of the domain value x: y = mx^k + b, where k is the exponent value. + * Power scales also support negative domain values, in which case the input value and the resulting output value are multiplied by -1. + * + * If the range is also numeric, the mapping may be inverted. + * + * Note that the data types of the range and output of the scale must be compatible with the interpolator applied by the scale. + * + * The first generic corresponds to the data type of the range elements. + * + * The second generic corresponds to the data type of the output elements generated by the scale. + * + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + */ +export interface ScalePower extends ScaleContinuousNumeric { + /** + * Returns the scale’s current interpolator factory, which defaults to interpolate. + */ + interpolate(): InterpolatorFactory; + + /** + * Sets the scale’s range interpolator factory. This interpolator factory is used to create interpolators for each adjacent pair of values from the range; + * these interpolators then map a normalized domain parameter t in [0, 1] to the corresponding value in the range. + * + * Note: the default interpolator may reuse return values. For example, if the range values are objects, then the value interpolator always returns the same object, modifying it in-place. + * If the scale is used to set an attribute or style, this is typically acceptable (and desirable for performance); + * however, if you need to store the scale’s return value, you must specify your own interpolator or make a copy as appropriate. + * + * As part of the interpolation process the interpolated value from the range may be converted to a corresponding output value. + * + * @param interpolate An interpolation factory. The generics for Range and Output of the scale must correspond to the interpolation factory applied to the scale. + */ + interpolate(interpolate: InterpolatorFactory): this; + /** + * Sets the scale’s range interpolator factory. This interpolator factory is used to create interpolators for each adjacent pair of values from the range; + * these interpolators then map a normalized domain parameter t in [0, 1] to the corresponding value in the range. + * + * Note: the default interpolator may reuse return values. For example, if the range values are objects, then the value interpolator always returns the same object, modifying it in-place. + * If the scale is used to set an attribute or style, this is typically acceptable (and desirable for performance); + * however, if you need to store the scale’s return value, you must specify your own interpolator or make a copy as appropriate. + * + * As part of the interpolation process the interpolated value from the range may be converted to a corresponding output value. + * + * The generic "NewOutput" can be used to change the scale to have a different output element type corresponding to the new interpolation factory. + * + * @param interpolate An interpolation factory. The generics for Range and Output of the scale must correspond to the interpolation factory applied to the scale. + */ + interpolate(interpolate: InterpolatorFactory): ScalePower; + + /** + * If exponent is not specified, returns the current exponent, which defaults to 1. + * (Note that this is effectively a linear scale until you set a different exponent.) + */ + exponent(): number; + /** + * Sets the current exponent to the given numeric value. + * (Note that this is effectively a linear scale until you set a different exponent.) + */ + exponent(exponent: number): this; + + /** + * Returns the current unknown value, which defaults to undefined. + */ + unknown(): UnknownReturnType; + /** + * Sets the output value of the scale for undefined (or NaN) input values and returns this scale. + * + * @param value The output value of the scale for undefined (or NaN) input values. + */ + unknown(value: NewUnknown): ScalePower; +} + +/** + * Constructs a new continuous scale with the specified range, the exponent 1, the default interpolator and clamping disabled. + * The domain defaults to [0, 1]. + * If range is not specified, it defaults to [0, 1]. + * (Note that this is effectively a linear scale until you set a different exponent.) + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the output elements generated by the scale. + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + * + * The range must be set in accordance with the range element type. + * + * The interpolator factory may be set using the interpolate(...) method of the scale. + * + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scalePow( + range?: Iterable, +): ScalePower; +/** + * Constructs a new continuous scale with the specified domain and range, the exponent 1, the default interpolator and clamping disabled. + * (Note that this is effectively a linear scale until you set a different exponent.) + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the output elements generated by the scale. + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + * + * The range must be set in accordance with the range element type. + * + * The interpolator factory may be set using the interpolate(...) method of the scale. + * + * @param domain Array of numeric domain values. + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scalePow( + domain: Iterable, + range: Iterable, +): ScalePower; + +/** + * Constructs a new continuous power scale with the specified range, the exponent 0.5, the default interpolator and clamping disabled. + * The domain defaults to [0, 1]. + * If range is not specified, it defaults to [0, 1]. + * This is a convenience method equivalent to d3.scalePow().exponent(0.5). + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the output elements generated by the scale. + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + * + * The range must be set in accordance with the range element type. + * + * The interpolator factory may be set using the interpolate(...) method of the scale. + * + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleSqrt( + range?: Iterable, +): ScalePower; +/** + * Constructs a new continuous power scale with the specified domain and range, the exponent 0.5, the default interpolator and clamping disabled. + * This is a convenience method equivalent to d3.scalePow().exponent(0.5). + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the output elements generated by the scale. + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + * + * The range must be set in accordance with the range element type. + * + * The interpolator factory may be set using the interpolate(...) method of the scale. + * + * @param domain Array of numeric domain values. + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleSqrt( + domain: Iterable, + range: Iterable, +): ScalePower; + +// ------------------------------------------------------------------------------- +// Logarithmic Scale Factory +// ------------------------------------------------------------------------------- + +/** + * A continuous logarithmic scale defined over a numeric domain. + * + * Continuous scales map a continuous, quantitative input domain to a continuous output range. + * + * The mapping to the range value y can be expressed as a function of the domain value x: y = m log(x) + b. + * + * As log(0) = -∞, a log scale domain must be strictly-positive or strictly-negative; the domain must not include or cross zero. + * A log scale with a positive domain has a well-defined behavior for positive values, and a log scale with a negative domain has a well-defined behavior for negative values. + * (For a negative domain, input and output values are implicitly multiplied by -1.) + * The behavior of the scale is undefined if you pass a negative value to a log scale with a positive domain or vice versa. + * + * If the range is also numeric, the mapping may be inverted. + * + * Note that the data types of the range and output of the scale must be compatible with the interpolator applied by the scale. + * + * The first generic corresponds to the data type of the range elements. + * + * The second generic corresponds to the data type of the output elements generated by the scale. + * + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + */ +export interface ScaleLogarithmic + extends ScaleContinuousNumeric +{ + /** + * Returns a copy of the scale’s current domain. + */ + domain(): number[]; + /** + * Sets the scale’s domain to the specified array of numbers. The array must contain two or more elements. + * If the elements in the given array are not numbers, they will be coerced to numbers + * + * As log(0) = -∞, a log scale domain must be strictly-positive or strictly-negative; the domain must not include or cross zero. + * A log scale with a positive domain has a well-defined behavior for positive values, and a log scale with a negative domain has a well-defined behavior for negative values. + * (For a negative domain, input and output values are implicitly multiplied by -1.) + * The behavior of the scale is undefined if you pass a negative value to a log scale with a positive domain or vice versa. + * + * Although continuous scales typically have two values each in their domain and range, specifying more than two values produces a piecewise scale. + * + * Internally, a piecewise scale performs a binary search for the range interpolator corresponding to the given domain value. + * Thus, the domain must be in ascending or descending order. If the domain and range have different lengths N and M, only the first min(N,M) elements in each are observed. + * + * @param domain Array of numeric domain values. + */ + domain(domain: Iterable): this; + + /** + * Returns the scale’s current interpolator factory, which defaults to interpolate. + */ + interpolate(): InterpolatorFactory; + + /** + * Sets the scale’s range interpolator factory. This interpolator factory is used to create interpolators for each adjacent pair of values from the range; + * these interpolators then map a normalized domain parameter t in [0, 1] to the corresponding value in the range. + * + * Note: the default interpolator may reuse return values. For example, if the range values are objects, then the value interpolator always returns the same object, modifying it in-place. + * If the scale is used to set an attribute or style, this is typically acceptable (and desirable for performance); + * however, if you need to store the scale’s return value, you must specify your own interpolator or make a copy as appropriate. + * + * As part of the interpolation process the interpolated value from the range may be converted to a corresponding output value. + * + * @param interpolate An interpolation factory. The generics for Range and Output of the scale must correspond to the interpolation factory applied to the scale. + */ + interpolate(interpolate: InterpolatorFactory): this; + /** + * Sets the scale’s range interpolator factory. This interpolator factory is used to create interpolators for each adjacent pair of values from the range; + * these interpolators then map a normalized domain parameter t in [0, 1] to the corresponding value in the range. + * + * Note: the default interpolator may reuse return values. For example, if the range values are objects, then the value interpolator always returns the same object, modifying it in-place. + * If the scale is used to set an attribute or style, this is typically acceptable (and desirable for performance); + * however, if you need to store the scale’s return value, you must specify your own interpolator or make a copy as appropriate. + * + * As part of the interpolation process the interpolated value from the range may be converted to a corresponding output value. + * + * The generic "NewOutput" can be used to change the scale to have a different output element type corresponding to the new interpolation factory. + * + * @param interpolate An interpolation factory. The generics for Range and Output of the scale must correspond to the interpolation factory applied to the scale. + */ + interpolate( + interpolate: InterpolatorFactory, + ): ScaleLogarithmic; + + /** + * Returns approximately count representative values from the scale’s domain. + * + * If count is not specified, it defaults to 10. + * + * If the base is an integer, the returned ticks are uniformly spaced within each integer power of base; otherwise, one tick per power of base is returned. + * The returned ticks are guaranteed to be within the extent of the domain. If the orders of magnitude in the domain is greater than count, then at most one tick per power is returned. + * Otherwise, the tick values are unfiltered, but note that you can use log.tickFormat to filter the display of tick labels. + * + * @param count Optional approximate number of ticks to be returned. If count is not specified, it defaults to 10. + */ + ticks(count?: number): number[]; + + /** + * Returns a number format function suitable for displaying a tick value, automatically computing the appropriate precision based on the fixed interval between tick values. + * + * The specified count typically has the same value as the count that is used to generate the tick values. + * If there are too many ticks, the formatter may return the empty string for some of the tick labels; + * however, note that the ticks are still shown. + * To disable filtering, specify a count of Infinity. When specifying a count, you may also provide a format specifier or format function. + * For example, to get a tick formatter that will display 20 ticks of a currency, say log.tickFormat(20, "$,f"). + * If the specifier does not have a defined precision, the precision will be set automatically by the scale, returning the appropriate format. + * This provides a convenient way of specifying a format whose precision will be automatically set by the scale. + * + * @param count Approximate number of ticks to be used when calculating precision for the number format function. + * @param specifier An optional valid format specifier string which allows a custom format where the precision of the format is automatically set by the scale as appropriate for the tick interval. + * For example, to get a tick formatter that will display 20 ticks of a currency, say log.tickFormat(20, "$,f"). + * If the specifier does not have a defined precision, the precision will be set automatically by the scale, returning the appropriate format. + * This provides a convenient way of specifying a format whose precision will be automatically set by the scale. + */ + tickFormat(count?: number, specifier?: string): (d: NumberValue) => string; + + /** + * Extends the domain to integer powers of base. For example, for a domain of [0.201479…, 0.996679…], and base 10, the nice domain is [0.1, 1]. + * If the domain has more than two values, nicing the domain only affects the first and last value. + * + * Nicing a scale only modifies the current domain; it does not automatically nice domains that are subsequently set using continuous.domain. + * You must re-nice the scale after setting the new domain, if desired. + */ + nice(): this; + + /** + * Returns the current base, which defaults to 10. + */ + base(): number; + /** + * Sets the base for this logarithmic scale to the specified value. + */ + base(base: number): this; + + /** + * Returns the current unknown value, which defaults to undefined. + */ + unknown(): UnknownReturnType; + /** + * Sets the output value of the scale for undefined (or NaN) input values and returns this scale. + * + * @param value The output value of the scale for undefined (or NaN) input values. + */ + unknown(value: NewUnknown): ScaleLogarithmic; +} + +/** + * Constructs a new continuous scale with the specified range, the base 10, the default interpolator and clamping disabled. + * The domain defaults to [1, 10]. + * If range is not specified, it defaults to [0, 1]. + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the output elements generated by the scale. + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + * + * The range must be set in accordance with the range element type. + * + * The interpolator factory may be set using the interpolate(...) method of the scale. + * + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleLog( + range?: Iterable, +): ScaleLogarithmic; +/** + * Constructs a new continuous scale with the specified domain and range, the base 10, the default interpolator and clamping disabled. + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the output elements generated by the scale. + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + * + * The range must be set in accordance with the range element type. + * + * The interpolator factory may be set using the interpolate(...) method of the scale. + * + * @param domain Array of numeric domain values. + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleLog( + domain: Iterable, + range: Iterable, +): ScaleLogarithmic; + +// ------------------------------------------------------------------------------- +// Symlog Scale Factory +// ------------------------------------------------------------------------------- + +/** + * A bi-symmetric log transformation for wide-range data by Webber scale defined over a numeric domain. + * + * Continuous scales map a continuous, quantitative input domain to a continuous output range. + * + * See “A bi-symmetric log transformation for wide-range data” by Webber for more + * + * If the range is also numeric, the mapping may be inverted. + * + * Note that the data types of the range and output of the scale must be compatible with the interpolator applied by the scale. + * + * The first generic corresponds to the data type of the range elements. + * + * The second generic corresponds to the data type of the output elements generated by the scale. + * + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + */ +export interface ScaleSymLog extends ScaleContinuousNumeric { + /** + * Returns a number format function suitable for displaying a tick value, automatically computing the appropriate precision based on the fixed interval between tick values. + * + * The specified count typically has the same value as the count that is used to generate the tick values. + * If there are too many ticks, the formatter may return the empty string for some of the tick labels; + * however, note that the ticks are still shown. + * To disable filtering, specify a count of Infinity. When specifying a count, you may also provide a format specifier or format function. + * For example, to get a tick formatter that will display 20 ticks of a currency, say log.tickFormat(20, "$,f"). + * If the specifier does not have a defined precision, the precision will be set automatically by the scale, returning the appropriate format. + * This provides a convenient way of specifying a format whose precision will be automatically set by the scale. + * + * @param count Approximate number of ticks to be used when calculating precision for the number format function. + * @param specifier An optional valid format specifier string which allows a custom format where the precision of the format is automatically set by the scale as appropriate for the tick interval. + * For example, to get a tick formatter that will display 20 ticks of a currency, say log.tickFormat(20, "$,f"). + * If the specifier does not have a defined precision, the precision will be set automatically by the scale, returning the appropriate format. + * This provides a convenient way of specifying a format whose precision will be automatically set by the scale. + */ + tickFormat(count?: number, specifier?: string): (d: NumberValue) => string; + /** + * Returns the current constant, which defaults to 1. + */ + constant(): number; + /** + * Sets the symlog constant to the specified number and returns this scale; + * otherwise returns the current value of the symlog constant, which defaults to 1. See “A bi-symmetric log transformation for wide-range data” by Webber for more. + */ + constant(constant: number): this; + + /** + * Returns the current unknown value, which defaults to undefined. + */ + unknown(): UnknownReturnType; + /** + * Sets the output value of the scale for undefined (or NaN) input values and returns this scale. + * + * @param value The output value of the scale for undefined (or NaN) input values. + */ + unknown(value: NewUnknown): ScaleSymLog; +} + +/** + * Constructs a new continuous scale with the specified range, the constant 1, the default interpolator and clamping disabled. + * The domain defaults to [0, 1]. + * If range is not specified, it defaults to [0, 1]. + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the output elements generated by the scale. + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + * + * The range must be set in accordance with the range element type. + * + * The interpolator factory may be set using the interpolate(...) method of the scale. + * + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleSymlog( + range?: Iterable, +): ScaleSymLog; +/** + * Constructs a new continuous scale with the specified domain and range, the constant 1, the default interpolator and clamping disabled. + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the output elements generated by the scale. + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + * + * The range must be set in accordance with the range element type. + * + * The interpolator factory may be set using the interpolate(...) method of the scale. + * + * @param domain Array of numeric domain values. + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleSymlog( + domain: Iterable, + range: Iterable, +): ScaleSymLog; + +// ------------------------------------------------------------------------------- +// Identity Scale Factory +// ------------------------------------------------------------------------------- + +/** + * Identity scales are a special case of linear scales where the domain and range are identical; the scale and its invert method are thus the identity function. + * These scales are occasionally useful when working with pixel coordinates, say in conjunction with an axis. + * + * The generic corresponds to the data type of the unknown value. + */ +export interface ScaleIdentity { + /** + * Given a value from the domain, returns the corresponding value from the range, subject to interpolation, if any. + * + * If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range. + * + * Note: The interpolation function applied by the scale may change the output type from the range type as part of the interpolation. + * + * @param value A numeric value from the domain. + */ + (value: NumberValue): number | Unknown; + + /** + * Given a value from the range, returns the corresponding value from the domain. Inversion is useful for interaction, + * say to determine the data value corresponding to the position of the mouse. + * + * If the given value is outside the range, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the domain. + * + * IMPORTANT: This method is only supported if the range is numeric. If the range is not numeric, returns NaN. + * + * For a valid value y in the range, continuous(continuous.invert(y)) approximately equals y; + * similarly, for a valid value x in the domain, continuous.invert(continuous(x)) approximately equals x. + * The scale and its inverse may not be exact due to the limitations of floating point precision. + * + * @param value A numeric value from the range. + */ + invert(value: NumberValue): number; + + /** + * Returns a copy of the scale’s current domain. + */ + domain(): number[]; + /** + * Sets the scale’s domain to the specified array of numbers. The array must contain two or more elements. + * If the elements in the given array are not numbers, they will be coerced to numbers + * + * Although continuous scales typically have two values each in their domain and range, specifying more than two values produces a piecewise scale. + * + * Internally, a piecewise scale performs a binary search for the range interpolator corresponding to the given domain value. + * Thus, the domain must be in ascending or descending order. If the domain and range have different lengths N and M, only the first min(N,M) elements in each are observed. + * + * @param domain Array of numeric domain values. + */ + domain(domain: Iterable): this; + + /** + * Returns a copy of the scale’s current range. + */ + range(): number[]; + /** + * Sets the scale’s range to the specified array of values. + * + * The array must contain two or more elements. Unlike the domain, elements in the given array need not be numbers; + * any value that is supported by the underlying interpolator will work, though note that numeric ranges are required for invert. + * + * @param range Array of range values. + */ + range(range: Iterable): this; + + /** + * Returns approximately count representative values from the scale’s domain. + * + * If count is not specified, it defaults to 10. + * + * The returned tick values are uniformly spaced, have human-readable values (such as multiples of powers of 10), + * and are guaranteed to be within the extent of the domain. Ticks are often used to display reference lines, or tick marks, in conjunction with the visualized data. + * The specified count is only a hint; the scale may return more or fewer values depending on the domain. See also d3-array’s ticks. + * + * @param count Optional approximate number of ticks to be returned. If count is not specified, it defaults to 10. + */ + ticks(count?: number): number[]; + + /** + * Returns a number format function suitable for displaying a tick value, automatically computing the appropriate precision based on the fixed interval between tick values. + * The specified count should have the same value as the count that is used to generate the tick values. + * + * @param count Approximate number of ticks to be used when calculating precision for the number format function. + * @param specifier An optional valid format specifier string which allows a custom format where the precision of the format is automatically set by the scale as appropriate for the tick interval. + * If specifier uses the format type "s", the scale will return a SI-prefix format based on the largest value in the domain. + * If the specifier already specifies a precision, this method is equivalent to locale.format. + */ + tickFormat(count?: number, specifier?: string): (d: NumberValue) => string; + + /** + * Extends the domain so that it starts and ends on nice round values. + * This method typically modifies the scale’s domain, and may only extend the bounds to the nearest round value. + * An optional tick count argument allows greater control over the step size used to extend the bounds, + * guaranteeing that the returned ticks will exactly cover the domain. + * Nicing is useful if the domain is computed from data, say using extent, and may be irregular. + * For example, for a domain of [0.201479…, 0.996679…], a nice domain might be [0.2, 1.0]. + * If the domain has more than two values, nicing the domain only affects the first and last value. + * + * Nicing a scale only modifies the current domain; it does not automatically nice domains that are subsequently set using continuous.domain. + * You must re-nice the scale after setting the new domain, if desired. + * + * @param count An optional number of ticks expected to be used. + */ + nice(count?: number): this; + + /** + * Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa. + */ + copy(): this; + + /** + * Returns the current unknown value, which defaults to undefined. + */ + unknown(): UnknownReturnType; + /** + * Sets the output value of the scale for undefined (or NaN) input values and returns this scale. + * + * @param value The output value of the scale for undefined (or NaN) input values. + */ + unknown(value: NewUnknown): ScaleIdentity; +} + +/** + * Constructs a new identity scale with the specified domain and range. + * If range is not specified, it defaults to [0, 1]. + * + * The generic corresponds to the data type of the unknown value. + * + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleIdentity(range?: Iterable): ScaleIdentity; + +// ------------------------------------------------------------------------------- +// Radial Scale Factory +// ------------------------------------------------------------------------------- + +export interface ScaleRadial extends ScaleContinuousNumeric { + /** + * Returns the current unknown value, which defaults to undefined. + */ + unknown(): UnknownReturnType; + /** + * Sets the output value of the scale for undefined (or NaN) input values and returns this scale. + * + * @param value The output value of the scale for undefined (or NaN) input values. + */ + unknown(value: NewUnknown): ScaleRadial; +} + +/** + * Constructs a new radial scale with the specified range. + * The domain defaults to [0, 1]. + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the unknown value. + * + * The range must be set in accordance with the range element type. + * + * @param range Iterable of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleRadial( + range?: Iterable, +): ScaleRadial; +/** + * Constructs a new radial scale with the specified domain and range. + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the unknown value. + * + * The range must be set in accordance with the range element type. + * + * @param domain Iterable of numeric domain values. + * @param range Iterable of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleRadial( + domain: Iterable, + range: Iterable, +): ScaleRadial; + +// ------------------------------------------------------------------------------- +// Time Scale Factories +// ------------------------------------------------------------------------------- + +/** + * A linear scale defined over a temporal domain. + * + * Time scales implement ticks based on calendar intervals, taking the pain out of generating axes for temporal domains. + * + * If the range is numeric, the mapping may be inverted to return a date. + * + * Note that the data types of the range and output of the scale must be compatible with the interpolator applied by the scale. + * + * The first generic corresponds to the data type of the range elements. + * + * The second generic corresponds to the data type of the output elements generated by the scale. + * + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + */ +export interface ScaleTime { + /** + * Given a value from the domain, returns the corresponding value from the range, subject to interpolation, if any. + * + * If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range. + * + * Note: The interpolation function applied by the scale may change the output type from the range type as part of the interpolation. + * + * @param value A temporal value from the domain. If the value is not a Date, it will be coerced to Date. + */ + (value: Date | NumberValue): Output | Unknown; + + /** + * Given a value from the range, returns the corresponding value from the domain. Inversion is useful for interaction, + * say to determine the data value corresponding to the position of the mouse. + * + * If the given value is outside the range, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the domain. + * + * IMPORTANT: This method is only supported if the range is numeric. If the range is not numeric, returns Invalid Date. + * + * For a valid value y in the range, time(time.invert(y)) equals y; similarly, for a valid value x in the domain, time.invert(time(x)) equals x. + * The invert method is useful for interaction, say to determine the value in the domain that corresponds to the pixel location under the mouse. + * + * @param value A numeric value from the range. + */ + invert(value: NumberValue): Date; + + /** + * Returns a copy of the scale’s current domain. + */ + domain(): Date[]; + + /** + * Sets the scale’s domain to the specified array of temporal domain values. The array must contain two or more elements. + * If the elements in the given array are not dates, they will be coerced to dates. + * + * Although continuous scales typically have two values each in their domain and range, specifying more than two values produces a piecewise scale. + * + * Internally, a piecewise scale performs a binary search for the range interpolator corresponding to the given domain value. + * Thus, the domain must be in ascending or descending order. If the domain and range have different lengths N and M, only the first min(N,M) elements in each are observed. + * + * @param domain Array of temporal domain values. Numeric values will be coerced to dates. + */ + domain(domain: Iterable): this; + + /** + * Returns a copy of the scale’s current range. + */ + range(): Range[]; + /** + * Sets the scale’s range to the specified array of values. + * + * The array must contain two or more elements. Unlike the domain, elements in the given array need not be temporal domain values; + * any value that is supported by the underlying interpolator will work, though note that numeric ranges are required for invert. + * + * @param range Array of range values. + */ + range(range: Iterable): this; + + /** + * Sets the scale’s range to the specified array of values while also setting the scale’s interpolator to interpolateRound. + * + * The rounding interpolator is sometimes useful for avoiding antialiasing artifacts, + * though also consider the shape-rendering “crispEdges” styles. Note that this interpolator can only be used with numeric ranges. + * + * The array must contain two or more elements. Unlike the domain, elements in the given array need not be temporal domain values; + * any value that is supported by the underlying interpolator will work, though note that numeric ranges are required for invert. + * + * @param range Array of range values. + */ + rangeRound(range: Iterable): this; + + /** + * Returns whether or not the scale currently clamps values to within the range. + */ + clamp(): boolean; + /** + * Enables or disables clamping, respectively. If clamping is disabled and the scale is passed a value outside the domain, + * the scale may return a value outside the range through extrapolation. + * + * If clamping is enabled, the return value of the scale is always within the scale’s range. Clamping similarly applies to the "invert" method. + * + * @param clamp A flag to enable (true) or disable (false) clamping. + */ + clamp(clamp: boolean): this; + + /** + * Returns the scale’s current interpolator factory, which defaults to interpolate. + */ + interpolate(): InterpolatorFactory; + + /** + * Sets the scale’s range interpolator factory. This interpolator factory is used to create interpolators for each adjacent pair of values from the range; + * these interpolators then map a normalized domain parameter t in [0, 1] to the corresponding value in the range. + * + * Note: the default interpolator may reuse return values. For example, if the range values are objects, then the value interpolator always returns the same object, modifying it in-place. + * If the scale is used to set an attribute or style, this is typically acceptable (and desirable for performance); + * however, if you need to store the scale’s return value, you must specify your own interpolator or make a copy as appropriate. + * + * As part of the interpolation process the interpolated value from the range may be converted to a corresponding output value. + * + * @param interpolate An interpolation factory. The generics for Range and Output of the scale must correspond to the interpolation factory applied to the scale. + */ + interpolate(interpolate: InterpolatorFactory): this; + /** + * Sets the scale’s range interpolator factory. This interpolator factory is used to create interpolators for each adjacent pair of values from the range; + * these interpolators then map a normalized domain parameter t in [0, 1] to the corresponding value in the range. + * + * Note: the default interpolator may reuse return values. For example, if the range values are objects, then the value interpolator always returns the same object, modifying it in-place. + * If the scale is used to set an attribute or style, this is typically acceptable (and desirable for performance); + * however, if you need to store the scale’s return value, you must specify your own interpolator or make a copy as appropriate. + * + * As part of the interpolation process the interpolated value from the range may be converted to a corresponding output value. + * + * The generic "NewOutput" can be used to change the scale to have a different output element type corresponding to the new interpolation factory. + * + * @param interpolate An interpolation factory. The generics for Range and Output of the scale must correspond to the interpolation factory applied to the scale. + */ + interpolate(interpolate: InterpolatorFactory): ScaleTime; + + /** + * Returns representative dates from the scale’s domain. The returned tick values are uniformly-spaced (mostly), + * have sensible values (such as every day at midnight), and are guaranteed to be within the extent of the domain. + * Ticks are often used to display reference lines, or tick marks, in conjunction with the visualized data. + * + * An optional count may be specified to affect how many ticks are generated. If count is not specified, it defaults to 10. + * The specified count is only a hint; the scale may return more or fewer values depending on the domain. + * + * @param count Expected number of ticks. + */ + ticks(count?: number): Date[]; + /** + * Returns representative dates from the scale’s domain. The returned tick values are uniformly-spaced (mostly), + * have sensible values (such as every day at midnight), and are guaranteed to be within the extent of the domain. + * Ticks are often used to display reference lines, or tick marks, in conjunction with the visualized data. + * + * The specified time interval controls the ticks generated and returned. To prune the generated ticks for a given time interval, + * use interval.every(...) or interval.filter(...). + * + * @param interval A time interval to specify the expected ticks. + */ + ticks(interval: TimeInterval): Date[]; + + /** + * Returns a time format function suitable for displaying tick values. + * + * The default multi-scale time format chooses a human-readable representation based on the specified date as follows: + * + * - %Y - for year boundaries, such as 2011. + * - %B - for month boundaries, such as February. + * - %b %d - for week boundaries, such as Feb 06. + * - %a %d - for day boundaries, such as Mon 07. + * - %I %p - for hour boundaries, such as 01 AM. + * - %I:%M - for minute boundaries, such as 01:23. + * - :%S - for second boundaries, such as :45. + * - .%L - milliseconds for all other times, such as .012. + * + * Although somewhat unusual, this default behavior has the benefit of providing both local and global context: + * for example, formatting a sequence of ticks as [11 PM, Mon 07, 01 AM] reveals information about hours, dates, and day simultaneously, + * rather than just the hours [11 PM, 12 AM, 01 AM]. + * + * The specified count is currently ignored, but is accepted for consistency with other scales such as continuous.tickFormat. + * + * @param count Expected number of ticks. (Currently ignored) + * @param specifier An optional valid date format specifier string (see d3-time-format). + */ + tickFormat(count?: number, specifier?: string): (d: Date) => string; + /** + * Returns a time format function suitable for displaying tick values. + * + * The specified time interval is currently ignored, but is accepted for consistency with other scales such as continuous.tickFormat. + * + * @param interval A time interval to specify the expected ticks. (Currently ignored) + * @param specifier An optional valid date format specifier string (see d3-time-format). + */ + tickFormat(interval: TimeInterval, specifier?: string): (d: Date) => string; + + /** + * Extends the domain so that it starts and ends on nice round values. + * This method typically modifies the scale’s domain, and may only extend the bounds to the nearest round value. + * + * An optional count argument allows greater control over the step size used to extend the bounds, guaranteeing that the returned ticks will exactly cover the domain. + * + * Nicing is useful if the domain is computed from data, say using extent, and may be irregular. + * For example, for a domain of [2009-07-13T00:02, 2009-07-13T23:48], the nice domain is [2009-07-13, 2009-07-14]. + * If the domain has more than two values, nicing the domain only affects the first and last value. + * + * @param count Expected number of ticks. + */ + nice(count?: number): this; + /** + * Extends the domain so that it starts and ends on nice round values. + * This method typically modifies the scale’s domain, and may only extend the bounds to the nearest round value. + * + * A time interval may be specified to explicitly set the ticks. + * If an interval is specified, an optional step may also be specified to skip some ticks. + * For example, time.nice(d3.timeSecond.every(10)) will extend the domain to an even ten seconds (0, 10, 20, etc.). + * See time.ticks and interval.every for further detail. + * + * Nicing is useful if the domain is computed from data, say using extent, and may be irregular. + * For example, for a domain of [2009-07-13T00:02, 2009-07-13T23:48], the nice domain is [2009-07-13, 2009-07-14]. + * If the domain has more than two values, nicing the domain only affects the first and last value. + * + * @param interval A time interval to specify the expected ticks. + */ + nice(interval: CountableTimeInterval): this; + + /** + * Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa. + */ + copy(): this; + + /** + * Returns the current unknown value, which defaults to undefined. + */ + unknown(): UnknownReturnType; + /** + * Sets the output value of the scale for undefined (or NaN) input values and returns this scale. + * + * @param value The output value of the scale for undefined (or NaN) input values. + */ + unknown(value: NewUnknown): ScaleTime; +} + +/** + * Constructs a new time scale with the specified range, the default interpolator and clamping disabled. + * The domain defaults to [2000-01-01, 2000-01-02]. + * If range is not specified, it defaults to [0, 1]. + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the output elements generated by the scale. + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + * + * The range must be set in accordance with the range element type. + * + * The interpolator factory may be set using the interpolate(...) method of the scale. + * + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleTime( + range?: Iterable, +): ScaleTime; +/** + * Constructs a new time scale with the specified domain and range, the default interpolator and clamping disabled. + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the output elements generated by the scale. + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + * + * The range must be set in accordance with the range element type. + * + * The interpolator factory may be set using the interpolate(...) method of the scale. + * + * @param domain Array of temporal domain values. Numeric values will be coerced to dates. + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleTime( + domain: Iterable, + range: Iterable, +): ScaleTime; + +/** + * Constructs a new time scale using Coordinated Universal Time (UTC) with the specified range, the default interpolator and clamping disabled. + * The domain defaults to [2000-01-01, 2000-01-02]. + * If range is not specified, it defaults to [0, 1]. + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the output elements generated by the scale. + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + * + * The range must be set in accordance with the range element type. + * + * The interpolator factory may be set using the interpolate(...) method of the scale. + * + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleUtc( + range?: Iterable, +): ScaleTime; +/** + * Constructs a new time scale using Coordinated Universal Time (UTC) with the specified domain and range, the default interpolator and clamping disabled. + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the output elements generated by the scale. + * The third generic corresponds to the data type of the unknown value. + * + * If range element and output element type differ, the interpolator factory used with the scale must match this behavior and + * convert the interpolated range element to a corresponding output element. + * + * The range must be set in accordance with the range element type. + * + * The interpolator factory may be set using the interpolate(...) method of the scale. + * + * @param domain Array of temporal domain values. Numeric values will be coerced to dates. + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleUtc( + domain: Iterable, + range: Iterable, +): ScaleTime; + +// ------------------------------------------------------------------------------- +// Sequential Scale Factory +// ------------------------------------------------------------------------------- + +/** + * Sequential scales are similar to continuous scales in that they map a continuous, numeric input domain to a continuous output range. + * However, unlike continuous scales, the input domain and output range of a sequential scale always has exactly two elements, + * and the output range is typically specified as an interpolator rather than an array of values. + * These scales do not expose invert and interpolate methods. + * + * The first generic corresponds to the data type of the output of the interpolator underlying the scale. + * + * The second generic corresponds to the data type of the unknown value. + */ +export interface ScaleSequentialBase { + /** + * Given a value from the domain, returns the corresponding value from the output range, subject to interpolation. + * + * If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range. + * + * @param value A numeric value from the domain. + */ + (value: NumberValue): Output | Unknown; + + /** + * Returns a copy of the scale’s current domain. + */ + domain(): [number, number]; + /** + * Sets the scale’s domain to the specified array of numbers. The array must contain exactly two elements. + * If the elements in the given array are not numbers, they will be coerced to numbers + * + * @param domain A two-element array of numeric domain values. + */ + domain(domain: Iterable): this; + + /** + * Returns whether or not the scale currently clamps values to within the range. + */ + clamp(): boolean; + /** + * Enables or disables clamping, respectively. If clamping is disabled and the scale is passed a value outside the domain, + * the scale may return a value outside the range through extrapolation. + * + * If clamping is enabled, the return value of the scale is always within the scale’s range. Clamping similarly applies to the "invert" method. + * + * @param clamp A flag to enable (true) or disable (false) clamping. + */ + clamp(clamp: boolean): this; + + /** + * See continuous.range. + */ + range(): [Output, Output]; + /** + * See continuous.range. + * The given two-element array is converted to an interpolator function using d3.interpolate. + * + * @param range Range values. + */ + range(range: Iterable): this; + + /** + * See continuous.rangeRound. + * If range is specified, implicitly uses d3.interpolateRound as the interpolator. + * + * @param range Range values. + */ + rangeRound(range: Iterable): this; + + /** + * Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa. + */ + copy(): this; +} + +export interface ScaleSequential extends ScaleSequentialBase { + /** + * Returns the current interpolator underlying the scale. + */ + interpolator(): (t: number) => Output; + /** + * Sets the scale’s interpolator to the specified function. + * + * @param interpolator An interpolator function mapping a value from the [0, 1] interval to an output value. + */ + interpolator(interpolator: (t: number) => Output): this; + /** + * Sets the scale’s interpolator to the specified function. + * + * The generic corresponds to a the new output type of the scale. The output type of the scale is determined by the output type of the interpolator function. + * + * @param interpolator An interpolator function mapping a value from the [0, 1] interval to an output value. + */ + interpolator(interpolator: (t: number) => NewOutput): ScaleSequential; + + /** + * Returns the current unknown value, which defaults to undefined. + */ + unknown(): UnknownReturnType; + /** + * Sets the output value of the scale for undefined (or NaN) input values and returns this scale. + * + * @param value The output value of the scale for undefined (or NaN) input values. + */ + unknown(value: NewUnknown): ScaleSequential; +} + +/** + * Constructs a new sequential scale with the specified interpolator function or array. + * The domain defaults to [0, 1]. + * If interpolator is not specified, it defaults to the identity function. + * When the scale is applied, the interpolator will be invoked with a value typically in the range [0, 1], where 0 represents the minimum value and 1 represents the maximum value. + * + * If interpolator is an array, it represents the scale’s two-element output range and is converted to an interpolator function using d3.interpolate. + * + * The first generic corresponds to the data type of the output of the interpolator underlying the scale. + * The second generic corresponds to the data type of the unknown value. + * + * @param interpolator The interpolator function or array to be used with the scale. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleSequential( + interpolator?: ((t: number) => Output) | Iterable, +): ScaleSequential; +/** + * Constructs a new sequential scale with the specified domain and interpolator function or array. + * When the scale is applied, the interpolator will be invoked with a value typically in the range [0, 1], where 0 represents the minimum value and 1 represents the maximum value. + * + * If interpolator is an array, it represents the scale’s two-element output range and is converted to an interpolator function using d3.interpolate. + * + * The first generic corresponds to the data type of the output of the interpolator underlying the scale. + * The second generic corresponds to the data type of the unknown value. + * + * @param domain A two-element array of numeric domain values. + * @param interpolator The interpolator function or array to be used with the scale. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleSequential( + domain: Iterable, + interpolator: ((t: number) => Output) | Iterable, +): ScaleSequential; + +/** + * A sequential scale with a logarithmic transform, analogous to a log scale. + * + * The first generic corresponds to the data type of the output of the interpolator underlying the scale. + * The second generic corresponds to the data type of the unknown value. + * + * @param interpolator The interpolator function to be used with the scale. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleSequentialLog( + interpolator?: (t: number) => Output, +): ScaleSequential; +/** + * A sequential scale with a logarithmic transform, analogous to a log scale. + * + * The first generic corresponds to the data type of the output of the interpolator underlying the scale. + * The second generic corresponds to the data type of the unknown value. + * + * @param domain A two-element array of numeric domain values. + * @param interpolator The interpolator function to be used with the scale. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleSequentialLog( + domain: Iterable, + interpolator: (t: number) => Output, +): ScaleSequential; + +/** + * A sequential scale with a exponential transform, analogous to a power scale. + * + * The first generic corresponds to the data type of the output of the interpolator underlying the scale. + * The second generic corresponds to the data type of the unknown value. + * + * @param interpolator The interpolator function to be used with the scale. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleSequentialPow( + interpolator?: (t: number) => Output, +): ScaleSequential; +/** + * A sequential scale with a exponential transform, analogous to a power scale. + * + * The first generic corresponds to the data type of the output of the interpolator underlying the scale. + * The second generic corresponds to the data type of the unknown value. + * + * @param domain A two-element array of numeric domain values. + * @param interpolator The interpolator function to be used with the scale. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleSequentialPow( + domain: Iterable, + interpolator: (t: number) => Output, +): ScaleSequential; + +/** + * A sequential scale with a square-root transform, analogous to a d3.scaleSqrt. + * + * The first generic corresponds to the data type of the output of the interpolator underlying the scale. + * The second third generic corresponds to the data type of the unknown value. + * + * @param interpolator The interpolator function to be used with the scale. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleSequentialSqrt( + interpolator?: (t: number) => Output, +): ScaleSequential; +/** + * A sequential scale with a square-root transform, analogous to a d3.scaleSqrt. + * + * The first generic corresponds to the data type of the output of the interpolator underlying the scale. + * The second generic corresponds to the data type of the unknown value. + * + * @param domain A two-element array of numeric domain values. + * @param interpolator The interpolator function to be used with the scale. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleSequentialSqrt( + domain: Iterable, + interpolator: (t: number) => Output, +): ScaleSequential; + +/** + * A sequential scale with a symmetric logarithmic transform, analogous to a symlog scale. + * + * The first generic corresponds to the data type of the output of the interpolator underlying the scale. + * The second generic corresponds to the data type of the unknown value. + * + * @param interpolator The interpolator function to be used with the scale. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleSequentialSymlog( + interpolator?: (t: number) => Output, +): ScaleSequential; +/** + * A sequential scale with a symmetric logarithmic transform, analogous to a symlog scale. + * + * The first generic corresponds to the data type of the output of the interpolator underlying the scale. + * The second generic corresponds to the data type of the unknown value. + * + * @param domain A two-element array of numeric domain values. + * @param interpolator The interpolator function to be used with the scale. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleSequentialSymlog( + domain: Iterable, + interpolator: (t: number) => Output, +): ScaleSequential; + +export interface ScaleSequentialQuantile extends ScaleSequentialBase { + /** + * Returns an array of n + 1 quantiles. + * For example, if n = 4, returns an array of five numbers: the minimum value, the first quartile, the median, the third quartile, and the maximum. + */ + quantiles(): number[]; + + /** + * Returns the current interpolator underlying the scale. + */ + interpolator(): (t: number) => Output; + /** + * Sets the scale’s interpolator to the specified function. + * + * @param interpolator An interpolator function mapping a value from the [0, 1] interval to an output value. + */ + interpolator(interpolator: (t: number) => Output): this; + /** + * Sets the scale’s interpolator to the specified function. + * + * The generic corresponds to a the new output type of the scale. The output type of the scale is determined by the output type of the interpolator function. + * + * @param interpolator An interpolator function mapping a value from the [0, 1] interval to an output value. + */ + interpolator(interpolator: (t: number) => NewOutput): ScaleSequentialQuantile; + + /** + * Returns the current unknown value, which defaults to undefined. + */ + unknown(): UnknownReturnType; + /** + * Sets the output value of the scale for undefined (or NaN) input values and returns this scale. + * + * @param value The output value of the scale for undefined (or NaN) input values. + */ + unknown(value: NewUnknown): ScaleSequentialQuantile; +} + +/** + * A sequential scale using a p-quantile transform, analogous to a quantile scale. + * + * The first generic corresponds to the data type of the output of the interpolator underlying the scale. + * The second generic corresponds to the data type of the unknown value. + * + * @param interpolator The interpolator function to be used with the scale. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleSequentialQuantile( + interpolator?: (t: number) => Output, +): ScaleSequentialQuantile; +/** + * A sequential scale using a p-quantile transform, analogous to a quantile scale. + * + * The first generic corresponds to the data type of the output of the interpolator underlying the scale. + * The second generic corresponds to the data type of the unknown value. + * + * @param domain A two-element array of numeric domain values. + * @param interpolator The interpolator function to be used with the scale. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleSequentialQuantile( + domain: Iterable, + interpolator: (t: number) => Output, +): ScaleSequentialQuantile; + +// ------------------------------------------------------------------------------- +// Diverging Scale Factory +// ------------------------------------------------------------------------------- + +/** + * Diverging scales, like sequential scales, are similar to continuous scales in that they map a continuous, numeric input domain to a continuous output range. + * However, unlike continuous scales, the input domain and output range of a diverging scale always has exactly three elements, + * and the output range is typically specified as an interpolator rather than an array of values. + * These scales do not expose invert and interpolate methods. + * + * The first generic corresponds to the data type of the interpolator return type. + * + * The second generic corresponds to the data type of the unknown value. + */ +export interface ScaleDiverging { + /** + * Given a value from the domain, returns the corresponding value subject to interpolation. + * + * If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range. + * + * @param value A numeric value from the domain. + */ + (value: NumberValue): Output | Unknown; + + /** + * Returns a copy of the scale’s current domain. + */ + domain(): [number, number, number]; + /** + * Sets the scale’s domain to the specified array of numbers. + * The domain must be numeric and must contain exactly three values. The default domain is [0, 0.5, 1]. + * If the elements in the given array are not numbers, they will be coerced to numbers + * + * @param domain Array of three numeric domain values. + */ + domain(domain: Iterable): this; + + /** + * Returns whether or not the scale currently clamps values to within the range. + */ + clamp(): boolean; + /** + * Enables or disables clamping, respectively. If clamping is disabled and the scale is passed a value outside the domain, + * the scale may return a value outside the range through extrapolation. + * + * If clamping is enabled, the return value of the scale is always within the interpolator scale’s range. + * + * @param clamp A flag to enable (true) or disable (false) clamping. + */ + clamp(clamp: boolean): this; + + /** + * Returns the scale’s current interpolator. + */ + interpolator(): (t: number) => Output; + /** + * Sets the scale’s interpolator to the specified function. + * + * @param interpolator The scale’s interpolator. + */ + interpolator(interpolator?: (t: number) => Output): this; + + /** + * See continuous.range. + */ + range(): [Output, Output, Output]; + /** + * See continuous.range. + * The given two-element array is converted to an interpolator function using d3.interpolate and d3.piecewise. + * + * @param range Range values. + */ + range(range: Iterable): this; + + /** + * See continuous.rangeRound. + * If range is specified, implicitly uses d3.interpolateRound as the interpolator. + * + * @param range Range values. + */ + rangeRound(range: Iterable): this; + + /** + * Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa. + */ + copy(): this; + + /** + * Returns the current unknown value, which defaults to undefined. + */ + unknown(): UnknownReturnType; + /** + * Sets the output value of the scale for undefined (or NaN) input values and returns this scale. + * + * @param value The output value of the scale for undefined (or NaN) input values. + */ + unknown(value: NewUnknown): ScaleDiverging; +} + +/** + * Constructs a new diverging scale with the specified interpolator function or array. + * The domain defaults to [0, 0.5, 1]. + * If interpolator is not specified, it defaults to the identity function. + * When the scale is applied, the interpolator will be invoked with a value typically in the range [0, 1], + * where 0 represents the extreme negative value, 0.5 represents the neutral value, and 1 represents the extreme positive value. + * + * If interpolator is an array, it represents the scale’s three-element output range and is converted to an interpolator function using d3.interpolate and d3.piecewise. + * + * The first generic corresponds to the data type of the interpolator return type. + * The second generic corresponds to the data type of the unknown value. + * + * @param interpolator The scale’s interpolator function or array. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleDiverging( + interpolator?: ((t: number) => Output) | Iterable, +): ScaleDiverging; +/** + * Constructs a new diverging scale with the specified domain and interpolator function or array. + * When the scale is applied, the interpolator will be invoked with a value typically in the range [0, 1], + * where 0 represents the extreme negative value, 0.5 represents the neutral value, and 1 represents the extreme positive value. + * + * If interpolator is an array, it represents the scale’s three-element output range and is converted to an interpolator function using d3.interpolate and d3.piecewise. + * + * The first generic corresponds to the data type of the interpolator return type. + * The second generic corresponds to the data type of the unknown value. + * + * @param domain Array of three numeric domain values. + * @param interpolator The scale’s interpolator function or array. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleDiverging( + domain: Iterable, + interpolator: ((t: number) => Output) | Iterable, +): ScaleDiverging; + +/** + * A diverging scale with a logarithmic transform, analogous to a log scale. + * + * The first generic corresponds to the data type of the interpolator return type. + * The second generic corresponds to the data type of the unknown value. + * + * @param interpolator The scale’s interpolator. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleDivergingLog( + interpolator?: (t: number) => Output, +): ScaleDiverging; +/** + * A diverging scale with a logarithmic transform, analogous to a log scale. + * + * The first generic corresponds to the data type of the interpolator return type. + * The second generic corresponds to the data type of the unknown value. + * + * @param domain Array of three numeric domain values. + * @param interpolator The scale’s interpolator. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleDivergingLog( + domain: Iterable, + interpolator: (t: number) => Output, +): ScaleDiverging; + +/** + * A diverging scale with a exponential transform, analogous to a power scale. + * + * The first generic corresponds to the data type of the interpolator return type. + * The second generic corresponds to the data type of the unknown value. + * + * @param interpolator The scale’s interpolator. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleDivergingPow( + interpolator?: (t: number) => Output, +): ScaleDiverging; +/** + * A diverging scale with a exponential transform, analogous to a power scale. + * + * The first generic corresponds to the data type of the interpolator return type. + * The second generic corresponds to the data type of the unknown value. + * + * @param domain Array of three numeric domain values. + * @param interpolator The scale’s interpolator. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleDivergingPow( + domain: Iterable, + interpolator: (t: number) => Output, +): ScaleDiverging; + +/** + * A diverging scale with a square-root transform, analogous to a d3.scaleSqrt. + * + * The first generic corresponds to the data type of the interpolator return type. + * The second generic corresponds to the data type of the unknown value. + * + * @param interpolator The scale’s interpolator. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleDivergingSqrt( + interpolator?: (t: number) => Output, +): ScaleDiverging; +/** + * A diverging scale with a square-root transform, analogous to a d3.scaleSqrt. + * + * The first generic corresponds to the data type of the interpolator return type. + * The second generic corresponds to the data type of the unknown value. + * + * @param domain Array of three numeric domain values. + * @param interpolator The scale’s interpolator. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleDivergingSqrt( + domain: Iterable, + interpolator: (t: number) => Output, +): ScaleDiverging; + +/** + * A diverging scale with a symmetric logarithmic transform, analogous to a symlog scale. + * + * The first generic corresponds to the data type of the interpolator return type. + * The second generic corresponds to the data type of the unknown value. + * + * @param interpolator The scale’s interpolator. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleDivergingSymlog( + interpolator?: (t: number) => Output, +): ScaleDiverging; +/** + * A diverging scale with a symmetric logarithmic transform, analogous to a symlog scale. + * + * The first generic corresponds to the data type of the interpolator return type. + * The second generic corresponds to the data type of the unknown value. + * + * @param domain Array of three numeric domain values. + * @param interpolator The scale’s interpolator. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleDivergingSymlog( + domain: Iterable, + interpolator: (t: number) => Output, +): ScaleDiverging; + +// ------------------------------------------------------------------------------- +// Quantize Scale Factory +// ------------------------------------------------------------------------------- + +/** + * Quantize scales are similar to linear scales, except they use a discrete rather than continuous range. + * The continuous input domain is divided into uniform segments based on the number of values in (i.e., the cardinality of) the output range. + * + * Each range value y can be expressed as a quantized linear function of the domain value x: y = m round(x) + b. + * + * The first generic corresponds to the data type of the range elements. + * + * The second generic corresponds to the data type of the unknown value. + */ +export interface ScaleQuantize { + /** + * Given a value in the input domain, returns the corresponding value in the output range. + */ + (value: NumberValue): Range | Unknown; + /** + * Returns the extent of values in the domain [x0, x1] for the corresponding value in the range: the inverse of quantize. + * This method is useful for interaction, say to determine the value in the domain that corresponds to the pixel location under the mouse. + * + * If an invalid range value is entered, returns [NaN, NaN]. + * + * @param value A value from the range. + */ + invertExtent(value: Range): [number, number]; + + /** + * Returns the scale’s current domain. + */ + domain(): [number, number]; + + /** + * Sets the scale’s domain to the specified two-element array of numbers. + * If the elements in the given array are not numbers, they will be coerced to numbers. + * + * @param domain A two-element array of numeric values defining the domain. + */ + domain(domain: Iterable): this; + + /** + * Returns the scale’s current range. + */ + range(): Range[]; + /** + * Sets the scale’s range to the specified array of values. The array may contain any number of discrete values. + * + * @param range Array of range values. + */ + range(range: Iterable): this; + + /** + * Returns approximately count representative values from the scale’s domain. + * + * If count is not specified, it defaults to 10. + * + * The returned tick values are uniformly spaced, have human-readable values (such as multiples of powers of 10), + * and are guaranteed to be within the extent of the domain. Ticks are often used to display reference lines, or tick marks, in conjunction with the visualized data. + * The specified count is only a hint; the scale may return more or fewer values depending on the domain. See also d3-array’s ticks. + * + * @param count Optional approximate number of ticks to be returned. If count is not specified, it defaults to 10. + */ + ticks(count?: number): number[]; + + /** + * Returns a number format function suitable for displaying a tick value, automatically computing the appropriate precision based on the fixed interval between tick values. + * The specified count should have the same value as the count that is used to generate the tick values. + * + * @param count Approximate number of ticks to be used when calculating precision for the number format function. + * @param specifier An optional valid format specifier string which allows a custom format where the precision of the format is automatically set by the scale as appropriate for the tick interval. + * If specifier uses the format type "s", the scale will return a SI-prefix format based on the largest value in the domain. + * If the specifier already specifies a precision, this method is equivalent to locale.format. + */ + tickFormat(count?: number, specifier?: string): (d: NumberValue) => string; + + /** + * Extends the domain so that it starts and ends on nice round values. + * This method typically modifies the scale’s domain, and may only extend the bounds to the nearest round value. + * + * Nicing is useful if the domain is computed from data, say using extent, and may be irregular. + * For example, for a domain of [0.201479…, 0.996679…], a nice domain might be [0.2, 1.0]. + * + * Nicing a scale only modifies the current domain; it does not automatically nice domains that are subsequently set using continuous.domain. + * You must re-nice the scale after setting the new domain, if desired. + * + * @param count An optional number of ticks expected to be used. + */ + nice(count?: number): this; + + /** + * Returns the current unknown value, which defaults to undefined. + */ + unknown(): UnknownReturnType; + /** + * Sets the output value of the scale for undefined (or NaN) input values and returns this scale. + * + * @param value The output value of the scale for undefined (or NaN) input values. + */ + unknown(value: NewUnknown): ScaleQuantize; + + /** + * Returns the array of computed thresholds within the domain. + */ + thresholds(): number[]; + + /** + * Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa. + */ + copy(): this; +} + +/** + * Constructs a new quantize scale with the specified range. + * The domain defaults to [0, 1]. + * If range is not specified, it defaults to [0, 1]. + * Thus, the default quantize scale is equivalent to the Math.round function. + * + * The range must be set corresponding to the type of the range elements. + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the unknown value. + * + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleQuantize(range?: Iterable): ScaleQuantize; +/** + * Constructs a new quantize scale with the specified domain and range. + * Thus, the default quantize scale is equivalent to the Math.round function. + * + * The range must be set corresponding to the type of the range elements. + * + * The first generic corresponds to the data type of the range elements. + * The second generic corresponds to the data type of the unknown value. + * + * @param domain A two-element array of numeric values defining the domain. + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleQuantize( + domain: Iterable, + range: Iterable, +): ScaleQuantize; + +// ------------------------------------------------------------------------------- +// Quantile Scale Factory +// ------------------------------------------------------------------------------- + +/** + * Quantile scales map a sampled input domain to a discrete range. + * The domain is considered continuous and thus the scale will accept any reasonable input value; + * however, the domain is specified as a discrete set of sample values. + * The number of values in (the cardinality of) the output range determines the number of quantiles that will be computed from the domain. + * To compute the quantiles, the domain is sorted, and treated as a population of discrete values; see d3-array’s quantile. + * + * The first generic corresponds to the data type of range elements. + * + * The second generic corresponds to the data type of the unknown value. + */ +export interface ScaleQuantile { + /** + * Given a value in the input domain, returns the corresponding value in the output range. + * + * @param value A numeric value in the input domain. + */ + (value: NumberValue): Range | Unknown; + + /** + * Returns the extent of values in the domain [x0, x1] for the corresponding value in the range: the inverse of quantile. + * This method is useful for interaction, say to determine the value in the domain that corresponds to the pixel location under the mouse. + * + * @param value A value from the range. + */ + invertExtent(value: Range): [number, number]; + + /** + * Returns the scale’s current domain. + */ + domain(): number[]; + /** + * Sets the domain of the quantile scale to the specified set of discrete numeric values. + * The array must not be empty, and must contain at least one numeric value; NaN, null and undefined values are ignored and not considered part of the sample population. + * + * If the elements in the given array are not numbers, they will be coerced to numbers. A copy of the input array is sorted and stored internally. + * + * @param domain Array of domain values. + */ + domain(domain: Iterable): this; + + /** + * Returns the current range. + */ + range(): Range[]; + /** + * Sets the discrete values in the range. The array must not be empty. + * The number of values in (the cardinality, or length, of) the range array determines the number of quantiles that are computed. + * + * For example, to compute quartiles, range must be an array of four elements such as [0, 1, 2, 3]. + * + * @param range Array of range values. + */ + range(range: Iterable): this; + + /** + * Returns the quantile thresholds. If the range contains n discrete values, the returned array will contain n - 1 thresholds. + * Values less than the first threshold are considered in the first quantile; + * values greater than or equal to the first threshold but less than the second threshold are in the second quantile, and so on. + * Internally, the thresholds array is used with bisect to find the output quantile associated with the given input value. + */ + quantiles(): number[]; + + /** + * Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa. + */ + copy(): this; + + /** + * Returns the current unknown value, which defaults to undefined. + */ + unknown(): UnknownReturnType; + /** + * Sets the output value of the scale for undefined (or NaN) input values and returns this scale. + * + * @param value The output value of the scale for undefined (or NaN) input values. + */ + unknown(value: NewUnknown): ScaleQuantile; +} + +/** + * Constructs a new quantile scale with the specified range. + * The domain defaults to the empty array. + * If range is not specified, it defaults to the empty array. + * The quantile scale is invalid until both a domain and range are specified. + * + * The first generic corresponds to the data type of range elements. + * The second generic corresponds to the data type of the unknown value. + * + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleQuantile(range?: Iterable): ScaleQuantile; +/** + * Constructs a new quantile scale with the specified domain and range. + * The quantile scale is invalid until both a domain and range are specified. + * + * The first generic corresponds to the data type of range elements. + * The second generic corresponds to the data type of the unknown value. + * + * @param domain Array of domain values. + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleQuantile( + domain: Iterable, + range: Iterable, +): ScaleQuantile; + +// ------------------------------------------------------------------------------- +// Threshold Scale Factory +// ------------------------------------------------------------------------------- + +/** + * Threshold scales are similar to quantize scales, except they allow you to map arbitrary subsets of the domain to discrete values in the range. + * The input domain is still continuous, and divided into slices based on a set of threshold values. + * + * If the number of values in the scale’s range is N+1, the number of values in the scale’s domain must be N. + * If there are fewer than N elements in the domain, the additional values in the range are ignored. + * If there are more than N elements in the domain, the scale may return undefined for some inputs. + * + * The first generic corresponds to the data type of domain values. + * The second generic corresponds to the data type of range values. + * The third generic corresponds to the data type of the unknown value. + */ +export interface ScaleThreshold { + /** + * Given a value in the input domain, returns the corresponding value in the output range. + * + * @param value A domain value. + */ + (value: Domain): Range | Unknown; + + /** + * Returns the extent of values in the domain [x0, x1] for the corresponding value in the range, representing the inverse mapping from range to domain. + * This method is useful for interaction, say to determine the value in the domain that corresponds to the pixel location under the mouse. + * + * @param value A range value. + */ + invertExtent(value: Range): [Domain | undefined, Domain | undefined]; + + /** + * Returns the scale’s current domain. + */ + domain(): Domain[]; + /** + * Sets the scale’s domain to the specified array of values. The values must be in sorted ascending order, or the behavior of the scale is undefined. + * The values are typically numbers, but any naturally ordered values (such as strings) will work; a threshold scale can be used to encode any type that is ordered. + * If the number of values in the scale’s range is N+1, the number of values in the scale’s domain must be N. + * If there are fewer than N elements in the domain, the additional values in the range are ignored. + * If there are more than N elements in the domain, the scale may return undefined for some inputs. + * + * @param domain Array of domain values. + */ + domain(domain: Iterable): this; + + /** + * Returns the scale’s current range. + */ + range(): Range[]; + /** + * Sets the scale’s range to the specified array of values. If the number of values in the scale’s domain is N, the number of values in the scale’s range must be N+1. + * If there are fewer than N+1 elements in the range, the scale may return undefined for some inputs. + * If there are more than N+1 elements in the range, the additional values are ignored. + * + * @param range Array of range values. + */ + range(range: Iterable): this; + + /** + * Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa. + */ + copy(): this; + + /** + * Returns the current unknown value, which defaults to undefined. + */ + unknown(): UnknownReturnType; + /** + * Sets the output value of the scale for undefined (or NaN) input values and returns this scale. + * + * @param value The output value of the scale for undefined (or NaN) input values. + */ + unknown(value: NewUnknown): ScaleThreshold; +} + +/** + * Constructs a new threshold scale with the specified range. + * The domain defaults to [0.5]. + * If range is not specified, it defaults to [0, 1]. + * Thus, the default threshold scale is equivalent to the Math.round function for numbers; for example threshold(0.49) returns 0, and threshold(0.51) returns 1. + * + * The first generic corresponds to the data type of domain values. + * The second generic corresponds to the data type of range values. + * The third generic corresponds to the data type of the unknown value. + * + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleThreshold( + range?: Iterable, +): ScaleThreshold; +/** + * Constructs a new threshold scale with the specified domain and range. + * Thus, the default threshold scale is equivalent to the Math.round function for numbers; for example threshold(0.49) returns 0, and threshold(0.51) returns 1. + * + * The first generic corresponds to the data type of domain values. + * The second generic corresponds to the data type of range values. + * The third generic corresponds to the data type of the unknown value. + * + * @param domain Array of domain values. + * @param range Array of range values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleThreshold( + domain: Iterable, + range: Iterable, +): ScaleThreshold; + +// ------------------------------------------------------------------------------- +// Ordinal Scale Factory +// ------------------------------------------------------------------------------- + +/** + * Unlike continuous scales, ordinal scales have a discrete domain and range. For example, an ordinal scale might map a set of named categories to a set of colors, + * or determine the horizontal positions of columns in a column chart. + * + * The first element in the domain will be mapped to the first element in range, the second domain value to the second range value, and so on. + * If there are fewer elements in the range than in the domain, the scale will reuse values from the start of the range. + * + * The first generic corresponds to the data type of domain values. + * The second generic corresponds to the data type of range values. + * The third generic corresponds to the data type of the unknown value. + */ +export interface ScaleOrdinal { + /** + * Given a value in the input domain, returns the corresponding value in the output range. + * If the given value is not in the scale’s domain, returns the unknown; or, if the unknown value is implicit (the default), + * then the value is implicitly added to the domain and the next-available value in the range is assigned to value, + * such that this and subsequent invocations of the scale given the same input value return the same output value. + * + * @param x A value from the domain. + */ + (x: Domain): Range | Unknown; + + /** + * Returns the scale's current domain. + */ + domain(): Domain[]; + /** + * Sets the domain to the specified array of values. + * + * The first element in domain will be mapped to the first element in the range, + * the second domain value to the second range value, and so on. + * + * Domain values are stored internally in an InternMap from primitive value to index; the resulting index is then used to retrieve a value from the range. + * Thus, an ordinal scale’s values must be coercible to a primitive value, and the primitive domain value uniquely identifies the corresponding range value. + * + * Setting the domain on an ordinal scale is optional if the unknown value is implicit (the default). + * In this case, the domain will be inferred implicitly from usage by assigning each unique value passed to the scale a new value from the range. + * Note that an explicit domain is recommended to ensure deterministic behavior, as inferring the domain from usage will be dependent on ordering. + * + * @param domain Array of domain values. + */ + domain(domain: Iterable): this; + + /** + * Returns the scale's current range. + */ + range(): Range[]; + /** + * Sets the range of the ordinal scale to the specified array of values. + * + * The first element in the domain will be mapped to the first element in range, the second domain value to the second range value, and so on. + * + * If there are fewer elements in the range than in the domain, the scale will reuse values from the start of the range. + * + * @param range Array of range values. + */ + range(range: Iterable): this; + + /** + * Returns the current unknown value, which defaults to "implicit". + */ + unknown(): UnknownReturnType; + /** + * Sets the output value of the scale for unknown input values and returns this scale. + * The implicit value enables implicit domain construction. scaleImplicit can be used as a convenience to set the implicit value. + * + * @param value Unknown value to be used or scaleImplicit to set implicit scale generation. + */ + unknown( + value: NewUnknown, + ): NewUnknown extends { name: "implicit" } ? ScaleOrdinal + : ScaleOrdinal; + + /** + * Returns an exact copy of this ordinal scale. Changes to this scale will not affect the returned scale, and vice versa. + */ + copy(): this; +} + +/** + * Constructs a new ordinal scale with the specified range. + * The domain defaults to the empty array. + * If range is not specified, it defaults to the empty array; an ordinal scale always returns undefined until a non-empty range is defined. + * + * The generic corresponds to the data type of range elements. + * + * @param range An optional array of range values to initialize the scale with. + */ +export function scaleOrdinal(range?: Iterable): ScaleOrdinal; +/** + * Constructs a new ordinal scale with the specified range. + * The domain defaults to the empty array. + * If range is not specified, it defaults to the empty array; an ordinal scale always returns undefined until a non-empty range is defined. + * + * The first generic corresponds to the data type of domain elements. + * The second generic corresponds to the data type of range elements. + * The third generic corresponds to the data type of the unknown value. + * + * @param range An optional array of range values to initialize the scale with. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleOrdinal( + range?: Iterable, +): ScaleOrdinal; +/** + * Constructs a new ordinal scale with the specified domain and range. + * + * The first generic corresponds to the data type of domain elements. + * The second generic corresponds to the data type of range elements. + * The third generic corresponds to the data type of the unknown value. + * + * @param domain Array of domain values. + * @param range An optional array of range values to initialize the scale with. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleOrdinal( + domain: Iterable, + range: Iterable, +): ScaleOrdinal; + +/** + * A special value for ordinal.unknown that enables implicit domain construction: unknown values are implicitly added to the domain. + */ +export const scaleImplicit: { name: "implicit" }; + +// ------------------------------------------------------------------------------- +// Band Scale Factory +// ------------------------------------------------------------------------------- + +/** + * Band scales are like ordinal scales except the output range is continuous and numeric. + * Discrete output values are automatically computed by the scale by dividing the continuous range into uniform bands. + * Band scales are typically used for bar charts with an ordinal or categorical dimension. + * The unknown value of a band scale is effectively undefined: they do not allow implicit domain construction. + * + * The generic corresponds to the data type of domain elements. + */ +export interface ScaleBand { + /** + * Given a value in the input domain, returns the start of the corresponding band derived from the output range. + * If the given value is not in the scale’s domain, returns undefined. + * + * @param x A value from the domain. + */ + (x: Domain): number | undefined; + + /** + * Returns to scale's current domain + */ + domain(): Domain[]; + /** + * Sets the domain to the specified array of values. The first element in domain will be mapped to the first band, the second domain value to the second band, and so on. + * Domain values are stored internally in an InternMap from primitive value to index; the resulting index is then used to determine the band. + * Thus, a band scale’s values must be coercible to a primitive value, and the primitive domain value uniquely identifies the corresponding band. + * + * @param domain Array of domain values. + */ + domain(domain: Iterable): this; + + /** + * Returns the scale’s current range, which defaults to [0, 1]. + */ + range(): [number, number]; + /** + * Sets the scale’s range to the specified two-element array of numbers. If the elements in the given array are not numbers, they will be coerced to numbers. + * The default range is [0, 1]. + * + * @param range A two-element array of numeric values. + */ + range(range: Iterable): this; + + /** + * Sets the scale’s range to the specified two-element array of numbers while also enabling rounding. + * If the elements in the given array are not numbers, they will be coerced to numbers. + * + * Rounding is sometimes useful for avoiding antialiasing artifacts, though also consider the shape-rendering “crispEdges” styles. + * + * @param range A two-element array of numeric values. + */ + rangeRound(range: Iterable): this; + + /** + * Returns the current rounding status for the scale: enabled (= true) or disabled (= false). + */ + round(): boolean; + /** + * Enables or disables rounding accordingly. If rounding is enabled, the start and stop of each band will be integers. + * Rounding is sometimes useful for avoiding antialiasing artifacts, though also consider the shape-rendering “crispEdges” styles. + * Note that if the width of the domain is not a multiple of the cardinality of the range, there may be leftover unused space, even without padding! + * Use band.align to specify how the leftover space is distributed. + * + * @param round Enable rounding (= true), disable rounding (= false). + */ + round(round: boolean): this; + + /** + * Returns the current inner padding which defaults to 0. + */ + paddingInner(): number; + /** + * Sets the inner padding to the specified value which must be in the range [0, 1]. + * The inner padding determines the ratio of the range that is reserved for blank space between bands. + * + * The default setting is 0. + * + * @param padding Value for inner padding in [0, 1] interval. + */ + paddingInner(padding: number): this; + + /** + * Returns the current outer padding which defaults to 0. + */ + paddingOuter(): number; + /** + * Sets the outer padding to the specified value which must be in the range [0, 1]. + * The outer padding determines the ratio of the range that is reserved for blank space before the first band and after the last band. + * + * The default setting is 0. + * + * @param padding Value for outer padding in [0, 1] interval. + */ + paddingOuter(padding: number): this; + + /** + * Returns the inner padding. + */ + padding(): number; + /** + * A convenience method for setting the inner and outer padding to the same padding value. + * + * @param padding Value for inner and outer padding in [0, 1] interval. + */ + padding(padding: number): this; + + /** + * Returns the current alignment which defaults to 0.5. + */ + align(): number; + /** + * Sets the alignment to the specified value which must be in the range [0, 1]. + * + * The default is 0.5. + * + * The alignment determines how any leftover unused space in the range is distributed. + * A value of 0.5 indicates that the outer patter should be equally distributed before the first band and after the last band; + * i.e., the bands should be centered within the range. A value of 0 or 1 may be used to shift the bands to one side, say to position them adjacent to an axis. + * + * @param align Value for alignment setting in [0, 1] interval. + */ + align(align: number): this; + + /** + * Returns the width of each band. + */ + bandwidth(): number; + + /** + * Returns the distance between the starts of adjacent bands. + */ + step(): number; + + /** + * Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa. + */ + copy(): this; +} + +/** + * Constructs a new band scale with the specified range, no padding, no rounding and center alignment. + * The domain defaults to the empty domain. + * If range is not specified, it defaults to the unit range [0, 1]. + * + * The generic corresponds to the data type of domain elements. + * + * @param range A two-element array of numeric values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scaleBand( + range?: Iterable, +): ScaleBand; +/** + * Constructs a new band scale with the specified domain and range, no padding, no rounding and center alignment. + * + * The generic corresponds to the data type of domain elements. + * + * @param domain Array of domain values. + * @param range A two-element array of numeric values. + */ +export function scaleBand( + domain: Iterable, + range: Iterable, +): ScaleBand; + +// ------------------------------------------------------------------------------- +// Point Scale Factory +// ------------------------------------------------------------------------------- + +/** + * Point scales are a variant of band scales with the bandwidth fixed to zero. + * Point scales are typically used for scatterplots with an ordinal or categorical dimension. + * The unknown value of a point scale is always undefined: they do not allow implicit domain construction. + * + * The generic corresponds to the data type of domain elements. + */ +export interface ScalePoint { + /** + * Given a value in the input domain, returns the corresponding point derived from the output range. + * If the given value is not in the scale’s domain, returns undefined. + * + * @param x A value from the domain. + */ + (x: Domain): number | undefined; + + /** + * Returns the scale's current domain. + */ + domain(): Domain[]; + /** + * Sets the domain to the specified array of values. The first element in domain will be mapped to the first point, the second domain value to the second point, and so on. + * Domain values are stored internally in an InternMap from primitive value to index; the resulting index is then used to determine the point. + * Thus, a point scale’s values must be coercible to a primitive value, and the primitive domain value uniquely identifies the corresponding point. + * + * @param domain Array of domain values. + */ + domain(domain: Iterable): this; + + /** + * Returns the scale’s current range, which defaults to [0, 1]. + */ + range(): [number, number]; + /** + * Sets the scale’s range to the specified two-element array of numbers. + * If the elements in the given array are not numbers, they will be coerced to numbers. + * The default range is [0, 1]. + * + * @param range A two-element array of numeric values. + */ + range(range: Iterable): this; + + /** + * Sets the scale’s range to the specified two-element array of numbers while also enabling rounding. + * If the elements in the given array are not numbers, they will be coerced to numbers. + * + * Rounding is sometimes useful for avoiding antialiasing artifacts, though also consider the shape-rendering “crispEdges” styles. + * + * @param range A two-element array of numeric values. + */ + rangeRound(range: Iterable): this; + + /** + * Returns the current rounding status for the scale: enabled (= true) or disabled (= false). + */ + round(): boolean; + /** + * Enables or disables rounding accordingly. If rounding is enabled, the position of each point will be integers. + * Rounding is sometimes useful for avoiding antialiasing artifacts, though also consider the shape-rendering “crispEdges” styles. + * Note that if the width of the domain is not a multiple of the cardinality of the range, there may be leftover unused space, even without padding! + * Use point.align to specify how the leftover space is distributed. + * + * @param round Enable rounding (= true), disable rounding (= false). + */ + round(round: boolean): this; + + /** + * Returns the current outer padding which defaults to 0. + * The outer padding determines the ratio of the range that is reserved for blank space + * before the first point and after the last point. + */ + padding(): number; + /** + * Sets the outer padding to the specified value which must be in the range [0, 1]. + * The outer padding determines the ratio of the range that is reserved for blank space + * before the first point and after the last point. + * + * The default is 0. + * + * @param padding Value for outer padding in [0, 1] interval. + */ + padding(padding: number): this; + + /** + * Returns the current alignment which defaults to 0.5. + */ + align(): number; + /** + * Sets the alignment to the specified value which must be in the range [0, 1]. + * + * The alignment determines how any leftover unused space in the range is distributed. + * A value of 0.5 indicates that the leftover space should be equally distributed before the first point and after the last point; + * i.e., the points should be centered within the range. A value of 0 or 1 may be used to shift the points to one side, say to position them adjacent to an axis. + * + * The default value is 0.5. + * + * @param align Value for alignment setting in [0, 1] interval. + */ + align(align: number): this; + + /** + * Return 0. + */ + bandwidth(): number; + + /** + * Returns the distance between the starts of adjacent points. + */ + step(): number; + + /** + * Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa. + */ + copy(): this; +} + +/** + * Constructs a new point scale with the specified range, no padding, no rounding and center alignment. + * The domain defaults to the empty domain. + * If range is not specified, it defaults to the unit range [0, 1]. + * + * The generic corresponds to the data type of domain elements. + * + * @param range A two-element array of numeric values. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function scalePoint( + range?: Iterable, +): ScalePoint; +/** + * Constructs a new point scale with the specified domain and range, no padding, no rounding and center alignment. + * The domain defaults to the empty domain. + * + * The generic corresponds to the data type of domain elements. + * + * @param domain Array of domain values. + * @param range A two-element array of numeric values. + */ +export function scalePoint( + domain: Iterable, + range: Iterable, +): ScalePoint; diff --git a/tools/ui/node_modules/@types/d3-scale/package.json b/tools/ui/node_modules/@types/d3-scale/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ce8f0d038be028fbf668f879008c4c5c351a427b --- /dev/null +++ b/tools/ui/node_modules/@types/d3-scale/package.json @@ -0,0 +1,53 @@ +{ + "name": "@types/d3-scale", + "version": "4.0.9", + "description": "TypeScript definitions for d3-scale", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-scale", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "rulonder", + "githubUsername": "rulonder", + "url": "https://github.com/rulonder" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-scale" + }, + "scripts": {}, + "dependencies": { + "@types/d3-time": "*" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "c7eb4d63d0dfb659f0f8e359a4de33ed1f690bdea8051641bffa941f06a92f4d", + "typeScriptVersion": "5.0" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-selection/LICENSE b/tools/ui/node_modules/@types/d3-selection/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-selection/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-selection/README.md b/tools/ui/node_modules/@types/d3-selection/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bb086a5c018fea1a5d9440310653332859bcf41e --- /dev/null +++ b/tools/ui/node_modules/@types/d3-selection/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-selection` + +# Summary +This package contains type definitions for d3-selection (https://github.com/d3/d3-selection/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-selection. + +### Additional Details + * Last updated: Mon, 07 Oct 2024 22:38:10 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [denisname](https://github.com/denisname), [Nathan Bierema](https://github.com/Methuselah96), and [Ambar Mutha](https://github.com/ambar-arkin). diff --git a/tools/ui/node_modules/@types/d3-selection/index.d.ts b/tools/ui/node_modules/@types/d3-selection/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1187c250114db60b33b4659e33ccbacd2c0e26a2 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-selection/index.d.ts @@ -0,0 +1,1173 @@ +// Last module patch version validated against: 3.0.0 + +// -------------------------------------------------------------------------- +// Shared Type Definitions and Interfaces +// -------------------------------------------------------------------------- + +/** + * BaseType serves as an alias for the 'minimal' data type which can be selected + * without 'd3-selection' trying to use properties internally which would otherwise not + * be supported. + */ +export type BaseType = Element | EnterElement | Document | Window | null; + +/** + * KeyType serves as alias for valid types that d3 supports as key for data binding + */ +export type KeyType = string | number; + +/** + * A helper interface which covers arguments like NodeListOf or HTMLCollectionOf + * argument types + */ +export interface ArrayLike { + length: number; + item(index: number): T | null; + [index: number]: T; +} + +/** + * An interface describing the element type of the Enter Selection group elements + * created when invoking selection.enter(). + */ +export interface EnterElement { + ownerDocument: Document; + namespaceURI: string; + appendChild(newChild: Node): Node; + insertBefore(newChild: Node, refChild: Node): Node; + querySelector(selectors: string): Element; + querySelectorAll(selectors: string): NodeListOf; +} + +/** + * Container element type usable for mouse/touch functions + */ +export type ContainerElement = HTMLElement | SVGSVGElement | SVGGElement; + +/** + * A User interface event (e.g. mouse event, touch or MSGestureEvent) with captured clientX and clientY properties. + */ +export interface ClientPointEvent { + clientX: number; + clientY: number; +} + +/** + * Interface for optional parameters map, when dispatching custom events + * on a selection + */ +export interface CustomEventParameters { + /** + * If true, the event is dispatched to ancestors in reverse tree order + */ + bubbles: boolean; + /** + * If true, event.preventDefault is allowed + */ + cancelable: boolean; + /** + * Any custom data associated with the event + */ + detail: any; +} + +/** + * Callback type for selections and transitions + */ +export type ValueFn = ( + this: T, + datum: Datum, + index: number, + groups: T[] | ArrayLike, +) => Result; + +/** + * TransitionLike is a helper interface to represent a quasi-Transition, without specifying the full Transition interface in this file. + * For example, wherever d3-zoom allows a Transition to be passed in as an argument, it internally immediately invokes its `selection()` + * method to retrieve the underlying Selection object before proceeding. + * d3-brush uses a subset of Transition methods internally. + * The use of this interface instead of the full imported Transition interface is [referred] to achieve + * two things: + * (1) the d3-transition module may not be required by a projects use case, + * (2) it avoids possible complications from 'module augmentation' from d3-transition to Selection. + */ +export interface TransitionLike { + selection(): Selection; + on(type: string, listener: null): TransitionLike; + on(type: string, listener: ValueFn): TransitionLike; + tween(name: string, tweenFn: null): TransitionLike; + tween(name: string, tweenFn: ValueFn void)>): TransitionLike; +} + +// -------------------------------------------------------------------------- +// All Selection related interfaces and function +// -------------------------------------------------------------------------- + +/** + * Select the first element that matches the specified selector string. If no elements match the selector, returns an empty selection. + * If multiple elements match the selector, only the first matching element (in document order) will be selected. + * + * The first generic "GElement" refers to the type of element to be selected. The second generic "OldDatum" refers to the type of the + * datum, on the selected element. This is useful when re-selecting an element with a previously set, know datum type. + * + * @param selector CSS selector string + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function select( + selector: string, +): Selection; +/** + * Select the specified node element. + * + * The first generic "GElement" refers to the type of element to be selected. The second generic "OldDatum" refers to the type of the + * datum, on the selected element. This is useful when re-selecting an element with a previously set, know datum type. + * + * @param node An element to be selected + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function select( + node: GElement, +): Selection; + +/** + * Create an empty selection. + */ +export function selectAll(selector?: null): Selection; +/** + * Select all elements that match the specified selector string. The elements will be selected in document order (top-to-bottom). + * If no elements in the document match the selector, returns an empty selection. + * + * The first generic "GElement" refers to the type of element to be selected. The second generic "OldDatum" refers to the type of the + * datum, of a selected element. This is useful when re-selecting elements with a previously set, know datum type. + * + * @param selector CSS selector string + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function selectAll( + selector: string, +): Selection; +/** + * Select the specified array, array-like, or iterable of nodes. + * This is useful if you already have a reference to nodes, such as `this.childNodes` within an event listener or a global such as `document.links`. + * The nodes may instead be an iterable, or a pseudo-array such as a NodeList. + * + * The first generic "GElement" refers to the type of element to be selected. + * The second generic "OldDatum" refers to the type of the datum, of a selected element. + * + * @param nodes An array, array-like, or iterable of nodes + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function selectAll( + nodes: GElement[] | ArrayLike | Iterable, +): Selection; + +/** + * A D3 Selection of elements. + * + * The first generic "GElement" refers to the type of the selected element(s). + * The second generic "Datum" refers to the type of the datum of a selected element(s). + * The third generic "PElement" refers to the type of the parent element(s) in the D3 selection. + * The fourth generic "PDatum" refers to the type of the datum of the parent element(s). + */ +export interface Selection { + // Sub-selection ------------------------- + + /** + * For each selected element, select the first descendant element that matches the specified selector string. + * If no element matches the specified selector for the current element, the element at the current index will + * be null in the returned selection. If multiple elements match the selector, only the first matching element + * in document order is selected. Selection.select does not affect grouping: it preserves the existing group + * structure and indexes, and propagates data (if any) to selected children. + * + * If the current element has associated data, this data is propagated to the + * corresponding selected element. + * + * The generic represents the type of the descendant element to be selected. + * + * @param selector CSS selector string + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + select(selector: string): Selection; + /** + * Create an empty sub-selection. Selection.select does not affect grouping: it preserves the existing group + * structure and indexes. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + select(selector: null): Selection; + /** + * For each selected element, select the descendant element returned by the selector function. + * If no element is returned by the selector function for the current element, the element at the + * current index will be null in the returned selection. Selection.select does not affect grouping: + * it preserves the existing group structure and indexes, and propagates data (if any) to selected children. + * + * If the current element has associated data, this data is propagated to the + * corresponding selected element. + * + * The generic represents the type of the descendant element to be selected. + * + * @param selector A selector function, which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). + * It must return an element, or null if there is no matching element. + */ + select( + selector: ValueFn, + ): Selection; + + /** + * Create an empty sub-selection. Selection.selectAll does affect grouping: The elements in the returned + * selection are grouped by their corresponding parent node in this selection, the group at the current index will be empty. + */ + selectAll(selector?: null): Selection; + /** + * For each selected element, selects the descendant elements that match the specified selector string. The elements in the returned + * selection are grouped by their corresponding parent node in this selection. If no element matches the specified selector + * for the current element, the group at the current index will be empty. Selection.selectAll does affect grouping: each selected descendant + * is grouped by the parent element in the originating selection. + * + * The selected elements do not inherit data from this selection; use selection.data to propagate data to children. + * + * The first generic "DescElement" refers to the type of descendant element to be selected. The second generic "OldDatum" refers to the type of the + * datum, of a selected element. This is useful when re-selecting elements with a previously set, know datum type. + * + * @param selector CSS selector string + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + selectAll( + selector: string, + ): Selection; + /** + * For each selected element, selects the descendant elements returned by the selector function. The elements in the returned + * selection are grouped by their corresponding parent node in this selection. If no element matches the specified selector + * for the current element, the group at the current index will be empty. Selection.selectAll does affect grouping: each selected descendant + * is grouped by the parent element in the originating selection. + * + * The selected elements do not inherit data from this selection; use selection.data to propagate data to children. + * + * The first generic "DescElement" refers to the type of descendant element to be selected. The second generic "OldDatum" refers to the type of the + * datum, of a selected element. This is useful when re-selecting elements with a previously set, know datum type. + * + * @param selector A selector function which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). It must return an array of elements + * (or an iterable, or a pseudo-array, such as a NodeList), or the empty array if there are no matching elements. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + selectAll( + selector: ValueFn | Iterable>, + ): Selection; + + /** + * Filters the selection, returning a new selection that contains only the elements for + * which the specified filter is true. + * + * The returned filtered selection preserves the parents of this selection, but like array.filter, + * it does not preserve indexes as some elements may be removed; use selection.select to preserve the index, if needed. + * + * @param selector A CSS selector string to match when filtering. + */ + filter(selector: string): Selection; + /** + * Filters the selection, returning a new selection that contains only the elements for + * which the specified filter is true. + * + * The returned filtered selection preserves the parents of this selection, but like array.filter, + * it does not preserve indexes as some elements may be removed; use selection.select to preserve the index, if needed. + * + * The generic refers to the type of element which will be selected after applying the filter, i.e. if the element types + * contained in a pre-filter selection are narrowed to a subset as part of the filtering. + * + * @param selector A CSS selector string to match when filtering. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + filter(selector: string): Selection; + /** + * Filter the selection, returning a new selection that contains only the elements for + * which the specified filter is true. + * + * The returned filtered selection preserves the parents of this selection, but like array.filter, + * it does not preserve indexes as some elements may be removed; use selection.select to preserve the index, if needed. + * + * @param selector A value function which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). This function should return true + * for an element to be included, and false otherwise. + */ + filter(selector: ValueFn): Selection; + /** + * Filter the selection, returning a new selection that contains only the elements for + * which the specified filter is true. + * + * The returned filtered selection preserves the parents of this selection, but like array.filter, + * it does not preserve indexes as some elements may be removed; use selection.select to preserve the index, if needed. + * + * @param selector A value function which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). This function should return true + * for an element to be included, and false otherwise. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + filter( + selector: ValueFn, + ): Selection; + + /** + * Returns a new selection merging this selection with the specified other selection or transition. + * The returned selection has the same number of groups and the same parents as this selection. + * Any missing (null) elements in this selection are filled with the corresponding element, + * if present (not null), from the specified selection. (If the other selection has additional groups or parents, + * they are ignored.) + * + * This method is commonly used to merge the enter and update selections after a data-join. + * After modifying the entering and updating elements separately, you can merge the two selections and + * perform operations on both without duplicate code. + * + * This method is not intended for concatenating arbitrary selections, however: if both this selection + * and the specified other selection have (non-null) elements at the same index, this selection’s element + * is returned in the merge and the other selection’s element is ignored. + * + * @param other Selection to be merged. + */ + merge( + other: Selection | TransitionLike, + ): Selection; + + /** + * Returns a new selection with the (first) child of each element of the current selection matching the selector. + * Selects the first child that matches (if any). + * + * The generic represents the type of the descendant element to be selected. + * + * @param selector CSS selector string + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + selectChild(selector?: string): Selection; + /** + * Returns a new selection with the (first) child of each element of the current selection matching the selector. + * + * The first generic represents the type of the descendant element to be selected. + * The second generic represents the type of any of the child elements. + * + * @param selector A selector function, which is evaluated for each of the children nodes, in order, being passed the child (child), the child’s index (i), and the list of children (children); + * the method selects the first child for which the selector return truthy, if any. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + selectChild( + selector: (child: ChildElement, i: number, children: ChildElement[]) => boolean, + ): Selection; + + /** + * Returns a new selection with the children of each element of the current selection matching the selector. + * Selects the children that match (if any) + * + * The first generic represents the type of the descendant element to be selected. + * The second generic refers to the type of the datum of the element to be selected. + * + * @param selector CSS selector string + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + selectChildren( + selector?: string, + ): Selection; + /** + * Returns a new selection with the children of each element of the current selection matching the selector. + * + * The first generic represents the type of the descendant element to be selected. + * The second generic refers to the type of the datum of the element to be selected. + * The third generic represents the type of any of the child elements. + * + * @param selector A selector function, which is evaluated for each of the children nodes, in order, being passed the child (child), the child’s index (i), and the list of children (children); + * the method selects the first child for which the selector return truthy, if any. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + selectChildren( + selector: (child: ChildElement, i: number, children: ChildElement[]) => boolean, + ): Selection; + + /** + * Returns the selection (for symmetry with transition.selection). + */ + selection(): this; + + // Modifying ------------------------------- + + /** + * Return the current value of the specified attribute for the first (non-null) element in the selection. + * This is generally useful only if you know that the selection contains exactly one element. + * + * @param name Name of the attribute + */ + attr(name: string): string; + /** + * Sets the attribute with the specified name to the specified value on the selected elements and returns this selection. + * If the value is a constant, all elements are given the same attribute value; + * otherwise, if the value is a function, it is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). + * The function’s return value is then used to set each element’s attribute. + * A null value will remove the specified attribute. + */ + attr( + name: string, + value: + | null + | string + | number + | boolean + | ReadonlyArray + | ValueFn>, + ): this; + + /** + * Returns true if and only if the first (non-null) selected element has the specified classes. + * This is generally useful only if you know the selection contains exactly one element. + * + * @param names A string of space-separated class names. + */ + classed(names: string): boolean; + /** + * Assigns or unassigns the specified CSS class names on the selected elements by setting + * the class attribute or modifying the classList property and returns this selection. + * If the constant value is truthy, then all elements are assigned the specified classes; otherwise, the classes are unassigned. + * + * @param names A string of space-separated class names. + * @param value A boolean flag (true = assign / false = unassign) + */ + classed(names: string, value: boolean): this; + /** + * Assigns or unassigns the specified CSS class names on the selected elements by setting + * the class attribute or modifying the classList property and returns this selection. + * The assign/unassign status for the individual selected elements is determined by the boolean return + * value of the value function. + * + * @param names A string of space-separated class names. + * @param value A value function which is evaluated for each selected element, in order, + * being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). + * The function’s return value is then used to assign or unassign classes on each element. + */ + classed(names: string, value: ValueFn): this; + + /** + * Returns the current value of the specified style property for the first (non-null) element in the selection. + * The current value is defined as the element’s inline value, if present, and otherwise its computed value. + * Accessing the current style value is generally useful only if you know the selection contains exactly one element. + * + * @param name Name of the style + */ + style(name: string): string; + /** + * Clear the style with the specified name for the selected elements and returns this selection. + * + * @param name Name of the style + * @param value null,to clear the style + */ + style(name: string, value: null): this; + /** + * Sets the value of the style with the specified name for the selected elements and returns this selection. + * All elements are given the same style value. + * + * @param name Name of the style + * @param value Constant value for the style + * @param priority An optional priority flag, either null or the string important (without the exclamation point) + */ + style(name: string, value: string | number | boolean, priority?: null | "important"): this; + /** + * Sets the value of the style with the specified name for the selected elements and returns this selection. + * The value for the individual selected elements is determined by the value function. + * + * @param name Name of the style + * @param value A value function which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). A null value will clear the style. + * @param priority An optional priority flag, either null or the string important (without the exclamation point) + */ + style( + name: string, + value: ValueFn, + priority?: null | "important", + ): this; + + /** + * Return the current value of the specified property for the first (non-null) element in the selection. + * This is generally useful only if you know that the selection contains exactly one element. + * + * @param name Name of the property + */ + property(name: string): any; + /** + * Look up a local variable on the first node of this selection. Note that this is not equivalent to `local.get(selection.node())` in that it will not look up locals set on the parent node(s). + * + * @param name The `d3.local` variable to look up. + */ + property(name: Local): T | undefined; + /** + * Sets the property with the specified name to the specified value on selected elements. + * If the value is a constant, then all elements are given the same property value; + * otherwise, if the value is a function, it is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). + * The function’s return value is then used to set each element’s property. A null value will delete the specified property. + */ + property(name: string, value: ValueFn | null): this; + /** + * Sets the value of the property with the specified name for the selected elements and returns this selection. + * All elements are given the same property value. + * + * @param name Name of the property + * @param value Constant value for the property + */ + property(name: string, value: any): this; + /** + * Store a value in a `d3.local` variable. + * This is equivalent to `selection.each(function (d, i, g) { name.set(this, value.call(this, d, i, g)); })` but more concise. + * + * @param name A `d3.local` variable + * @param value A callback that returns the value to store + */ + property(name: Local, value: ValueFn): this; + /** + * Store a value in a `d3.local` variable for each node in the selection. + * This is equivalent to `selection.each(function () { name.set(this, value); })` but more concise. + * + * @param name A `d3.local` variable + * @param value A callback that returns the value to store + */ + property(name: Local, value: T): this; + + /** + * Returns the text content for the first (non-null) element in the selection. + * This is generally useful only if you know the selection contains exactly one element. + */ + text(): string; + /** + * Sets the text content to the specified value on all selected elements, replacing any existing child elements. + * If the value is a constant, then all elements are given the same text content; + * otherwise, if the value is a function, it is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). + * The function’s return value is then used to set each element’s text content. + * A null value will clear the content. + */ + text(value: null | string | number | boolean | ValueFn): this; + + /** + * Returns a string representation of the inner HTML for the first (non-null) element in the selection. + * This is generally useful only if you know the selection contains exactly one element. + */ + html(): string; + /** + * Sets the inner HTML to the specified value on all selected elements, replacing any existing child elements. + * If the value is a constant, then all elements are given the same inner HTML; + * otherwise, if the value is a function, it is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). + * The function’s return value is then used to set each element’s inner HTML. + * A null value will clear the content. + */ + html(value: null | string | ValueFn): this; + + /** + * Appends a new element of this type (tag name) as the last child of each selected element, + * or before the next following sibling in the update selection if this is an enter selection. + * The latter behavior for enter selections allows you to insert elements into the DOM in an order consistent with the new bound data; + * however, note that selection.order may still be required if updating elements change order + * (i.e., if the order of new data is inconsistent with old data). + * + * This method returns a new selection containing the appended elements. + * Each new element inherits the data of the current elements, if any. + * + * @param type A string representing the tag name. + */ + append(type: K): Selection; + /** + * Appends a new element of this type (tag name) as the last child of each selected element, + * or before the next following sibling in the update selection if this is an enter selection. + * The latter behavior for enter selections allows you to insert elements into the DOM in an order consistent with the new bound data; + * however, note that selection.order may still be required if updating elements change order + * (i.e., if the order of new data is inconsistent with old data). + * + * This method returns a new selection containing the appended elements. + * Each new element inherits the data of the current elements, if any. + * + * The generic refers to the type of the child element to be appended. + * + * @param type A string representing the tag name. The specified name may have a namespace prefix, such as svg:text + * to specify a text attribute in the SVG namespace. If no namespace is specified, the namespace will be inherited + * from the parent element; or, if the name is one of the known prefixes, the corresponding namespace will be used + * (for example, svg implies svg:svg) + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + append(type: string): Selection; + /** + * Appends a new element of the type provided by the element creator function as the last child of each selected element, + * or before the next following sibling in the update selection if this is an enter selection. + * The latter behavior for enter selections allows you to insert elements into the DOM in an order consistent with the new bound data; + * however, note that selection.order may still be required if updating elements change order + * (i.e., if the order of new data is inconsistent with old data). + * + * This method returns a new selection containing the appended elements. + * Each new element inherits the data of the current elements, if any. + * + * The generic refers to the type of the child element to be appended. + * + * @param type A creator function which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). This function should return + * an element to be appended. (The function typically creates a new element, but it may instead return an existing element.) + */ + append( + type: ValueFn, + ): Selection; + + /** + * Inserts a new element of the specified type (tag name) before the first element matching the specified + * before selector for each selected element. For example, a before selector :first-child will prepend nodes before the first child. + * If before is not specified, it defaults to null. (To append elements in an order consistent with bound data, use selection.append.) + * + * This method returns a new selection containing the appended elements. + * Each new element inherits the data of the current elements, if any. + * + * The generic refers to the type of the child element to be appended. + * + * @param type A string representing the tag name for the element type to be inserted. + * @param before One of: + * * A CSS selector string for the element before which the insertion should occur. + * * A child selector function which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). This function should return the child element + * before which the element should be inserted. + */ + insert( + type: K, + before?: string | ValueFn, + ): Selection; + /** + * Inserts a new element of the specified type (tag name) before the first element matching the specified + * before selector for each selected element. For example, a before selector :first-child will prepend nodes before the first child. + * If before is not specified, it defaults to null. (To append elements in an order consistent with bound data, use selection.append.) + * + * This method returns a new selection containing the appended elements. + * Each new element inherits the data of the current elements, if any. + * + * The generic refers to the type of the child element to be appended. + * + * @param type One of: + * * A string representing the tag name for the element type to be inserted. The specified name may have a namespace prefix, + * such as svg:text to specify a text attribute in the SVG namespace. If no namespace is specified, the namespace will be inherited + * from the parent element; or, if the name is one of the known prefixes, the corresponding namespace will be used + * (for example, svg implies svg:svg) + * * A creator function which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). This function should return + * an element to be inserted. (The function typically creates a new element, but it may instead return an existing element.) + * @param before One of: + * * A CSS selector string for the element before which the insertion should occur. + * * A child selector function which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). This function should return the child element + * before which the element should be inserted. + */ + insert( + type: string | ValueFn, + before?: string | ValueFn, + ): Selection; + + /** + * Removes the selected elements from the document. + * Returns this selection (the removed elements) which are now detached from the DOM. + */ + remove(): this; + + /** + * Inserts clones of the selected elements immediately following the selected elements and returns a selection of the newly + * added clones. If deep is true, the descendant nodes of the selected elements will be cloned as well. Otherwise, only the elements + * themselves will be cloned. + * + * @param deep Perform deep cloning if this flag is set to true. + */ + clone(deep?: boolean): Selection; + + /** + * Return a new selection that contains a copy of each group in this selection sorted according + * to the compare function. After sorting, re-inserts elements to match the resulting order (per selection.order). + * + * Note that sorting is not guaranteed to be stable; however, it is guaranteed to have the same + * behavior as your browser’s built-in sort method on arrays. + * + * @param comparator An optional comparator function, which defaults to "ascending". The function is passed + * two elements’ data a and b to compare. It should return either a negative, positive, or zero value. + * If negative, then a should be before b; if positive, then a should be after b; otherwise, a and b are + * considered equal and the order is arbitrary. + */ + sort(comparator?: (a: Datum, b: Datum) => number): this; + + /** + * Re-insert elements into the document such that the document order of each group matches the selection order. + * This is equivalent to calling selection.sort if the data is already sorted, but much faster. + */ + order(): this; + + /** + * Re-insert each selected element, in order, as the last child of its parent. + */ + raise(): this; + + /** + * Re-insert each selected element, in order, as the first child of its parent. + */ + lower(): this; + + // Data Join --------------------------------- + + /** + * Returns the array of data for the selected elements. + */ + data(): Datum[]; + /** + * Joins the specified array of data with the selected elements, returning a new selection that represents + * the update selection: the elements successfully bound to data. Also defines the enter and exit selections on + * the returned selection, which can be used to add or remove elements to correspond to the new data. + * + * The data is specified for each group in the selection. If the selection has multiple groups + * (such as d3.selectAll followed by selection.selectAll), then data should typically be specified as a function. + * + * If a key function is not specified, then the first datum in data is assigned to the first selected element, + * the second datum to the second selected element, and so on. + * A key function may be specified to control which datum is assigned to which element, replacing the default join-by-index, + * by computing a string identifier for each datum and element. + * + * The update and enter selections are returned in data order, while the exit selection preserves the selection + * order prior to the join. If a key function is specified, the order of elements in the selection may not match + * their order in the document; use selection.order or selection.sort as needed. + * + * This method cannot be used to clear bound data; use selection.datum instead. + * + * For details see: {@link https://github.com/d3/d3-selection#joining-data } + * + * The generic refers to the type of the new datum to be used for the selected elements. + * + * @param data The specified data is an array or iterable of arbitrary values (e.g., numbers or objects) + * or a value function which will be evaluated for each group in order, being passed the group’s parent datum + * (d, which may be undefined), the group index (i), and the selection’s parent nodes (nodes), + * with this as the group’s parent element. The function returns an array or iterable of values for each group. + * @param key An optional key function which is evaluated for each selected element, in order, being passed the + * current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]); the returned string is the element’s key. + * The key function is then also evaluated for each new datum in data, being passed the current datum (d), + * the current index (i), and the group’s new data, with this as the group’s parent DOM element (nodes[i]); the returned string is the datum’s key. + * The datum for a given key is assigned to the element with the matching key. If multiple elements have the same key, + * the duplicate elements are put into the exit selection; if multiple data have the same key, the duplicate data are put into the enter selection. + */ + data( + data: NewDatum[] | Iterable | ValueFn>, + key?: ValueFn, + ): Selection; + + /** + * Appends, removes and reorders elements as necessary to match the data that was previously bound by `selection.data`, returning the merged enter and update selection. + * This method is a convenient alternative to the more explicit `selection.enter`, `selection.exit`, `selection.append` and `selection.remove`. + * + * The "matching" logic is determined by the key function passed to `selection.data`. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + join( + enter: K, + update?: ( + elem: Selection, + ) => Selection | TransitionLike | undefined, + exit?: (elem: Selection) => void, + ): Selection; + /** + * Appends, removes and reorders elements as necessary to match the data that was previously bound by `selection.data`, returning the merged enter and update selection. + * This method is a convenient alternative to the more explicit `selection.enter`, `selection.exit`, `selection.append` and `selection.remove`. + * + * The "matching" logic is determined by the key function passed to `selection.data`. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + join( + enter: + | string + | (( + elem: Selection, + ) => Selection | TransitionLike), + update?: ( + elem: Selection, + ) => Selection | TransitionLike | undefined, + exit?: (elem: Selection) => void, + ): Selection; + + /** + * Return the enter selection: placeholder nodes for each datum that had no corresponding DOM element + * in the selection. (The enter selection is empty for selections not returned by selection.data.) + */ + enter(): Selection; + + /** + * Returns the exit selection: existing DOM elements in the selection for which no new datum was found. + * (The exit selection is empty for selections not returned by selection.data.) + * + * IMPORTANT: The generic refers to the type of the old datum associated with the exit selection elements. + * Ensure you set the generic to the correct type, if you need to access the data on the exit selection in + * follow-up steps, e.g. to set styles as part of an exit transition before removing them. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + exit(): Selection; + + /** + * Returns the bound datum for the first (non-null) element in the selection. + * This is generally useful only if you know the selection contains exactly one element. + */ + datum(): Datum; + /** + * Delete the bound data for each element in the selection. + */ + datum(value: null): Selection; + /** + * Sets the element’s bound data using the specified value function on all selected elements. + * Unlike selection.data, this method does not compute a join and does not affect + * indexes or the enter and exit selections. + * + * The generic refers to the type of the new datum to be used for the selected elements. + * + * @param value A value function which is evaluated for each selected element, in order, + * being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element (nodes[i]). The function is then used to set each element’s new data. + * A null value will delete the bound data. + */ + datum(value: ValueFn): Selection; + /** + * Sets the element’s bound data to the specified value on all selected elements. + * Unlike selection.data, this method does not compute a join and does not affect + * indexes or the enter and exit selections. + * + * The generic refers to the type of the new datum to be used for the selected elements. + * + * @param value A value object to be used as the datum for each element. + */ + datum(value: NewDatum): Selection; + + // Event Handling ------------------- + + /** + * Return the currently-assigned listener for the specified event typename on the first (non-null) selected element, + * if any, If multiple typenames are specified, the first matching listener is returned. + * + * @param typenames The typenames is a string event type, such as click, mouseover, or submit; any DOM event type supported by your browser may be used. + * The type may be optionally followed by a period (.) and a name; the optional name allows multiple callbacks to be registered + * to receive events of the same type, such as click.foo and click.bar. To specify multiple typenames, separate typenames with spaces, + * such as "input change"" or "click.foo click.bar". + */ + on(typenames: string): ((this: GElement, event: any, d: Datum) => void) | undefined; + /** + * Remove a listener for the specified event type names. To remove all listeners for a given name, + * pass null as the listener and ".foo" as the typename, where foo is the name; to remove all listeners with no name, specify "." as the typename. + * + * @param typenames The typenames is a string event type, such as click, mouseover, or submit; any DOM event type supported by your browser may be used. + * The type may be optionally followed by a period (.) and a name; the optional name allows multiple callbacks to be registered + * to receive events of the same type, such as click.foo and click.bar. To specify multiple typenames, separate typenames with spaces, + * such as "input change"" or "click.foo click.bar". + * @param listener null to indicate removal of listener + */ + on(typenames: string, listener: null): this; + /** + * Add an event listener for the specified event type names. If an event listener was previously registered for the same typename + * on a selected element, the old listener is removed before the new listener is added. + * + * When a specified event is dispatched on a selected node, the specified listener will be evaluated for each selected element. + * + * @param typenames The typenames is a string event type, such as click, mouseover, or submit; any DOM event type supported by your browser may be used. + * The type may be optionally followed by a period (.) and a name; the optional name allows multiple callbacks to be registered + * to receive events of the same type, such as click.foo and click.bar. To specify multiple typenames, separate typenames with spaces, + * such as "input change"" or "click.foo click.bar". + * @param listener A listener function which will be evaluated for each selected element, + * being passed the current event (event) and the current datum (d), with this as the current DOM element (event.currentTarget). + * Listeners always see the latest datum for their element. + * Note: while you can use event.pageX and event.pageY directly, + * it is often convenient to transform the event position to the local coordinate system of that element that received the event using d3.pointer. + * @param options An optional options object may specify characteristics about the event listener, such as wehether it is captures or passive; see element.addEventListener. + */ + on(typenames: string, listener: (this: GElement, event: any, d: Datum) => void, options?: any): this; + + /** + * Dispatches a custom event of the specified type to each selected element, in order. + * An optional parameters map may be specified to set additional properties of the event. + * + * @param type Name of event to dispatch + * @param parameters An optional value map with custom event parameters + */ + dispatch(type: string, parameters?: CustomEventParameters): this; + /** + * Dispatches a custom event of the specified type to each selected element, in order. + * An optional value function returning a parameters map for each element in the selection may be specified to set additional properties of the event. + * + * @param type Name of event to dispatch + * @param parameters A value function which is evaluated for each selected element, in order, + * being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element (nodes[i]). It must return the parameters map for the current element. + */ + dispatch(type: string, parameters?: ValueFn): this; + + // Control Flow ---------------------- + + /** + * Invoke the specified function for each selected element, passing in the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). + * This method can be used to invoke arbitrary code for each selected element, and is useful for creating a context to access parent and child data simultaneously. + * + * @param func A function which is invoked for each selected element, + * being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). + */ + each(func: ValueFn): this; + + /** + * Invoke the specified function exactly once, passing in this selection along with any optional arguments. + * Returns this selection. + * + * @param func A function which is passed this selection as the first argument along with any optional arguments. + * @param args List of optional arguments to be passed to the callback function. + */ + call( + func: (selection: Selection, ...args: Args) => void, + ...args: Args + ): this; + + /** + * Return true if this selection contains no (non-null) elements. + */ + empty(): boolean; + + /** + * Return an array of all (non-null) elements in this selection. + */ + nodes(): GElement[]; + + /** + * Return the first (non-null) element in this selection. If the selection is empty, returns null. + */ + node(): GElement | null; + + /** + * Returns the total number of elements in this selection. + */ + size(): number; + + /** + * Returns an iterator over the selected (non-null) elements. + */ + [Symbol.iterator](): Iterator; +} + +/** + * Selects the root element, document.documentElement. This function can also be used to test for selections + * (instanceof d3.selection) or to extend the selection prototype. + */ +export type SelectionFn = () => Selection; + +/** + * Selects the root element, document.documentElement. This function can also be used to test for selections + * (instanceof d3.selection) or to extend the selection prototype. + */ +export const selection: SelectionFn; + +// --------------------------------------------------------------------------- +// pointer.js and pointers.js related +// --------------------------------------------------------------------------- + +/** + * Returns a two-element array of numbers [x, y] representing the coordinates of the specified event relative to the specified target. + * event can be a MouseEvent, a PointerEvent, a Touch, or a custom event holding a UIEvent as event.sourceEvent. + * + * If target is not specified, it defaults to the source event’s currentTarget property, if available. + * If the target is an SVG element, the event’s coordinates are transformed using the inverse of the screen coordinate transformation matrix. + * If the target is an HTML element, the event’s coordinates are translated relative to the top-left corner of the target’s bounding client rectangle. + * (As such, the coordinate system can only be translated relative to the client coordinates. See also GeometryUtils.) + * Otherwise, [event.pageX, event.pageY] is returned. + * + * @param event The specified event. + * @param target The target which the coordinates are relative to. + */ +export function pointer(event: any, target?: any): [number, number]; + +/** + * Returns an array [[x0, y0], [x1, y1]…] of coordinates of the specified event’s pointer locations relative to the specified target. + * For touch events, the returned array of positions corresponds to the event.touches array; for other events, returns a single-element array. + * + * If target is not specified, it defaults to the source event’s currentTarget property, if any. + * + * @param event The specified event. + * @param target The target which the coordinates are relative to. + */ +export function pointers(event: any, target?: any): Array<[number, number]>; + +// --------------------------------------------------------------------------- +// style +// --------------------------------------------------------------------------- + +/** + * Returns the value of the style property with the specified name for the specified node. + * If the node has an inline style with the specified name, its value is returned; otherwise, the computed property value is returned. + * See also selection.style. + * + * @param node A DOM node (e.g. HTMLElement, SVGElement) for which to retrieve the style property. + * @param name Style property name. + */ +export function style(node: Element, name: string): string; + +// --------------------------------------------------------------------------- +// local.js related +// --------------------------------------------------------------------------- + +export interface Local { + /** + * Retrieves a local variable stored on the node (or one of its parents). + * + * @param node A node element. + */ + get(node: Element): T | undefined; + /** + * Deletes the value associated with the given node. Values stored on ancestors are not affected, meaning that child nodes will still see inherited values. + * + * This function returns true if there was a value stored directly on the node, and false otherwise. + * + * @param node A node element. + */ + remove(node: Element): boolean; + /** + * Store a value for this local variable. Calling `.get()` on children of this node will also retrieve the variable's value. + * + * @param node A node element. + * @param value Value to store locally + */ + set(node: Element, value: T): T; + /** + * Obtain a string with the internally assigned property name for the local + * which is used to store the value on a node + */ + toString(): string; +} + +/** + * Obtain a new local variable + * + * The generic refers to the type of the variable to store locally. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function local(): Local; + +// --------------------------------------------------------------------------- +// namespace.js related +// --------------------------------------------------------------------------- + +/** + * Interface for object literal containing local name with related fully qualified namespace + */ +export interface NamespaceLocalObject { + /** + * Fully qualified namespace + */ + space: string; + /** + * Name of the local to be namespaced. + */ + local: string; +} + +/** + * Obtain an object with properties of fully qualified namespace string and + * name of local by parsing a shorthand string "prefix:local". If the prefix + * does not exist in the "namespaces" object provided by d3-selection, then + * the local name is returned as a simple string. + * + * @param prefixedLocal A string composed of the namespace prefix and local + * name separated by colon, e.g. "svg:text". + */ +export function namespace(prefixedLocal: string): NamespaceLocalObject | string; + +// --------------------------------------------------------------------------- +// namespaces.js related +// --------------------------------------------------------------------------- + +/** + * Interface for maps of namespace prefixes to corresponding fully qualified namespace strings + */ +export interface NamespaceMap { + [prefix: string]: string; +} + +/** + * Map of namespace prefixes to corresponding fully qualified namespace strings + */ +export const namespaces: NamespaceMap; + +// --------------------------------------------------------------------------- +// window.js related +// --------------------------------------------------------------------------- + +/** + * Returns the owner window for the specified node. If node is a node, returns the owner document’s default view; + * if node is a document, returns its default view; otherwise returns the node. + * + * @param DOMNode A DOM element + */ +export function window(DOMNode: Window | Document | Element): Window; + +// --------------------------------------------------------------------------- +// creator.js and matcher.js Complex helper closure generating functions +// for explicit bound-context dependent use +// --------------------------------------------------------------------------- + +/** + * Given the specified element name, returns a single-element selection containing + * a detached element of the given name in the current document. + * + * @param name tag name of the element to be added. + */ +export function create( + name: K, +): Selection; +/** + * Given the specified element name, returns a single-element selection containing + * a detached element of the given name in the current document. + * + * @param name Tag name of the element to be added. See "namespace" for details on supported namespace prefixes, + * such as for SVG elements. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function create(name: string): Selection; + +/** + * Given the specified element name, returns a function which creates an element of the given name, + * assuming that "this" is the parent element. + * + * @param name Tag name of the element to be added. + */ +export function creator(name: K): (this: BaseType) => ElementTagNameMap[K]; +/** + * Given the specified element name, returns a function which creates an element of the given name, + * assuming that "this" is the parent element. + * + * The generic refers to the type of the new element to be returned by the creator function. + * + * @param name Tag name of the element to be added. See "namespace" for details on supported namespace prefixes, + * such as for SVG elements. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function creator(name: string): (this: BaseType) => NewGElement; + +/** + * Given the specified selector, returns a function which returns true if "this" element matches the specified selector. + * + * @param selector A CSS selector string. + */ +export function matcher(selector: string): (this: BaseType) => boolean; + +// ---------------------------------------------------------------------------- +// selector.js and selectorAll.js related functions +// ---------------------------------------------------------------------------- + +/** + * Given the specified selector, returns a function which returns the first descendant of "this" element + * that matches the specified selector. + * + * The generic refers to the type of the returned descendant element. + * + * @param selector A CSS selector string. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function selector(selector: string): (this: BaseType) => DescElement; + +/** + * Given the specified selector, returns a function which returns all descendants of "this" element that match the specified selector. + * + * The generic refers to the type of the returned descendant element. + * + * @param selector A CSS selector string. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function selectorAll(selector: string): (this: BaseType) => NodeListOf; diff --git a/tools/ui/node_modules/@types/d3-selection/package.json b/tools/ui/node_modules/@types/d3-selection/package.json new file mode 100644 index 0000000000000000000000000000000000000000..40493de4043f4d21b2ebd9e109b39ac1474dcb86 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-selection/package.json @@ -0,0 +1,50 @@ +{ + "name": "@types/d3-selection", + "version": "3.0.11", + "description": "TypeScript definitions for d3-selection", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-selection", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + }, + { + "name": "Ambar Mutha", + "githubUsername": "ambar-arkin", + "url": "https://github.com/ambar-arkin" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-selection" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "fefb1bdeb8d385251c2a5f0f16c4a924e80663081d09b1d98f79573a4db8ff6c", + "typeScriptVersion": "4.8" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-shape/LICENSE b/tools/ui/node_modules/@types/d3-shape/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-shape/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-shape/README.md b/tools/ui/node_modules/@types/d3-shape/README.md new file mode 100644 index 0000000000000000000000000000000000000000..22cd74a2b1a1be917f72bd72243fcc63f2f930de --- /dev/null +++ b/tools/ui/node_modules/@types/d3-shape/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-shape` + +# Summary +This package contains type definitions for d3-shape (https://github.com/d3/d3-shape/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-shape. + +### Additional Details + * Last updated: Mon, 12 Jan 2026 09:42:37 GMT + * Dependencies: [@types/d3-path](https://npmjs.com/package/@types/d3-path) + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [denisname](https://github.com/denisname), [Nathan Bierema](https://github.com/Methuselah96), and [Fil](https://github.com/Fil). diff --git a/tools/ui/node_modules/@types/d3-shape/index.d.ts b/tools/ui/node_modules/@types/d3-shape/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d596f65ce47e8b46f27a82fad7da5498f7c4ee4e --- /dev/null +++ b/tools/ui/node_modules/@types/d3-shape/index.d.ts @@ -0,0 +1,2680 @@ +// Last module patch version validated against: 3.1.0 + +import { Path } from "d3-path"; + +declare global { + interface CanvasRenderingContext2D {} // eslint-disable-line @typescript-eslint/no-empty-interface +} + +// ----------------------------------------------------------------------------------- +// Shared Types and Interfaces +// ----------------------------------------------------------------------------------- + +/** + * @deprecated + * This interface is used to bridge the gap between two incompatible versions of TypeScript (see [#25944](https://github.com/Microsoft/TypeScript/pull/25944)). + * Use `CanvasPathMethods` instead with TS <= 3.0 and `CanvasPath` with TS >= 3.1. + */ +export interface CanvasPath_D3Shape { + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + closePath(): void; + ellipse( + x: number, + y: number, + radiusX: number, + radiusY: number, + rotation: number, + startAngle: number, + endAngle: number, + anticlockwise?: boolean, + ): void; + lineTo(x: number, y: number): void; + moveTo(x: number, y: number): void; + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + rect(x: number, y: number, w: number, h: number): void; +} + +// ----------------------------------------------------------------------------------- +// Arc Generator +// ----------------------------------------------------------------------------------- + +/** + * Interface corresponding to the minimum data type assumed by the accessor functions of the Arc generator. + */ +export interface DefaultArcObject { + /** + * Inner radius of arc. + */ + innerRadius: number; + /** + * Outer radius of arc. + */ + outerRadius: number; + /** + * Start angle of arc. The angle is specified in radians, with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + */ + startAngle: number; + /** + * End angle of arc. The angle is specified in radians, with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + */ + endAngle: number; + /** + * Optional. Pad angle of arc in radians. + */ + padAngle?: number | undefined; +} + +/** + * The arc generator produces a circular or annular sector, as in a pie or donut chart. + * + * If the difference between the start and end angles (the angular span) is greater than τ, the arc generator will produce a complete circle or annulus. + * If it is less than τ, arcs may have rounded corners and angular padding. Arcs are always centered at ⟨0,0⟩; use a transform (see: SVG, Canvas) to move the arc to a different position. + * + * See also the pie generator, which computes the necessary angles to represent an array of data as a pie or donut chart; these angles can then be passed to an arc generator. + * + * The first generic corresponds to the type of the "this" context within which the arc generator and its accessor functions will be invoked. + * + * The second generic corresponds to the datum type for which the arc is to be generated. + */ +export interface Arc { + /** + * Generates an arc for the given arguments. + * + * IMPORTANT: If the rendering context of the arc generator is null, + * then the arc is returned as a path data string. + * + * The "this" context within which this function is invoked, will be the context within which the accessor methods of the generator are invoked. + * All arguments passed into this function, will be passed to the accessor functions of the generator. + * + * @param d The datum for which the arc is to be generated. + */ + (this: This, d: Datum, ...args: any[]): string | null; + /** + * Generates an arc for the given arguments. + * + * IMPORTANT: If the arc generator has been configured with a rendering context, + * then the arc is rendered to this context as a sequence of path method calls and this function returns void. + * + * The "this" context within which this function is invoked, will be the context within which the accessor methods of the generator are invoked. + * All arguments passed into this function, will be passed to the accessor functions of the generator. + * + * @param d The datum for which the arc is to be generated. + */ + (this: This, d: Datum, ...args: any[]): void; + + /** + * Computes the midpoint [x, y] of the center line of the arc that would be generated by the given arguments. + * + * To be consistent with the generated arc, the accessors must be deterministic, i.e., return the same value given the same arguments. + * The midpoint is defined as (startAngle + endAngle) / 2 and (innerRadius + outerRadius) / 2. + * + * Note that this is not the geometric center of the arc, which may be outside the arc; + * this method is merely a convenience for positioning labels. + * + * The method is invoked in the same "this" context as the generator was invoked in and + * receives the same arguments that are passed into the arc generator. + * + * @param d The datum for which the arc is to be generated. + */ + centroid(d: Datum, ...args: any[]): [number, number]; + + /** + * Returns the current inner radius accessor, which defaults to a function returning the innerRadius property + * of the first argument passed into it. + */ + innerRadius(): (this: This, d: Datum, ...args: any[]) => number; + /** + * Sets the inner radius to the specified number and returns this arc generator. + * + * Specifying the inner radius as a function is useful for constructing a stacked polar bar chart, often in conjunction with a sqrt scale. + * More commonly, a constant inner radius is used for a donut or pie chart. If the outer radius is smaller than the inner radius, the inner and outer radii are swapped. + * A negative value is treated as zero. + * + * @param radius Constant radius. + */ + innerRadius(radius: number): this; + /** + * Sets the inner radius to the specified function and returns this arc generator. + * + * Specifying the inner radius as a function is useful for constructing a stacked polar bar chart, often in conjunction with a sqrt scale. + * More commonly, a constant inner radius is used for a donut or pie chart. If the outer radius is smaller than the inner radius, the inner and outer radii are swapped. + * A negative value is treated as zero. + * + * @param radius An accessor function returning a number to be used as a radius. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives the same arguments that were passed into the arc generator. + */ + innerRadius(radius: (this: This, d: Datum, ...args: any[]) => number): this; + + /** + * Returns the current outer radius accessor, which defaults to a function returning the outerRadius property + * of the first argument passed into it. + */ + outerRadius(): (this: This, d: Datum, ...args: any[]) => number; + /** + * Sets the outer radius to the specified number and returns this arc generator. + * + * Specifying the outer radius as a function is useful for constructing a coxcomb or polar bar chart, + * often in conjunction with a sqrt scale. More commonly, a constant outer radius is used for a pie or donut chart. + * If the outer radius is smaller than the inner radius, the inner and outer radii are swapped. + * A negative value is treated as zero. + * + * @param radius Constant radius. + */ + outerRadius(radius: number): this; + /** + * Sets the outer radius to the specified function and returns this arc generator. + * + * Specifying the outer radius as a function is useful for constructing a coxcomb or polar bar chart, + * often in conjunction with a sqrt scale. More commonly, a constant outer radius is used for a pie or donut chart. + * If the outer radius is smaller than the inner radius, the inner and outer radii are swapped. + * A negative value is treated as zero. + * + * @param radius An accessor function returning a number to be used as a radius. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives the same arguments that were passed into the arc generator. + */ + outerRadius(radius: (this: This, d: Datum, ...args: any[]) => number): this; + + /** + * Returns the current corner radius accessor, which defaults to a function returning a constant value of zero. + */ + cornerRadius(): (this: This, d: Datum, ...args: any[]) => number; + /** + * Sets the corner radius to the specified number and returns this arc generator. + * + * If the corner radius is greater than zero, the corners of the arc are rounded using circles of the given radius. + * For a circular sector, the two outer corners are rounded; for an annular sector, all four corners are rounded. + * + * The corner radius may not be larger than (outerRadius - innerRadius) / 2. + * In addition, for arcs whose angular span is less than π, the corner radius may be reduced as two adjacent rounded corners intersect. + * This is occurs more often with the inner corners. + * + * @param radius Constant radius. + */ + cornerRadius(radius: number): this; + /** + * Sets the corner radius to the specified function and returns this arc generator. + * + * The corner radius may not be larger than (outerRadius - innerRadius) / 2. + * In addition, for arcs whose angular span is less than π, the corner radius may be reduced as two adjacent rounded corners intersect. + * This is occurs more often with the inner corners. + * + * @param radius An accessor function returning a number to be used as a radius. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives the same arguments that were passed into the arc generator. + */ + cornerRadius(radius: (this: This, d: Datum, ...args: any[]) => number): this; + + /** + * Returns the current start angle accessor, which defaults to a function returning the startAngle property + * of the first argument passed into it. + */ + startAngle(): (this: This, d: Datum, ...args: any[]) => number; + /** + * Sets the start angle to the specified number and returns this arc generator. + * + * The angle is specified in radians, with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + * If |endAngle - startAngle| ≥ τ, a complete circle or annulus is generated rather than a sector. + * + * @param angle Constant angle in radians. + */ + startAngle(angle: number): this; + /** + * Sets the start angle to the specified function and returns this arc generator. + * + * The angle is specified in radians, with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + * If |endAngle - startAngle| ≥ τ, a complete circle or annulus is generated rather than a sector. + * + * @param angle An accessor function returning a number in radians to be used as an angle. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives the same arguments that were passed into the arc generator. + */ + startAngle(angle: (this: This, d: Datum, ...args: any[]) => number): this; + + /** + * Returns the current end angle accessor, which defaults to a function returning the endAngle property + * of the first argument passed into it. + */ + endAngle(): (this: This, d: Datum, ...args: any[]) => number; + /** + * Sets the end angle to the specified number and returns this arc generator. + * + * The angle is specified in radians, with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + * If |endAngle - startAngle| ≥ τ, a complete circle or annulus is generated rather than a sector. + * + * @param angle Constant angle in radians. + */ + endAngle(angle: number): this; + /** + * Sets the end angle to the specified function and returns this arc generator. + * + * The angle is specified in radians, with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + * If |endAngle - startAngle| ≥ τ, a complete circle or annulus is generated rather than a sector. + * + * @param angle An accessor function returning a number in radians to be used as an angle. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives the same arguments that were passed into the arc generator. + */ + endAngle(angle: (this: This, d: Datum, ...args: any[]) => number): this; + + /** + * Returns the current pad angle accessor, which defaults to a function returning the padAngle property + * of the first argument passed into it, or false if no data are passed in or the property is not defined. + */ + padAngle(): (this: This, d: Datum, ...args: any[]) => number | undefined; + /** + * Sets the pad angle to the specified number and returns this arc generator. + * + * The pad angle is converted to a fixed linear distance separating adjacent arcs, defined as padRadius * padAngle. This distance is subtracted equally from the start and end of the arc. + * If the arc forms a complete circle or annulus, as when |endAngle - startAngle| ≥ τ, the pad angle is ignored. If the inner radius or angular span is small relative to the pad angle, + * it may not be possible to maintain parallel edges between adjacent arcs. In this case, the inner edge of the arc may collapse to a point, similar to a circular sector. + * For this reason, padding is typically only applied to annular sectors (i.e., when innerRadius is positive). + * + * The recommended minimum inner radius when using padding is outerRadius * padAngle / sin(θ), where θ is the angular span of the smallest arc before padding. + * For example, if the outer radius is 200 pixels and the pad angle is 0.02 radians, a reasonable θ is 0.04 radians, and a reasonable inner radius is 100 pixels. + * + * Often, the pad angle is not set directly on the arc generator, but is instead computed by the pie generator so as to ensure that the area of padded arcs is proportional to their value; + * see pie.padAngle. See the pie padding animation for illustration. + * If you apply a constant pad angle to the arc generator directly, it tends to subtract disproportionately from smaller arcs, introducing distortion. + * + * @param angle Constant angle in radians. + */ + padAngle(angle: number | undefined): this; + /** + * Sets the pad angle to the specified function and returns this arc generator. + * + * The pad angle is converted to a fixed linear distance separating adjacent arcs, defined as padRadius * padAngle. This distance is subtracted equally from the start and end of the arc. + * If the arc forms a complete circle or annulus, as when |endAngle - startAngle| ≥ τ, the pad angle is ignored. If the inner radius or angular span is small relative to the pad angle, + * it may not be possible to maintain parallel edges between adjacent arcs. In this case, the inner edge of the arc may collapse to a point, similar to a circular sector. + * For this reason, padding is typically only applied to annular sectors (i.e., when innerRadius is positive). + * + * The recommended minimum inner radius when using padding is outerRadius * padAngle / sin(θ), where θ is the angular span of the smallest arc before padding. + * For example, if the outer radius is 200 pixels and the pad angle is 0.02 radians, a reasonable θ is 0.04 radians, and a reasonable inner radius is 100 pixels. + * + * Often, the pad angle is not set directly on the arc generator, but is instead computed by the pie generator so as to ensure that the area of padded arcs is proportional to their value; + * see pie.padAngle. See the pie padding animation for illustration. + * If you apply a constant pad angle to the arc generator directly, it tends to subtract disproportionately from smaller arcs, introducing distortion. + * + * @param angle An accessor function returning a number in radians to be used as an angle. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives the same arguments that were passed into the arc generator. + */ + padAngle(angle: (this: This, d: Datum, ...args: any[]) => number | undefined): this; + + /** + * Returns the current pad radius accessor, which defaults to null, indicating that the pad radius should be automatically computed as sqrt(innerRadius * innerRadius + outerRadius * outerRadius). + */ + padRadius(): ((this: This, d: Datum, ...args: any[]) => number) | null; + /** + * Sets the pad radius to the specified function or number and returns this arc generator. + * The pad radius determines the fixed linear distance separating adjacent arcs, defined as padRadius * padAngle. + */ + padRadius(radius: null | number | ((this: This, d: Datum, ...args: any[]) => number)): this; + + /** + * Returns the current rendering context, which defaults to null. + */ + context(): CanvasRenderingContext2D | null; + /** + * Sets the context and returns this arc generator. + * If context is not specified, returns the current context, which defaults to null. + */ + context(context: CanvasRenderingContext2D | null): this; +} + +/** + * Constructs a new arc generator with the default settings. + * + * Ensure that the accessors used with the arc generator correspond to the arguments passed into them, + * or set them to constants as appropriate. + */ +export function arc(): Arc; +/** + * Constructs a new arc generator with the default settings. + * + * Ensure that the accessors used with the arc generator correspond to the arguments passed into them, + * or set them to constants as appropriate. + * + * The generic corresponds to the datum type representing a arc. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function arc(): Arc; +/** + * Constructs a new arc generator with the default settings. + * + * Ensure that the accessors used with the arc generator correspond to the arguments passed into them, + * or set them to constants as appropriate. + * + * The first generic corresponds to the type of the "this" context within which the arc generator and its accessor functions will be invoked. + * + * The second generic corresponds to the datum type representing a arc. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function arc(): Arc; + +// ----------------------------------------------------------------------------------- +// Pie Generator +// ----------------------------------------------------------------------------------- + +/** + * Element of the Arc Datums Array created by invoking the Pie generator. + * + * The generic refers to the data type of an element in the input array passed into the Pie generator. + */ +export interface PieArcDatum { + /** + * The input datum; the corresponding element in the input data array of the Pie generator. + */ + data: T; + /** + * The numeric value of the arc. + */ + value: number; + /** + * The zero-based sorted index of the arc. + */ + index: number; + /** + * The start angle of the arc. + * If the pie generator was configured to be used for the arc generator, + * then the units are in radians with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + */ + startAngle: number; + /** + * The end angle of the arc. + * If the pie generator was configured to be used for the arc generator, + * then the units are in radians with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + */ + endAngle: number; + /** + * The pad angle of the arc. If the pie generator was configured to be used for the arc generator, than the units are in radians. + */ + padAngle: number; +} + +/** + * The pie generator does not produce a shape directly, but instead computes the necessary angles to represent a tabular dataset as a pie or donut chart; + * these angles can then be passed to an arc generator. + * + * The first generic corresponds to the type of the "this" context within which the pie generator and its accessor functions will be invoked. + * + * The second generic refers to the data type of an element in the input array passed into the Pie generator. + */ +export interface Pie { + /** + * Generates a pie for the given array of data, returning an array of objects representing each datum’s arc angles. + * Any additional arguments are arbitrary; they are simply propagated to the pie generator’s accessor functions along with the this object. + * The length of the returned array is the same as data, and each element i in the returned array corresponds to the element i in the input data. + * + * This representation is designed to work with the arc generator’s default startAngle, endAngle and padAngle accessors. + * The angular units are arbitrary, but if you plan to use the pie generator in conjunction with an arc generator, + * you should specify angles in radians, with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + * + * @param data Array of data elements. + */ + (this: This, data: Datum[], ...args: any[]): Array>; + + /** + * Returns the current value accessor, which defaults to a function returning the first argument passed into it. + * The default value accessor assumes that the input data are numbers, or that they are coercible to numbers using valueOf. + */ + value(): (d: Datum, i: number, data: Datum[]) => number; + /** + * Sets the value accessor to use the specified constant number and returns this pie generator. + * + * @param value Constant value to be used. + */ + value(value: number): this; + /** + * Sets the value accessor to use the specified function and returns this pie generator. + * + * When a pie is generated, the value accessor will be invoked for each element in the input data array. + * The default value accessor assumes that the input data are numbers, or that they are coercible to numbers using valueOf. + * If your data are not simply numbers, then you should specify an accessor that returns the corresponding numeric value for a given datum. + * + * @param value A value accessor function, which is invoked for each element in the input data array, being passed the element d, the index i, and the array data as three arguments. + * It returns a numeric value. + */ + value(value: (d: Datum, i: number, data: Datum[]) => number): this; + + /** + * Returns the current data comparator, which defaults to null. + */ + sort(): ((a: Datum, b: Datum) => number) | null; + /** + * Sets the data comparator to the specified function and returns this pie generator. + * + * If both the data comparator and the value comparator are null, then arcs are positioned in the original input order. + * Otherwise, the data is sorted according to the data comparator, and the resulting order is used. Setting the data comparator implicitly sets the value comparator to null. + * + * Sorting does not affect the order of the generated arc array which is always in the same order as the input data array; it merely affects the computed angles of each arc. + * The first arc starts at the start angle and the last arc ends at the end angle. + * + * @param comparator A compare function takes two arguments a and b, each elements from the input data array. + * If the arc for a should be before the arc for b, then the comparator must return a number less than zero; + * if the arc for a should be after the arc for b, then the comparator must return a number greater than zero; + * returning zero means that the relative order of a and b is unspecified. + */ + sort(comparator: (a: Datum, b: Datum) => number): this; + /** + * Sets the data comparator to null and returns this pie generator. + * + * If both the data comparator and the value comparator are null, then arcs are positioned in the original input order. + * + * @param comparator null, to set the pie generator to use the original input order or use the sortValues comparator, if any. + */ + sort(comparator: null): this; + + /** + * Returns the current value comparator, which defaults to descending value. + */ + sortValues(): ((a: number, b: number) => number) | null; + /** + * Sets the value comparator to the specified function and returns this pie generator. + * + * If both the data comparator and the value comparator are null, then arcs are positioned in the original input order. + * Otherwise, the data is sorted according to the data comparator, and the resulting order is used. + * Setting the value comparator implicitly sets the data comparator to null. + * + * The value comparator is similar to the data comparator, except the two arguments a and b are values derived from the input data array using the value accessor, not the data elements. + * If the arc for a should be before the arc for b, then the comparator must return a number less than zero; + * if the arc for a should be after the arc for b, then the comparator must return a number greater than zero; + * returning zero means that the relative order of a and b is unspecified. + */ + sortValues(comparator: ((a: number, b: number) => number) | null): this; + + /** + * Returns the current start angle accessor, which defaults to a function returning a constant zero. + */ + startAngle(): (this: This, data: Datum[], ...args: any[]) => number; + /** + * Sets the overall start angle of the pie to the specified number and returns this pie generator. + * + * The default start angle is zero. + * + * The start angle here means the overall start angle of the pie, i.e., the start angle of the first arc. + * The start angle accessor is invoked once, being passed the same arguments and this context as the pie generator. + * The units of angle are arbitrary, but if you plan to use the pie generator in conjunction with an arc generator, + * you should specify an angle in radians, with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + * + * @param angle A constant angle. + */ + startAngle(angle: number): this; + /** + * Sets the overall start angle of the pie to the specified function and returns this pie generator. + * + * The default start angle is zero. + * + * The start angle here means the overall start angle of the pie, i.e., the start angle of the first arc. + * The start angle accessor is invoked once, being passed the same arguments and this context as the pie generator. + * The units of angle are arbitrary, but if you plan to use the pie generator in conjunction with an arc generator, + * you should specify an angle in radians, with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + * + * @param angle An angle accessor function, which is invoked once, being passed the same arguments and this context as the pie generator. + */ + startAngle(angle: (this: This, data: Datum[], ...args: any[]) => number): this; + + /** + * Returns the current end angle accessor, which defaults to a function returning a constant 2*pi. + */ + endAngle(): (this: This, data: Datum[], ...args: any[]) => number; + /** + * Sets the overall end angle of the pie to the specified number and returns this pie generator. + * + * The default end angle is 2*pi. + * + * The end angle here means the overall end angle of the pie, i.e., the end angle of the last arc. + * The units of angle are arbitrary, but if you plan to use the pie generator in conjunction with an arc generator, + * you should specify an angle in radians, with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + * + * The value of the end angle is constrained to startAngle ± τ, such that |endAngle - startAngle| ≤ τ. + * + * @param angle A constant angle. + */ + endAngle(angle: number): this; + /** + * Sets the overall end angle of the pie to the specified function and returns this pie generator. + * + * The default end angle is 2*pi. + * + * The end angle here means the overall end angle of the pie, i.e., the end angle of the last arc. + * The end angle accessor is invoked once, being passed the same arguments and this context as the pie generator. + * The units of angle are arbitrary, but if you plan to use the pie generator in conjunction with an arc generator, + * you should specify an angle in radians, with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + * + * The value of the end angle is constrained to startAngle ± τ, such that |endAngle - startAngle| ≤ τ. + * + * @param angle An angle accessor function, which is invoked once, being passed the same arguments and this context as the pie generator. + */ + endAngle(angle: (this: This, data: Datum[], ...args: any[]) => number): this; + + /** + * Returns the current pad angle accessor, which defaults to a function returning a constant zero. + */ + padAngle(): (this: This, data: Datum[], ...args: any[]) => number; + /** + * Sets the pad angle to the specified number and returns this pie generator. + * + * The pad angle here means the angular separation between each adjacent arc. + * The total amount of padding reserved is the specified angle times the number of elements in the input data array, and at most |endAngle - startAngle|; + * the remaining space is then divided proportionally by value such that the relative area of each arc is preserved. + * The units of angle are arbitrary, but if you plan to use the pie generator in conjunction with an arc generator, you should specify an angle in radians. + * + * @param angle A constant angle. + */ + padAngle(angle: number): this; + /** + * Sets the pad angle to the specified function and returns this pie generator. + * + * The pad angle here means the angular separation between each adjacent arc. + * The total amount of padding reserved is the specified angle times the number of elements in the input data array, and at most |endAngle - startAngle|; + * the remaining space is then divided proportionally by value such that the relative area of each arc is preserved. + * The pad angle accessor is invoked once, being passed the same arguments and this context as the pie generator. + * The units of angle are arbitrary, but if you plan to use the pie generator in conjunction with an arc generator, you should specify an angle in radians. + * + * @param angle An angle accessor function, which is invoked once, being passed the same arguments and this context as the pie generator. + */ + padAngle(angle: (this: This, data: Datum[], ...args: any[]) => number): this; +} + +/** + * Constructs a new pie generator with the default settings. + * + * Ensure that the accessors used with the pie generator correspond to the arguments passed into them, + * or set them to constants as appropriate. + */ +export function pie(): Pie; +/** + * Constructs a new pie generator with the default settings. + * + * Ensure that the accessors used with the pie generator correspond to the arguments passed into them, + * or set them to constants as appropriate. + * + * The generic refers to the data type of an element in the input array passed into the Pie generator. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function pie(): Pie; +/** + * Constructs a new pie generator with the default settings. + * + * Ensure that the accessors used with the pie generator correspond to the arguments passed into them, + * or set them to constants as appropriate. + * + * The first generic corresponds to the type of the "this" context within which the pie generator and its accessor functions will be invoked. + * + * The second generic refers to the data type of an element in the input array passed into the Pie generator. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function pie(): Pie; + +// ----------------------------------------------------------------------------------- +// Line Generators +// ----------------------------------------------------------------------------------- + +/** + * The line generator produces a spline or polyline, as in a line chart. + * Lines also appear in many other visualization types, such as the links in hierarchical edge bundling. + * + * The generic refers to the data type of an element in the input array passed into the line generator. + */ +export interface Line { + /** + * Generates a line for the given array of data. Depending on this line generator’s associated curve, + * the given input data may need to be sorted by x-value before being passed to the line generator. + * + * IMPORTANT: If the rendering context of the line generator is null, + * then the line is returned as a path data string. + * + * @param data Array of data elements. + */ + (data: Iterable | Datum[]): string | null; + /** + * Generates a line for the given array of data. Depending on this line generator’s associated curve, + * the given input data may need to be sorted by x-value before being passed to the line generator. + * + * IMPORTANT: If the line generator has been configured with a rendering context, + * then the line is rendered to this context as a sequence of path method calls and this function returns void. + * + * @param data Array of data elements. + */ + (data: Iterable | Datum[]): void; + + /** + * Returns the current x-coordinate accessor function, which defaults to a function returning first element of a two-element array of numbers. + */ + x(): (d: Datum, index: number, data: Datum[]) => number; + /** + * Sets the x accessor to the specified number and returns this line generator. + * + * @param x A constant x-coordinate value. + */ + x(x: number): this; + /** + * Sets the x accessor to the specified function and returns this line generator. + * + * When a line is generated, the x accessor will be invoked for each defined element in the input data array. + * + * The default x accessor assumes that the input data are two-element arrays of numbers. If your data are in a different format, or if you wish to transform the data before rendering, + * then you should specify a custom accessor. + * + * @param x A coordinate accessor function which returns the x-coordinate value. The x accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + x(x: (d: Datum, index: number, data: Datum[]) => number): this; + + /** + * Returns the current y-coordinate accessor function, which defaults to a function returning second element of a two-element array of numbers. + */ + y(): (d: Datum, index: number, data: Datum[]) => number; + /** + * Sets the y accessor to the specified number and returns this line generator. + * + * @param y A constant y-coordinate value. + */ + y(y: number): this; + /** + * Sets the y accessor to the specified function and returns this line generator. + * + * When a line is generated, the y accessor will be invoked for each defined element in the input data array. + * + * The default y accessor assumes that the input data are two-element arrays of numbers. If your data are in a different format, or if you wish to transform the data before rendering, + * then you should specify a custom accessor. + * + * @param y A coordinate accessor function which returns the y-coordinate value. The y accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + y(y: (d: Datum, index: number, data: Datum[]) => number): this; + + /** + * Returns the current defined accessor, which defaults to a function returning a constant boolean value of true. + */ + defined(): (d: Datum, index: number, data: Datum[]) => boolean; + /** + * Sets the defined accessor to the specified boolean and returns this line generator. + * + * The default accessor for defined returns a constant boolean value of true, thus assumes that the input data is always defined. + * + * When a line is generated, the defined accessor will be invoked for each element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + * If the given element is defined (i.e., if the defined accessor returns a truthy value for this element), + * the x and y accessors will subsequently be evaluated and the point will be added to the current line segment. + * Otherwise, the element will be skipped, the current line segment will be ended, and a new line segment will be generated for the next defined point. + * As a result, the generated line may have several discrete segments. + * + * Note that if a line segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. + * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. + * + * @param defined A boolean constant. + */ + defined(defined: boolean): this; + /** + * Sets the defined accessor to the specified function and returns this line generator. + * + * The default accessor for defined returns a constant boolean value of true, thus assumes that the input data is always defined. + * + * When a line is generated, the defined accessor will be invoked for each element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + * If the given element is defined (i.e., if the defined accessor returns a truthy value for this element), + * the x and y accessors will subsequently be evaluated and the point will be added to the current line segment. + * Otherwise, the element will be skipped, the current line segment will be ended, and a new line segment will be generated for the next defined point. + * As a result, the generated line may have several discrete segments. + * + * Note that if a line segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. + * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. + * + * @param defined An accessor function which returns a boolean value. The accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + defined(defined: (d: Datum, index: number, data: Datum[]) => boolean): this; + + /** + * Returns the current curve factory, which defaults to curveLinear. + */ + curve(): CurveFactory | CurveFactoryLineOnly; + /** + * Returns the current curve factory, which defaults to curveLinear. + * + * The generic allows to cast the curve factory to a specific type, if known. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + curve(): C; + /** + * Sets the curve factory and returns this line generator. + * + * @param curve A valid curve factory. + */ + curve(curve: CurveFactory | CurveFactoryLineOnly): this; + + /** + * Returns the current rendering context, which defaults to null. + */ + context(): CanvasRenderingContext2D | null; + /** + * Sets the context and returns this line generator. + */ + context(context: CanvasRenderingContext2D | null): this; +} + +/** + * Constructs a new line generator with the default settings. + * + * If x or y are specified, sets the corresponding accessors to the specified function or number and returns this line generator. + * + * The generic refers to the data type of an element in the input array passed into the line generator. + * + * @param x Sets the x accessor + * @param y Sets the y accessor + */ +export function line( + x?: number | ((d: Datum, index: number, data: Datum[]) => number), + y?: number | ((d: Datum, index: number, data: Datum[]) => number), +): Line; + +/** + * The radial line generator produces a spline or polyline, as in a line chart. + * + * A radial line generator is equivalent to the standard Cartesian line generator, + * except the x and y accessors are replaced with angle and radius accessors. + * Radial lines are always positioned relative to ⟨0,0⟩; use a transform (see: SVG, Canvas) to change the origin. + * + * The generic refers to the data type of an element in the input array passed into the line generator. + */ +export interface LineRadial { + /** + * Generates a radial line for the given array of data. Depending on this radial line generator’s associated curve, + * the given input data may need to be sorted by x-value before being passed to the line generator. + * + * IMPORTANT: If the rendering context of the radial line generator is null, + * then the radial line is returned as a path data string. + * + * @param data Array of data elements. + */ + (data: Iterable | Datum[]): string | null; + /** + * Generates a radial line for the given array of data. Depending on this radial line generator’s associated curve, + * the given input data may need to be sorted by x-value before being passed to the radial line generator. + * + * IMPORTANT: If the radial line generator has been configured with a rendering context, + * then the radial line is rendered to this context as a sequence of path method calls and this function returns void. + * + * @param data Array of data elements. + */ + (data: Iterable | Datum[]): void; + + /** + * Returns the current angle accessor function, which defaults to a function returning first element of a two-element array of numbers. + */ + angle(): (d: Datum, index: number, data: Datum[]) => number; + /** + * Sets the angle accessor to the specified number and returns this radial line generator. + * + * @param angle A constant angle value in radians, with 0 at -y (12 o’clock). + */ + angle(angle: number): this; + /** + * Sets the angle accessor to the specified function and returns this radial line generator. + * + * When a radial line is generated, the angle accessor will be invoked for each defined element in the input data array. + * + * The default angle accessor assumes that the input data are two-element arrays of numbers. If your data are in a different format, or if you wish to transform the data before rendering, + * then you should specify a custom accessor. + * + * @param angle An angle accessor function which returns the angle value in radians, with 0 at -y (12 o’clock). The angle accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + angle(angle: (d: Datum, index: number, data: Datum[]) => number): this; + + /** + * Returns the current radius accessor function, which defaults to a function returning second element of a two-element array of numbers. + */ + radius(): (d: Datum, index: number, data: Datum[]) => number; + /** + * Sets the radius accessor to the specified number and returns this radial line generator. + * + * @param radius A constant radius value. + */ + radius(radius: number): this; + /** + * Sets the radius accessor to the specified function and returns this radial line generator. + * + * When a radial line is generated, the radius accessor will be invoked for each defined element in the input data array. + * + * The default radius accessor assumes that the input data are two-element arrays of numbers. If your data are in a different format, or if you wish to transform the data before rendering, + * then you should specify a custom accessor. + * + * @param radius A radius accessor function which returns the radius value. The radius accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + radius(radius: (d: Datum, index: number, data: Datum[]) => number): this; + + /** + * Returns the current defined accessor, which defaults to a function returning a constant boolean value of true. + */ + defined(): (d: Datum, index: number, data: Datum[]) => boolean; + /** + * Sets the defined accessor to the specified boolean and returns this radial line generator. + * + * The default accessor for defined returns a constant boolean value of true, thus assumes that the input data is always defined. + * + * When a radial line is generated, the defined accessor will be invoked for each element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + * If the given element is defined (i.e., if the defined accessor returns a truthy value for this element), + * the angle and radius accessors will subsequently be evaluated and the point will be added to the current radial line segment. + * Otherwise, the element will be skipped, the current radial line segment will be ended, and a new radial line segment will be generated for the next defined point. + * As a result, the generated radial line may have several discrete segments. + * + * Note that if a radial line segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. + * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. + * + * @param defined A boolean constant. + */ + defined(defined: boolean): this; + /** + * Sets the defined accessor to the specified function and returns this radial line generator. + * + * The default accessor for defined returns a constant boolean value of true, thus assumes that the input data is always defined. + * + * When a radial line is generated, the defined accessor will be invoked for each element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + * If the given element is defined (i.e., if the defined accessor returns a truthy value for this element), + * the angle and radius accessors will subsequently be evaluated and the point will be added to the current radial line segment. + * Otherwise, the element will be skipped, the current radial line segment will be ended, and a new radial line segment will be generated for the next defined point. + * As a result, the generated radial line may have several discrete segments. + * + * Note that if a radial line segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. + * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. + * + * @param defined An accessor function which returns a boolean value. The accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + defined(defined: (d: Datum, index: number, data: Datum[]) => boolean): this; + + /** + * Returns the current curve factory, which defaults to curveLinear. + */ + curve(): CurveFactory | CurveFactoryLineOnly; + /** + * Returns the current curve factory, which defaults to curveLinear. + * + * The generic allows to cast the curve factory to a specific type, if known. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + curve(): C; + /** + * Sets the curve factory and returns this radial line generator. + * + * Note that curveMonotoneX or curveMonotoneY are not recommended for radial lines because they assume that the data is monotonic in x or y, + * which is typically untrue of radial lines. + * + * @param curve A valid curve factory. + */ + curve(curve: CurveFactory | CurveFactoryLineOnly): this; + + /** + * Returns the current rendering context, which defaults to null. + */ + context(): CanvasRenderingContext2D | null; + /** + * Equivalent to line.context. + */ + context(context: CanvasRenderingContext2D | null): this; +} + +/** + * Constructs a new radial line generator with the default settings. + * + * Ensure that the accessors used with the radial line generator correspond to the arguments passed into them, + * or set them to constants as appropriate. + */ +export function lineRadial(): LineRadial<[number, number]>; +/** + * Constructs a new radial line generator with the default settings. + * + * Ensure that the accessors used with the radial line generator correspond to the arguments passed into them, + * or set them to constants as appropriate. + * + * The generic refers to the data type of an element in the input array passed into the radial line generator. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function lineRadial(): LineRadial; + +/** + * @deprecated Use LineRadial + */ +export type RadialLine = LineRadial; + +/** + * @deprecated Use lineRadial() + */ +export function radialLine(): RadialLine<[number, number]>; +/** + * @deprecated Use lineRadial() + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function radialLine(): RadialLine; + +// ----------------------------------------------------------------------------------- +// Area Generators +// ----------------------------------------------------------------------------------- + +/** + * The area generator produces an area, as in an area chart. An area is defined by two bounding lines, either splines or polylines. + * Typically, the two lines share the same x-values (x0 = x1), differing only in y-value (y0 and y1); most commonly, y0 is defined as a constant representing zero. + * The first line (the topline) is defined by x1 and y1 and is rendered first; the second line (the baseline) is defined by x0 and y0 and is rendered second, with the points in reverse order. + * With a curveLinear curve, this produces a clockwise polygon. + * + * The generic refers to the data type of an element in the input array passed into the area generator. + */ +export interface Area { + /** + * Generates an area for the given array of data. Depending on this area generator’s associated curve, + * the given input data may need to be sorted by x-value before being passed to the area generator. + * + * IMPORTANT: If the rendering context of the area generator is null, + * then the area is returned as a path data string. + * + * @param data Array of data elements. + */ + (data: Iterable | Datum[]): string | null; + /** + * Generates an area for the given array of data. Depending on this area generator’s associated curve, + * the given input data may need to be sorted by x-value before being passed to the area generator. + * + * IMPORTANT: If the area generator has been configured with a rendering context, + * then the area is rendered to this context as a sequence of path method calls and this function returns void. + * + * @param data Array of data elements. + */ + (data: Iterable | Datum[]): void; + + /** + * Returns the current x0 accessor. The default x0 accessor is a function returning the first element of a + * two-element array of numbers. + */ + x(): (d: Datum, index: number, data: Datum[]) => number; + /** + * Sets x0 to a constant number x and x1 to null and returns this area generator. + * + * Setting x1 to null indicates that the previously-computed x0 value should be reused for the x1 value. + * + * @param x A constant value to be used for x0. + */ + x(x: number): this; + /** + * Sets x0 to the specified function x and x1 to null and returns this area generator. + * + * The default x0 accessor assumes that the input data are two-element arrays of numbers and returns the first element. + * If your data are in a different format, or if you wish to transform the data before rendering, then you should specify a custom accessor. + * + * @param x An accessor function returning a value to be used for x0. The accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + x(x: (d: Datum, index: number, data: Datum[]) => number): this; + + /** + * Returns the current x0 accessor. The default x0 accessor is a function returning the first element of a + * two-element array of numbers. + */ + x0(): (d: Datum, index: number, data: Datum[]) => number; + /** + * Sets x0 to a constant number and returns this area generator. + * + * @param x A constant value. + */ + x0(x: number): this; + /** + * Sets x0 to the specified function and returns this area generator. + * + * The default x0 accessor assumes that the input data are two-element arrays of numbers and returns the first element. + * If your data are in a different format, or if you wish to transform the data before rendering, then you should specify a custom accessor. + * + * @param x An accessor function returning a value to be used for x0. The accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + x0(x: (d: Datum, index: number, data: Datum[]) => number): this; + + /** + * Returns the current x1 accessor, which defaults to null, indicating that the previously-computed x0 value should be reused for the x1 value. + */ + x1(): ((d: Datum, index: number, data: Datum[]) => number) | null; + /** + * Sets the x1 accessor to the specified number and returns this area generator. + */ + x1(x: null | number): this; + /** + * Sets x1 to the specified function and returns this area generator. + * + * The default x1 accessor is null, indicating that the previously-computed x0 value should be reused for the x1 value. + * If your data are in a different format, or if you wish to transform the data before rendering, then you should specify a custom accessor. + * + * @param x An accessor function returning a value to be used for x1. The accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + x1(x: (d: Datum, index: number, data: Datum[]) => number): this; + + /** + * Returns the current y0 accessor. The default y0 accessor is a function returning a constant value of zero. + */ + y(): (d: Datum, index: number, data: Datum[]) => number; + /** + * Sets y0 to a constant number y and y1 to null and returns this area generator. + * + * Setting y1 to null indicates that the previously-computed y0 value should be reused for the y1 value. + * + * @param y A constant value to be used for y0. + */ + y(y: number): this; + /** + * Sets y0 to the accessor function y and y1 to null and returns this area generator. + * + * The default y0 accessor returns a constant value of zero. + * If your data are in a different format, or if you wish to transform the data before rendering, then you should specify a custom accessor. + * + * @param y An accessor function returning a value to be used for y0. The accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + y(y: (d: Datum, index: number, data: Datum[]) => number): this; + + /** + * Returns the current y0 accessor. The default y0 accessor is a function a constant value of zero. + */ + y0(): (d: Datum, index: number, data: Datum[]) => number; + /** + * Sets y0 to a constant number and returns this area generator. + * + * @param y A constant value. + */ + y0(y: number): this; + /** + * Sets y0 to the specified function and returns this area generator. + * + * The default y0 accessor is a function which returns a constant value of zero. + * If your data are in a different format, or if you wish to transform the data before rendering, then you should specify a custom accessor. + * + * @param y An accessor function returning a value to be used for y0. The accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + y0(y: (d: Datum, index: number, data: Datum[]) => number): this; + + /** + * Returns the current y1 accessor or null. The default y1 accessor is a function returning the second element of a + * two-element array of numbers. + * + * If the y1 accessor is null, the previously-computed y0 value is reused for the y1 value. + */ + y1(): ((d: Datum, index: number, data: Datum[]) => number) | null; + /** + * sets the y1 accessor to the specified number and returns this area generator. + */ + y1(y: null | number): this; + /** + * Sets y1 to the specified function and returns this area generator. + * + * The default y1 accessor assumes that the input data are two-element arrays of numbers and returns the second element. + * If your data are in a different format, or if you wish to transform the data before rendering, then you should specify a custom accessor. + * + * @param y An accessor function returning a value to be used for y1. The accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + y1(y: (d: Datum, index: number, data: Datum[]) => number): this; + + /** + * Returns the current defined accessor, which defaults to a function returning a constant boolean value of true. + */ + defined(): (d: Datum, index: number, data: Datum[]) => boolean; + /** + * Sets the defined accessor to the specified boolean and returns this area generator. + * + * The default accessor for defined returns a constant boolean value of true, thus assumes that the input data is always defined. + * When an area is generated, the defined accessor will be invoked for each element in the input data array, being passed the element d, the index i, and the array data as three arguments. + * If the given element is defined (i.e., if the defined accessor returns a truthy value for this element), + * the x0, x1, y0 and y1 accessors will subsequently be evaluated and the point will be added to the current area segment. + * Otherwise, the element will be skipped, the current area segment will be ended, and a new area segment will be generated for the next defined point. + * As a result, the generated area may have several discrete segments. + * + * Note that if an area segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. + * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. + * + * @param defined A boolean constant. + */ + defined(defined: boolean): this; + /** + * Sets the defined accessor to the specified function and returns this area generator. + * + * The default accessor for defined returns a constant boolean value of true, thus assumes that the input data is always defined. + * + * The default accessor for defined returns a constant boolean value of true, thus assumes that the input data is always defined. + * When an area is generated, the defined accessor will be invoked for each element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + * If the given element is defined (i.e., if the defined accessor returns a truthy value for this element), + * the x0, x1, y0 and y1 accessors will subsequently be evaluated and the point will be added to the current area segment. + * Otherwise, the element will be skipped, the current area segment will be ended, and a new area segment will be generated for the next defined point. + * As a result, the generated area may have several discrete segments. + * + * Note that if an area segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. + * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. + * + * @param defined An accessor function which returns a boolean value. The accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + defined(defined: (d: Datum, index: number, data: Datum[]) => boolean): this; + + /** + * Returns the current curve factory, which defaults to curveLinear. + */ + curve(): CurveFactory; + /** + * Returns the current curve factory, which defaults to curveLinear. + * + * The generic allows to cast the curve factory to a specific type, if known. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + curve(): C; + /** + * Sets the curve factory and returns this area generator. + * + * @param curve A valid curve factory. + */ + curve(curve: CurveFactory): this; + + /** + * Returns the current rendering context, which defaults to null. + */ + context(): CanvasRenderingContext2D | null; + /** + * Sets the context and returns this area generator. + */ + context(context: CanvasRenderingContext2D | null): this; + + /** + * Returns a new line generator that has this area generator’s current defined accessor, curve and context. + * The line’s x-accessor is this area’s x0-accessor, and the line’s y-accessor is this area’s y0-accessor. + */ + lineX0(): Line; + /** + * Returns a new line generator that has this area generator’s current defined accessor, curve and context. + * The line’s x-accessor is this area’s x0-accessor, and the line’s y-accessor is this area’s y0-accessor. + */ + lineY0(): Line; + + /** + * Returns a new line generator that has this area generator’s current defined accessor, curve and context. + * The line’s x-accessor is this area’s x1-accessor, and the line’s y-accessor is this area’s y0-accessor. + */ + lineX1(): Line; + /** + * Returns a new line generator that has this area generator’s current defined accessor, curve and context. + * The line’s x-accessor is this area’s x0-accessor, and the line’s y-accessor is this area’s y1-accessor. + */ + lineY1(): Line; +} + +/** + * Constructs a new area generator with the default settings. + * + * If x, y0 or y1 are specified, sets the corresponding accessors to the specified function or number and returns this area generator. + * + * The generic refers to the data type of an element in the input array passed into the area generator. + * + * @param x Sets the x accessor. + * @param y0 Sets the y0 accessor. + * @param y1 Sets the y1 accessor. + */ +export function area( + x?: number | ((d: Datum, index: number, data: Datum[]) => number), + y0?: number | ((d: Datum, index: number, data: Datum[]) => number), + y1?: number | ((d: Datum, index: number, data: Datum[]) => number), +): Area; + +/** + * A radial area generator. + * + * A radial area generator is equivalent to the standard Cartesian area generator, + * except the x and y accessors are replaced with angle and radius accessors. + * Radial areas are always positioned relative to ⟨0,0⟩; use a transform (see: SVG, Canvas) to change the origin. + * + * The generic refers to the data type of an element in the input array passed into the area generator. + */ +export interface AreaRadial { + /** + * Generates a radial area for the given array of data. + * + * IMPORTANT: If the rendering context of the radial area generator is null, + * then the radial area is returned as a path data string. + * + * @param data Array of data elements. + */ + (data: Iterable | Datum[]): string | null; + /** + * Generates a radial area for the given array of data. + * + * IMPORTANT: If the radial area generator has been configured with a rendering context, + * then the radial area is rendered to this context as a sequence of path method calls and this function returns void. + * + * @param data Array of data elements. + */ + (data: Iterable | Datum[]): void; + + /** + * Returns the current startAngle accessor. The default startAngle accessor is a function returning the first element of a + * two-element array of numbers. + */ + angle(): (d: Datum, index: number, data: Datum[]) => number; + /** + * Sets startAngle to a constant number angle and endAngle to null and returns this radial area generator. + * + * Setting endAngle to null indicates that the previously-computed startAngle value should be reused for the endAngle value. + * + * @param angle A constant value in radians with 0 at -y (12 o’clock). + */ + angle(angle: number): this; + /** + * Sets startAngle to the specified function angle and endAngle to null and returns this radial area generator. + * + * The default startAngle accessor assumes that the input data are two-element arrays of numbers and returns the first element. + * If your data are in a different format, or if you wish to transform the data before rendering, then you should specify a custom accessor. + * + * @param angle An accessor function returning a value to be used for startAngle in radians with 0 at -y (12 o’clock). + * The accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + angle(angle: (d: Datum, index: number, data: Datum[]) => number): this; + + /** + * Returns the current startAngle accessor. The default startAngle accessor is a function returning the first element of a + * two-element array of numbers. + */ + startAngle(): (d: Datum, index: number, data: Datum[]) => number; + /** + * Sets startAngle to a constant number and returns this radial area generator. + * + * @param angle A constant value in radians with 0 at -y (12 o’clock). + */ + startAngle(angle: number): this; + /** + * Sets startAngle to the specified function and returns this radial area generator. + * + * The default startAngle accessor assumes that the input data are two-element arrays of numbers and returns the first element. + * If your data are in a different format, or if you wish to transform the data before rendering, then you should specify a custom accessor. + * + * @param angle An accessor function returning a value to be used for startAngle in radians with 0 at -y (12 o’clock). + * The accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + startAngle(angle: (d: Datum, index: number, data: Datum[]) => number): this; + + /** + * Returns the current endAngle accessor, which defaults to null, indicating that the previously-computed startAngle value should be reused for the endAngle value. + */ + endAngle(): ((d: Datum, index: number, data: Datum[]) => number) | null; + /** + * Equivalent to area.x1, except the accessor returns the angle in radians, with 0 at -y (12 o’clock). + * Note: typically angle is used instead of setting separate start and end angles. + */ + endAngle(angle: null | number): this; + /** + * Sets endAngle to the specified function and returns this radial area generator. + * + * The default endAngle accessor is null, indicating that the previously-computed startAngle value should be reused for the endAngle value. + * If your data are in a different format, or if you wish to transform the data before rendering, then you should specify a custom accessor. + * + * @param angle An accessor function returning a value to be used for endAngle in radians with 0 at -y (12 o’clock). + * The accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + endAngle(angle: (d: Datum, index: number, data: Datum[]) => number): this; + + /** + * Returns the current innerRadius accessor. The default innerRadius accessor is a function returning a constant value of zero. + */ + radius(): (d: Datum, index: number, data: Datum[]) => number; + /** + * Sets innerRadius to a constant number radius and outerRadius to null and returns this radial area generator. + * + * Setting outerRadius to null indicates that the previously-computed innerRadius value should be reused for the outerRadius value. + * + * @param radius A constant value to be used for innerRadius. + */ + radius(radius: number): this; + /** + * Sets innerRadius to the accessor function radius and outerRadius to null and returns this radial area generator. + * + * The default innerRadius accessor returns a constant value of zero. + * If your data are in a different format, or if you wish to transform the data before rendering, then you should specify a custom accessor. + * + * @param radius An accessor function returning a value to be used for innerRadius. The accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + radius(radius: (d: Datum, index: number, data: Datum[]) => number): this; + + /** + * Returns the current innerRadius accessor. The default innerRadius accessor is a function a constant value of zero. + */ + innerRadius(): (d: Datum, index: number, data: Datum[]) => number; + /** + * Sets innerRadius to a constant number and returns this radial area generator. + * + * @param radius A constant value. + */ + innerRadius(radius: number): this; + /** + * Sets innerRadius to the specified function and returns this radial area generator. + * + * The default innerRadius accessor is a function which returns a constant value of zero. + * If your data are in a different format, or if you wish to transform the data before rendering, then you should specify a custom accessor. + * + * @param radius An accessor function returning a value to be used for innerRadius. The accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + innerRadius(radius: (d: Datum, index: number, data: Datum[]) => number): this; + + /** + * Returns the current outerRadius accessor or null. The default outerRadius accessor is a function returning the second element of a + * two-element array of numbers. + * + * If the outerRadius accessor is null, the previously-computed innerRadius value is reused for the outerRadius value. + */ + outerRadius(): ((d: Datum, index: number, data: Datum[]) => number) | null; + /** + * Equivalent to area.y1, except the accessor returns the radius: the distance from the origin ⟨0,0⟩. + */ + outerRadius(radius: null | number): this; + /** + * Sets outerRadius to the specified function and returns this radial area generator. + * + * The default outerRadius accessor assumes that the input data are two-element arrays of numbers and returns the second element. + * If your data are in a different format, or if you wish to transform the data before rendering, then you should specify a custom accessor. + * + * @param radius An accessor function returning a value to be used for outerRadius. The accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + outerRadius(radius: (d: Datum, index: number, data: Datum[]) => number): this; + + /** + * Returns the current defined accessor, which defaults to a function returning a constant boolean value of true. + */ + defined(): (d: Datum, index: number, data: Datum[]) => boolean; + /** + * Sets the defined accessor to the specified boolean and returns this radial area generator. + * + * The default accessor for defined returns a constant boolean value of true, thus assumes that the input data is always defined. + * + * When a radial area is generated, the defined accessor will be invoked for each element in the input data array, being passed the element d, the index i, and the array data as three arguments. + * If the given element is defined (i.e., if the defined accessor returns a truthy value for this element), + * the startAngle, endAngle, innerRadius and outerRadius accessors will subsequently be evaluated and the point will be added to the current area segment. + * + * Otherwise, the element will be skipped, the current area segment will be ended, and a new area segment will be generated for the next defined point. + * As a result, the generated area may have several discrete segments. + * + * Note that if an area segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. + * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. + * + * @param defined A boolean constant. + */ + defined(defined: boolean): this; + /** + * Sets the defined accessor to the specified function and returns this radial area generator. + * + * The default accessor for defined returns a constant boolean value of true, thus assumes that the input data is always defined. + * + * When a radial area is generated, the defined accessor will be invoked for each element in the input data array, being passed the element d, the index i, and the array data as three arguments. + * If the given element is defined (i.e., if the defined accessor returns a truthy value for this element), + * the startAngle, endAngle, innerRadius and outerRadius accessors will subsequently be evaluated and the point will be added to the current area segment. + * + * Otherwise, the element will be skipped, the current area segment will be ended, and a new area segment will be generated for the next defined point. + * As a result, the generated area may have several discrete segments. + * + * Note that if an area segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. + * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. + * + * @param defined An accessor function which returns a boolean value. The accessor will be invoked for each defined element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + */ + defined(defined: (d: Datum, index: number, data: Datum[]) => boolean): this; + + /** + * Returns the current curve factory, which defaults to curveLinear. + */ + curve(): CurveFactory; + /** + * Returns the current curve factory, which defaults to curveLinear. + * + * The generic allows to cast the curve factory to a specific type, if known. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + curve(): C; + /** + * Sets the curve factory and returns this radial area generator. + * + * Note that curveMonotoneX or curveMonotoneY are not recommended for radial areas because they assume that the data is monotonic in x or y, which is typically untrue of radial areas. + * + * @param curve A valid curve factory. + */ + curve(curve: CurveFactory): this; + + /** + * Returns the current rendering context, which defaults to null. + */ + context(): CanvasRenderingContext2D | null; + /** + * Equivalent to line.context. + */ + context(context: CanvasRenderingContext2D | null): this; + + /** + * Returns a new radial line generator that has this radial area generator’s current defined accessor, curve and context. + * The line’s angle accessor is this area’s start angle accessor, and the line’s radius accessor is this area’s inner radius accessor. + */ + lineStartAngle(): LineRadial; + + /** + * Returns a new radial line generator that has this radial area generator’s current defined accessor, curve and context. + * The line’s angle accessor is this area’s start angle accessor, and the line’s radius accessor is this area’s inner radius accessor. + */ + lineInnerRadius(): LineRadial; + + /** + * Returns a new radial line generator that has this radial area generator’s current defined accessor, curve and context. + * The line’s angle accessor is this area’s end angle accessor, and the line’s radius accessor is this area’s inner radius accessor. + */ + lineEndAngle(): LineRadial; + + /** + * Returns a new radial line generator that has this radial area generator’s current defined accessor, curve and context. + * The line’s angle accessor is this area’s start angle accessor, and the line’s radius accessor is this area’s outer radius accessor. + */ + lineOuterRadius(): LineRadial; +} + +/** + * Constructs a new radial area generator with the default settings. + * + * Ensure that the accessors used with the area generator correspond to the arguments passed into them, + * or set them to constants as appropriate. + */ +export function areaRadial(): AreaRadial<[number, number]>; +/** + * Constructs a new radial area generator with the default settings. + * + * Ensure that the accessors used with the area generator correspond to the arguments passed into them, + * or set them to constants as appropriate. + * + * The generic refers to the data type of an element in the input array passed into the radial area generator. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function areaRadial(): AreaRadial; + +/** + * @deprecated Use AreaRadial interface + */ +export type RadialArea = AreaRadial; + +/** + * @deprecated Use areaRadial() + */ +export function radialArea(): RadialArea<[number, number]>; +/** + * @deprecated Use areaRadial() + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function radialArea(): RadialArea; + +// ----------------------------------------------------------------------------------- +// Curve Factories +// ----------------------------------------------------------------------------------- + +/** + * A minimal interface for a curve generator which supports only the rendering of lines. + * Methods for related to the rendering of areas are not implemented in this minimal interface. + * + * While lines are defined as a sequence of two-dimensional [x, y] points, + * there remains the task of transforming this discrete representation into a continuous shape: i.e., how to interpolate between the points. + * A curve generator serves this purpose. + * + * Curves are typically not constructed or used directly, instead being passed to line.curve. + */ +export interface CurveGeneratorLineOnly { + /** + * Indicates the start of a new line segment. Zero or more points will follow. + */ + lineStart(): void; + /** + * Indicates the end of the current line segment. + */ + lineEnd(): void; + /** + * Indicates a new point in the current line segment with the given x- and y-values. + */ + point(x: number, y: number): void; +} + +/** + * A factory for curve generators addressing only lines, but not areas. + */ +export type CurveFactoryLineOnly = + /** + * Returns a "lines only" curve generator which renders to the specified context. + * + * @param context A rendering context. + */ + (context: CanvasRenderingContext2D | Path) => CurveGeneratorLineOnly; + +/** + * A minimal interface for a curve generator which supports the rendering of lines and areas. + * + * While lines are defined as a sequence of two-dimensional [x, y] points, + * and areas are similarly defined by a topline and a baseline, + * there remains the task of transforming this discrete representation into a continuous shape: i.e., how to interpolate between the points. + * A curve generator serves this purpose. + * + * Curves are typically not constructed or used directly, instead being passed to line.curve and area.curve. + */ +export interface CurveGenerator extends CurveGeneratorLineOnly { + /** + * Indicates the start of a new area segment. + * Each area segment consists of exactly two line segments: the topline, followed by the baseline, with the baseline points in reverse order. + */ + areaStart(): void; + /** + * Indicates the end of the current area segment. + */ + areaEnd(): void; +} + +/** + * A factory for curve generators addressing both lines and areas. + */ +export type CurveFactory = + /** + * Returns a curve generator which renders to the specified context. + * + * @param context A rendering context. + */ + (context: CanvasRenderingContext2D | Path) => CurveGenerator; + +/** + * A curve factory for cubic basis spline generators. + * + * The curve generators produce a cubic basis spline using the specified control points. + * The first and last points are triplicated such that the spline starts at the first point and ends at the last point, + * and is tangent to the line between the first and second points, and to the line between the penultimate and last points. + */ +export const curveBasis: CurveFactory; + +/** + * A curve factory for closed cubic basis spline generators. + * + * The curve generators produce a closed cubic basis spline using the specified control points. + * When a line segment ends, the first three control points are repeated, producing a closed loop with C2 continuity. + */ +export const curveBasisClosed: CurveFactory; + +/** + * A curve factory for open cubic basis spline generators. + * + * The curve generators produce a cubic basis spline using the specified control points. + * Unlike basis, the first and last points are not repeated, and thus the curve typically does not intersect these points. + */ +export const curveBasisOpen: CurveFactory; + +/** + * Produces a Bézier curve between each pair of points, with horizontal tangents at each point. + */ +export const curveBumpX: CurveFactory; + +/** + * Produces a Bézier curve between each pair of points, with vertical tangents at each point. + */ +export const curveBumpY: CurveFactory; + +/** + * A curve factory for straightened cubic basis spline generators. + * + * The curve generators produce a straightened cubic basis spline using the specified control points, + * with the spline straightened according to the curve’s beta, which defaults to 0.85. + * This curve is typically used in hierarchical edge bundling to disambiguate connections, + * as proposed by Danny Holten in Hierarchical Edge Bundles: Visualization of Adjacency Relations in Hierarchical Data. + * + * This curve does not implement curve.areaStart and curve.areaEnd; it is intended to work with d3.line, not d3.area. + */ +export interface CurveBundleFactory extends CurveFactoryLineOnly { + /** + * Returns a bundle curve factory with the specified beta in the range [0, 1], representing the bundle strength. + * If beta equals zero, a straight line between the first and last point is produced; if beta equals one, + * a standard basis spline is produced. + * + * @param beta A constant value in the [0, 1] interval. + */ + beta(beta: number): this; +} + +/** + * A curve factory for straightened cubic basis spline generators. + * + * The curve generators produce a straightened cubic basis spline using the specified control points, + * with the spline straightened according to the curve’s beta, which defaults to 0.85. + * This curve is typically used in hierarchical edge bundling to disambiguate connections, + * as proposed by Danny Holten in Hierarchical Edge Bundles: Visualization of Adjacency Relations in Hierarchical Data. + * + * This curve does not implement curve.areaStart and curve.areaEnd; it is intended to work with d3.line, not d3.area. + */ +export const curveBundle: CurveBundleFactory; + +/** + * A curve factory for cubic cardinal spline generators. + */ +export interface CurveCardinalFactory extends CurveFactory { + /** + * Returns a cardinal curve factory with the specified tension in the range [0, 1]. + * The tension determines the length of the tangents: a tension of one yields all zero tangents, equivalent to curveLinear; a tension of zero produces a uniform Catmull–Rom spline. + * + * @param tension A constant in the [0, 1] interval. + */ + tension(tension: number): this; +} + +/** + * A curve factory for cubic cardinal spline generators. + * + * The curve generators produce a cubic cardinal spline using the specified control points, with one-sided differences used for the first and last piece. + * The default tension is 0. + */ +export const curveCardinal: CurveCardinalFactory; + +/** + * A curve factory for closed cubic cardinal spline generators. + * + * The curve generators produce closed cubic cardinal spline using the specified control points. + * When a line segment ends, the first three control points are repeated, producing a closed loop. + * The default tension is 0. + */ +export const curveCardinalClosed: CurveCardinalFactory; + +/** + * A curve factory for open cubic cardinal spline generators. + * + * The curve generators produce a cubic cardinal spline using the specified control points. + * Unlike curveCardinal, one-sided differences are not used for the first and last piece, + * and thus the curve starts at the second point and ends at the penultimate point. + * The default tension is 0. + */ +export const curveCardinalOpen: CurveCardinalFactory; + +/** + * A curve factory for cubic Catmull–Rom spline generators. + */ +export interface CurveCatmullRomFactory extends CurveFactory { + /** + * Returns a cubic Catmull–Rom curve factory with the specified alpha in the range [0, 1]. + * If alpha is zero, produces a uniform spline, equivalent to curveCardinal with a tension of zero; + * if alpha is one, produces a chordal spline; if alpha is 0.5, produces a centripetal spline. + * Centripetal splines are recommended to avoid self-intersections and overshoot. + * + * @param alpha A constant in the [0, 1] interval. + */ + alpha(alpha: number): this; +} + +/** + * A curve factory for cubic Catmull–Rom spline generators. + * + * The curve generators produce a cubic Catmull–Rom spline using the specified control points and the parameter alpha, + * which defaults to 0.5, as proposed by Yuksel et al. in On the Parameterization of Catmull–Rom Curves, + * with one-sided differences used for the first and last piece. + */ +export const curveCatmullRom: CurveCatmullRomFactory; + +/** + * A curve factory for cubic Catmull–Rom spline generators. + * + * The curve generators produce a closed cubic Catmull–Rom spline using the specified control points and the parameter alpha, + * which defaults to 0.5, as proposed by Yuksel et al. When a line segment ends, + * the first three control points are repeated, producing a closed loop. + */ +export const curveCatmullRomClosed: CurveCatmullRomFactory; + +/** + * A curve factory for cubic Catmull–Rom spline generators. + * + * The curve generators produce a cubic Catmull–Rom spline using the specified control points and the parameter alpha, + * which defaults to 0.5, as proposed by Yuksel et al. Unlike curveCatmullRom, one-sided differences are not used for the first and last piece, + * and thus the curve starts at the second point and ends at the penultimate point. + */ +export const curveCatmullRomOpen: CurveCatmullRomFactory; + +/** + * A curve factory for polyline generators. + * + * The curve generators produce a polyline through the specified points. + */ +export const curveLinear: CurveFactory; + +/** + * A curve factory for closed polyline generators. + * + * The curve generators produce a closed polyline through the specified points by repeating the first point when the line segment ends. + */ +export const curveLinearClosed: CurveFactory; + +/** + * A curve factory for cubic spline generators preserving monotonicity in y. + * + * The curve generators produce a cubic spline that preserves monotonicity in y, assuming monotonicity in x, as proposed by Steffen in A simple method for monotonic interpolation in one dimension: + * “a smooth curve with continuous first-order derivatives that passes through any given set of data points without spurious oscillations. + * Local extrema can occur only at grid points where they are given by the data, but not in between two adjacent grid points.” + */ +export const curveMonotoneX: CurveFactory; + +/** + * A curve factory for cubic spline generators preserving monotonicity in x. + * + * The curve generators produce a cubic spline that preserves monotonicity in x, assuming monotonicity in y, as proposed by Steffen in A simple method for monotonic interpolation in one dimension: + * “a smooth curve with continuous first-order derivatives that passes through any given set of data points without spurious oscillations. + * Local extrema can occur only at grid points where they are given by the data, but not in between two adjacent grid points.” + */ +export const curveMonotoneY: CurveFactory; + +/** + * A curve factory for natural cubic spline generators. + * + * The curve generators produce a natural cubic spline with the second derivative of the spline set to zero at the endpoints. + */ +export const curveNatural: CurveFactory; + +/** + * A curve factory for step function (midpoint) generators. + * + * The curve generators produce a piecewise constant function (a step function) consisting of alternating horizontal and vertical lines. + * The y-value changes at the midpoint of each pair of adjacent x-values. + */ +export const curveStep: CurveFactory; + +/** + * A curve factory for step function (after) generators. + * + * The curve generators produce a piecewise constant function (a step function) consisting of alternating horizontal and vertical lines. + * The y-value changes after the x-value. + */ +export const curveStepAfter: CurveFactory; + +/** + * A curve factory for step function (before) generators. + * + * The curve generators produce a piecewise constant function (a step function) consisting of alternating horizontal and vertical lines. + * The y-value changes before the x-value. + */ +export const curveStepBefore: CurveFactory; + +// ----------------------------------------------------------------------------------- +// LINKS +// ----------------------------------------------------------------------------------- + +/** + * An interface describing the default Link Data structure expected + * by the Link and LinkRadial generators. + */ +export interface DefaultLinkObject { + /** + * Source node of the link. + * + * For a link in a Cartesian coordinate system, the two element array contains + * the coordinates [x, y]. + * + * For a radial link, the two element array contains + * the coordinates [angle, radius]. The angle is stated in radians, with 0 at -y (12 o’clock). + * The radius measures the distance from the origin ⟨0,0⟩. + */ + source: [number, number]; + /** + * Target node of the link. + * + * For a link in a Cartesian coordinate system, the two element array contains + * the coordinates [x, y]. + * + * For a radial link, the two element array contains + * the coordinates [angle, radius]. The angle is stated in radians, with 0 at -y (12 o’clock). + * The radius measures the distance from the origin ⟨0,0⟩. + */ + target: [number, number]; +} + +/** + * A link generator for a Cartesian coordinate system. The link shape generates a smooth cubic Bézier curve from a + * source point to a target point. The tangents of the curve at the start and end are either vertical, horizontal. + * + * The first generic corresponds to the type of the "this" context within which the link generator and its accessor functions will be invoked. + * + * The second generic corresponds to the datum type of the link object for which the link is to be generated. + * + * The third generic corresponds to the datum type of the source/target node contained in the link object. + */ +export interface Link { + /** + * Generates a link for the given arguments. + * + * IMPORTANT: If the rendering context of the link generator is null, + * then the link is returned as a path data string. + * + * The "this" context within which this function is invoked, will be the context within which the accessor methods of the generator are invoked. + * All arguments passed into this function, will be passed to the accessor functions of the generator. + * + * @param d The datum for which the link is to be generated. + */ + (this: This, d: LinkDatum, ...args: any[]): string | null; + /** + * Generates an link for the given arguments. + * + * IMPORTANT: If the link generator has been configured with a rendering context, + * then the link is rendered to this context as a sequence of path method calls and this function returns void. + * + * The "this" context within which this function is invoked, will be the context within which the accessor methods of the generator are invoked. + * All arguments passed into this function, will be passed to the accessor functions of the generator. + * + * @param d The datum for which the link is to be generated. + */ + (this: This, d: LinkDatum, ...args: any[]): void; + + /** + * Returns the current source node accessor function. + * The default source accessor function returns a two element array [x, y]. + */ + source(): (this: This, d: LinkDatum, ...args: any[]) => NodeDatum; + /** + * Sets the source accessor to the specified function and returns this link generator. + * + * @param source Source node accessor function. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives the same arguments that were passed into the link generator. The default target accessor function returns a two element array [x, y]. + */ + source(source: (this: This, d: LinkDatum, ...args: any[]) => NodeDatum): this; + + /** + * Returns the current target node accessor function. + * The default target accessor function returns a two element array [x, y]. + */ + target(): (this: This, d: LinkDatum, ...args: any[]) => NodeDatum; + /** + * Sets the target accessor to the specified function and returns this link generator. + * + * @param target Target node accessor function. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives the same arguments that were passed into the link generator. The default target accessor function returns a two element array [x, y]. + */ + target(target: (this: This, d: LinkDatum, ...args: any[]) => NodeDatum): this; + + /** + * Returns the current x-accessor, which defaults to a function accepting an number array + * as its argument an returning the first element of the array. + */ + x(): (this: This, node: NodeDatum, ...args: any[]) => number; + /** + * Sets the x-accessor to the specified function and returns this link generator. + * + * @param x x-coordinate accessor function. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives as its first argument a node object followed by all additional arguments that were passed into the link generator. + */ + x(x: (this: This, node: NodeDatum, ...args: any[]) => number): this; + + /** + * Returns the current y-accessor, which defaults to a function accepting an number array + * as its argument an returning the second element of the array. + */ + y(): (this: This, node: NodeDatum, ...args: any[]) => number; + /** + * Sets the y-accessor to the specified function and returns this link generator. + * + * @param y y-coordinate accessor function. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives as its first argument a node object followed by all additional arguments that were passed into the link generator. + */ + y(y: (this: This, node: NodeDatum, ...args: any[]) => number): this; + + /** + * Returns the current rendering context, which defaults to null. + */ + context(): CanvasRenderingContext2D | null; + /** + * Sets the context and returns this link generator. + */ + context(context: CanvasRenderingContext2D | null): this; +} + +/** + * Returns a new link generator using the specified curve. For example, to visualize links in a tree diagram rooted on the top edge of the display + * + * With the default settings the link generator accepts a link object conforming to the DefaultLinkObject interface. + */ +export function link(curve: CurveFactory): Link; +/** + * Returns a new link generator using the specified curve. For example, to visualize links in a tree diagram rooted on the top edge of the display + * + * Important: Ensure that the accessor functions are configured to work with the link and node datum types + * specified in the generics. + * + * The first generic corresponds to the datum type of the link object for which the link is to be generated. + * + * The second generic corresponds to the datum type of the source/target node contained in the link object. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function link(curve: CurveFactory): Link; +/** + * Returns a new link generator using the specified curve. For example, to visualize links in a tree diagram rooted on the top edge of the display + * + * Important: Ensure that the accessor functions are configured to work with the link and node datum types + * specified in the generics. + * + * The first generic corresponds to the type of the "this" context within which the link generator and its accessor functions will be invoked. + * + * The second generic corresponds to the datum type of the link object for which the link is to be generated. + * + * The third generic corresponds to the datum type of the source/target node contained in the link object. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function link(curve: CurveFactory): Link; + +/** + * Shorthand for d3.link with d3.curveBumpX; suitable for visualizing links in a tree diagram rooted on the left edge of the display. + * + * With the default settings the link generator accepts a link object conforming to the DefaultLinkObject interface. + */ +export function linkHorizontal(): Link; +/** + * Shorthand for d3.link with d3.curveBumpX; suitable for visualizing links in a tree diagram rooted on the left edge of the display. + * + * Important: Ensure that the accessor functions are configured to work with the link and node datum types + * specified in the generics. + * + * The first generic corresponds to the datum type of the link object for which the link is to be generated. + * + * The second generic corresponds to the datum type of the source/target node contained in the link object. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function linkHorizontal(): Link; +/** + * Shorthand for d3.link with d3.curveBumpX; suitable for visualizing links in a tree diagram rooted on the left edge of the display. + * + * Important: Ensure that the accessor functions are configured to work with the link and node datum types + * specified in the generics. + * + * The first generic corresponds to the type of the "this" context within which the link generator and its accessor functions will be invoked. + * + * The second generic corresponds to the datum type of the link object for which the link is to be generated. + * + * The third generic corresponds to the datum type of the source/target node contained in the link object. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function linkHorizontal(): Link; + +/** + * Shorthand for d3.link with d3.curveBumpX; suitable for visualizing links in a tree diagram rooted on the left edge of the display. + * + * With the default settings the link generator accepts a link object conforming to the DefaultLinkObject interface. + */ +export function linkVertical(): Link; +/** + * Shorthand for d3.link with d3.curveBumpY; suitable for visualizing links in a tree diagram rooted on the top edge of the display. + * + * Important: Ensure that the accessor functions are configured to work with the link and node datum types + * specified in the generics. + * + * The first generic corresponds to the datum type of the link object for which the link is to be generated. + * + * The second generic corresponds to the datum type of the source/target node contained in the link object. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function linkVertical(): Link; +/** + * Shorthand for d3.link with d3.curveBumpY; suitable for visualizing links in a tree diagram rooted on the top edge of the display. + * + * Important: Ensure that the accessor functions are configured to work with the link and node datum types + * specified in the generics. + * + * The first generic corresponds to the type of the "this" context within which the link generator and its accessor functions will be invoked. + * + * The second generic corresponds to the datum type of the link object for which the link is to be generated. + * + * The third generic corresponds to the datum type of the source/target node contained in the link object. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function linkVertical(): Link; + +/** + * Shorthand for d3.link with d3.curveBumpY; suitable for visualizing links in a tree diagram rooted on the top edge of the display. + * + * The first generic corresponds to the type of the "this" context within which the radial link generator and its accessor functions will be invoked. + * + * The second generic corresponds to the datum type of the link object for which the link is to be generated. + * + * The third generic corresponds to the datum type of the source/target node contained in the link object. + */ +export interface LinkRadial { + /** + * Generates a radial link for the given arguments. + * + * IMPORTANT: If the rendering context of the radial link generator is null, + * then the link is returned as a path data string. + * + * The "this" context within which this function is invoked, will be the context within which the accessor methods of the generator are invoked. + * All arguments passed into this function, will be passed to the accessor functions of the generator. + * + * @param d The datum for which the link is to be generated. + */ + (this: This, d: LinkDatum, ...args: any[]): string | null; + /** + * Generates an link for the given arguments. + * + * IMPORTANT: If the radial link generator has been configured with a rendering context, + * then the link is rendered to this context as a sequence of path method calls and this function returns void. + * + * The "this" context within which this function is invoked, will be the context within which the accessor methods of the generator are invoked. + * All arguments passed into this function, will be passed to the accessor functions of the generator. + * + * @param d The datum for which the link is to be generated. + */ + (this: This, d: LinkDatum, ...args: any[]): void; + + /** + * Returns the current source node accessor function. + * The default source accessor function returns a two element array [x, y]. + */ + source(): (this: This, d: LinkDatum, ...args: any[]) => NodeDatum; + /** + * Sets the source accessor to the specified function and returns this radial link generator. + * + * @param source Source node accessor function. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives the same arguments that were passed into the radial link generator. The default target accessor function returns a two element array [x, y]. + */ + source(source: (this: This, d: LinkDatum, ...args: any[]) => NodeDatum): this; + + /** + * Returns the current target node accessor function. + * The default target accessor function returns a two element array [x, y]. + */ + target(): (this: This, d: LinkDatum, ...args: any[]) => NodeDatum; + /** + * Sets the target accessor to the specified function and returns this radial link generator. + * + * @param target Target node accessor function. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives the same arguments that were passed into the radial link generator. The default target accessor function returns a two element array [x, y]. + */ + target(target: (this: This, d: LinkDatum, ...args: any[]) => NodeDatum): this; + + /** + * Returns the current angle accessor, which defaults to a function accepting an number array + * as its argument an returning the first element of the array. + */ + angle(): (this: This, node: NodeDatum, ...args: any[]) => number; + /** + * Sets the angle accessor to the specified function and returns this radial link generator. + * The angle is stated in radians, with 0 at -y (12 o’clock). + * + * @param angle Angle accessor function. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives as its first argument a node object followed by all additional arguments that were passed into the radial link generator. + */ + angle(angle: (this: This, node: NodeDatum, ...args: any[]) => number): this; + + /** + * Returns the current radius accessor, which defaults to a function accepting an number array + * as its argument an returning the second element of the array. + */ + radius(): (this: This, node: NodeDatum, ...args: any[]) => number; + /** + * Sets the radius accessor to the specified function and returns this radial link generator. + * The radius is measured as the distance from the origin ⟨0,0⟩. + * + * @param radius Radius accessor function. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives as its first argument a node object followed by all additional arguments that were passed into the radial link generator. + */ + radius(radius: (this: This, node: NodeDatum, ...args: any[]) => number): this; + + /** + * Returns the current rendering context, which defaults to null. + */ + context(): CanvasRenderingContext2D | null; + /** + * Sets the context and returns this link generator. + */ + context(context: CanvasRenderingContext2D | null): this; +} + +/** + * @deprecated Use LinkRadial interface + */ +export type RadialLink = LinkRadial; + +/** + * Constructs a new default link generator with radial tangents, for example, to visualize links in a tree diagram + * rooted in the center of the display. + * + * With the default settings the link generator accepts a link object conforming to the DefaultLinkObject interface. + */ +export function linkRadial(): LinkRadial; +/** + * Constructs a new link generator with radial tangents, for example, to visualize links in a tree diagram + * rooted in the center of the display. + * + * Important: Ensure that the accessor functions are configured to work with the link and node datum types + * specified in the generics. + * + * The first generic corresponds to the datum type of the link object for which the link is to be generated. + * + * The second generic corresponds to the datum type of the source/target node contained in the link object. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function linkRadial(): LinkRadial; +/** + * Constructs a new link generator with radial tangents, for example, to visualize links in a tree diagram + * rooted in the center of the display. + * + * Important: Ensure that the accessor functions are configured to work with the link and node datum types + * specified in the generics. + * + * The first generic corresponds to the type of the "this" context within which the link generator and its accessor functions will be invoked. + * + * The second generic corresponds to the datum type of the link object for which the link is to be generated. + * + * The third generic corresponds to the datum type of the source/target node contained in the link object. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function linkRadial(): LinkRadial; + +// ----------------------------------------------------------------------------------- +// SYMBOLS +// ----------------------------------------------------------------------------------- + +/** + * A Symbol Type. + * + * Symbol types are typically not used directly, instead being passed to symbol.type. + * However, you can define your own symbol type implementation should none of the built-in types satisfy your needs using the following interface. + * You can also use this low-level interface with a built-in symbol type as an alternative to the symbol generator. + */ +export interface SymbolType { + /** + * Renders this symbol type to the specified context with the specified size in square pixels. The context implements the CanvasPath interface. + * (Note that this is a subset of the CanvasRenderingContext2D interface!) + * + * @param context A rendering context implementing CanvasPath. + * @param size Size of the symbol to draw. + */ + draw(context: CanvasPath_D3Shape, size: number): void; +} + +/** + * A symbol generator. + * + * Symbols provide a categorical shape encoding as is commonly used in scatterplots. Symbols are always centered at ⟨0,0⟩; + * use a transform (see: SVG, Canvas) to move the arc to a different position. + * + * The first generic corresponds to the "this" context within which the symbol generator is invoked. + * The second generic corresponds to the data type of the datum underlying the symbol. + */ +export interface Symbol { + /** + * Generates a symbol for the given arguments. + * + * IMPORTANT: If the rendering context of the symbol generator is null, + * then the symbol is returned as a path data string. + * + * The "this" context within which this function is invoked, will be the context within which the accessor methods of the generator are invoked. + * All arguments passed into this function, will be passed to the accessor functions of the generator. + * + * For example, with the default settings, no arguments are needed to produce a circle with area 64 square pixels. + * + * @param d The datum for which the symbol is to be generated. + */ + (this: This, d?: Datum, ...args: any[]): string | null; + /** + * Generates an symbol for the given arguments. + * + * IMPORTANT: If the symbol generator has been configured with a rendering context, + * then the symbol is rendered to this context as a sequence of path method calls and this function returns void. + * + * The "this" context within which this function is invoked, will be the context within which the accessor methods of the generator are invoked. + * All arguments passed into this function, will be passed to the accessor functions of the generator. + * + * For example, with the default settings, no arguments are needed to produce a circle with area 64 square pixels. + * + * @param d The datum for which the symbol is to be generated. + */ + (this: This, d?: Datum, ...args: any[]): void; + /** + * Returns the current size accessor, which defaults to a function returning a constant value of 64. + */ + size(): (this: This, d: Datum, ...args: any[]) => number; + /** + * Sets the size to the specified number and returns this symbol generator. + * + * @param size A fixed size (area in square pixels). + */ + size(size: number): this; + /** + * Sets the size to the specified function and returns this symbol generator. + * + * Specifying the size as a function is useful for constructing a scatterplot with a size encoding. + * If you wish to scale the symbol to fit a given bounding box, rather than by area, try SVG’s getBBox. + * + * @param size An accessor function returning a number to be used as a symbol size. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives the same arguments that were passed into the symbol generator. + */ + size(size: (this: This, d: Datum, ...args: any[]) => number): this; + + /** + * Returns the current symbol type accessor, which defaults to a function returning the circle symbol type. + */ + type(): (this: This, d: Datum, ...args: any[]) => SymbolType; + /** + * Sets the symbol type to the specified symbol type and returns this symbol generator. + * + * @param type A constant symbol type. + */ + type(type: SymbolType): this; + /** + * Sets the symbol type to the specified function and returns this symbol generator. + * + * @param type An accessor function returning a symbol type. The accessor function is invoked in the same "this" context as the generator was invoked in and + * receives the same arguments that were passed into the symbol generator. See symbols for the set of built-in symbol types. + * To implement a custom symbol type, return an object that implements symbolType.draw. + */ + type(type: (this: This, d: Datum, ...args: any[]) => SymbolType): this; + + /** + * Returns the current rendering context, which defaults to null. + */ + context(): CanvasRenderingContext2D | null; + /** + * Sets the context and returns this symbol generator. + */ + context(context: CanvasRenderingContext2D | null): this; +} + +/** + * Constructs a new symbol generator of the specified type and size. + * If not specified, type defaults to a circle, and size defaults to 64. + * + * The first generic corresponds to the "this" context within which the symbol generator is invoked. + * The second generic corresponds to the data type of the datum underlying the symbol. + * + * @param type The specified type. + * @param size The specified size. + */ +export function symbol( + type?: SymbolType | ((this: any, d: Datum, ...args: any[]) => SymbolType), + size?: number | ((this: any, d: Datum, ...args: any[]) => number), +): Symbol; + +/** + * Constructs a new symbol generator of the specified type and size. + * If not specified, type defaults to a circle, and size defaults to 64. + * + * The first generic corresponds to the "this" context within which the symbol generator is invoked. + * The second generic corresponds to the data type of the datum underlying the symbol. + * + * @param type The specified type. + * @param size The specified size. + */ +export function symbol( + type?: SymbolType | ((this: This, d: Datum, ...args: any[]) => SymbolType), + size?: number | ((this: This, d: Datum, ...args: any[]) => number), +): Symbol; + +/** + * An array containing a set of symbol types designed for filling: circle, cross, diamond, square, star, triangle, and wye. + * Useful for constructing the range of an ordinal scale should you wish to use a shape encoding for categorical data. + */ +export const symbolsFill: SymbolType[]; + +/** + * An array containing a set of symbol types designed for stroking: circle, plus, x, triangle2, asterisk, square2, and diamond2. + * Useful for constructing the range of an ordinal scale should you wish to use a shape encoding for categorical data. + */ +export const symbolsStroke: SymbolType[]; + +/** + * @deprecated Use symbolsFill + */ +export const symbols: SymbolType[]; + +/** + * The asterisk symbol type; intended for stroking. + */ +export const symbolAsterisk: SymbolType; + +/** + * The circle symbol type; intended for either filling or stroking. + */ +export const symbolCircle: SymbolType; + +/** + * The Greek cross symbol type, with arms of equal length; intended for filling. + */ +export const symbolCross: SymbolType; + +/** + * The rhombus symbol type; intended for filling. + */ +export const symbolDiamond: SymbolType; + +/** + * The rotated square symbol type; intended for stroking. + */ +export const symbolDiamond2: SymbolType; + +/** + * The plus symbol type; intended for stroking. + */ +export const symbolPlus: SymbolType; + +/** + * The square symbol type; intended for filling. + */ +export const symbolSquare: SymbolType; + +/** + * The square2 symbol type; intended for stroking. + */ +export const symbolSquare2: SymbolType; + +/** + * The pentagonal star (pentagram) symbol type; intended for filling. + */ +export const symbolStar: SymbolType; + +/** + * The up-pointing triangle symbol type; intended for filling. + */ +export const symbolTriangle: SymbolType; + +/** + * The up-pointing triangle symbol type; intended for stroking. + */ +export const symbolTriangle2: SymbolType; + +/** + * The Y-shape symbol type; intended for filling. + */ +export const symbolWye: SymbolType; + +/** + * The X-shape symbol type; intended for stroking. + */ +export const symbolX: SymbolType; + +/** + * The X-shape symbol type; intended for stroking. + */ +export const symbolTimes: SymbolType; + +// ----------------------------------------------------------------------------------- +// pointRadial +// ----------------------------------------------------------------------------------- + +/** + * Returns the point [x, y] for the given angle and the given radius. + * @param angle Angle in radians, with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + * @param radius Radius. + */ +export function pointRadial(angle: number, radius: number): [number, number]; + +// ----------------------------------------------------------------------------------- +// STACKS +// ----------------------------------------------------------------------------------- + +/** + * Each series point j in a stack chart corresponds to the jth element in the input data. + * Each point is represented as an array [y0, y1] where y0 is the lower value (baseline) and y1 is the upper value (topline); + * the difference between y0 and y1 corresponds to the computed value for this point. + * + * SeriesPoint is a [number, number] two-element Array with added data and index properties + * related to the data element which formed the basis for theSeriesPoint. + */ +export interface SeriesPoint extends Array { + /** + * Corresponds to y0, the lower value (baseline). + */ + 0: number; + /** + * Corresponds to y1, the upper value (topline). + */ + 1: number; + /** + * The data element underlying the series point. + */ + data: Datum; +} + +/** + * The series are determined by the keys accessor; each series i in the returned array corresponds to the ith key. + * Each series is an array of points, where each point j corresponds to the jth element in the input data. + * + * The key for each series is available as series.key, and the index as series.index. + */ +export interface Series extends Array> { + /** + * Key of the series. + */ + key: Key; + /** + * Index of the series in the series array returned by stack generator. + */ + index: number; +} + +/** + * A stack generator. + * + * Some shape types can be stacked, placing one shape adjacent to another. + * For example, a bar chart of monthly sales might be broken down into a multi-series bar chart by product category, stacking bars vertically. + * This is equivalent to subdividing a bar chart by an ordinal dimension (such as product category) and applying a color encoding. + * + * Stacked charts can show overall value and per-category value simultaneously; however, it is typically harder to compare across categories, as only the bottom layer of the stack is aligned. + * So, chose the stack order carefully, and consider a streamgraph. (See also grouped charts.) + * + * Like the pie generator, the stack generator does not produce a shape directly. Instead it computes positions which you can then pass to an area generator or use directly, say to position bars. + * + * The first generic corresponds to the "this" context in which the stack generator and its accessor functions are invoked. + * + * The second generic corresponds to the data type of an element in the data array passed into the stack generator. + * + * The third generic corresponds to the data type of key used to identify a series. + */ +export interface Stack { + /** + * Generates a stack for the given array of data, returning an array representing each series. + * The resulting array has one element per series. Each series in then typically passed to an area generator to render an area chart, + * or used to construct rectangles for a bar chart. + * + * Any additional arguments are arbitrary; they are simply propagated to the generator’s accessor functions along with the this object. + * + * @param data Array of data elements. + */ + (data: Iterable, ...args: any[]): Array>; + + /** + * Returns the current keys accessor, which defaults to the empty array. + */ + keys(): (this: This, data: Datum[], ...args: any[]) => Key[]; + /** + * Sets the keys accessor to the specified function or array and returns this stack generator. + * A series (layer) is generated for each key. + * Keys are typically strings, but they may be arbitrary values. + * The series’ key is passed to the value accessor, along with each data point, to compute the point’s value. + */ + keys(keys: Iterable | ((this: This, data: Datum[], ...args: any[]) => Key[])): this; + + /** + * Returns the current value accessor, which defaults to a function return the property corresponding to the relevant key from the data element. + * + * Thus, by default the stack generator assumes that the input data is an array of objects, with each object exposing named properties with numeric values; see stack for an example. + */ + value(): (d: Datum, key: Key, i: number, data: Datum[]) => number; + /** + * Sets the value accessor to the specified number and returns this stack generator. + * + * @param value A constant value. + */ + value(value: number): this; + /** + * Sets the value accessor to the specified function and returns this stack generator. + * + * @param value A value accessor function which returns the numeric value for a given data element and key combination. The accessor function is invoked for each data element and key being passed + * the datum, the key, index of the data element in the input data array, and the complete data array. + */ + value(value: (d: Datum, key: Key, i: number, data: Datum[]) => number): this; + + /** + * Returns the current order accessor, which defaults to stackOrderNone; this uses the order given by the key accessor. + */ + order(): (series: Series) => Iterable; + /** + * Sets the order accessor to the specified array and returns this stack generator. + */ + order(order: null | Iterable): this; + /** + * Sets the order accessor to the specified function and returns this stack generator. + * + * The stack order is computed prior to the offset; thus, the lower value for all points is zero at the time the order is computed. + * The index attribute for each series is also not set until after the order is computed. + * + * See stack orders for the built-in orders. + * + * @param order A function returning a sort order array. It is passed the generated series array and must return an array of numeric indexes representing the stack order. + */ + order(order: (series: Series) => Iterable): this; + + /** + * Returns the current offset accessor, which defaults to stackOffsetNone; this uses a zero baseline. + */ + offset(): (series: Series[], order: number[]) => void; + /** + * Reset the offset to use stackOffsetNone; this uses a zero baseline. + * + * @param offset null to set to the default stackOffsetNone. + */ + offset(offset: null): this; + /** + * Sets the offset accessor to the specified function and returns this stack generator. + * + * @param offset A function which is passed the generated series array and the order index array; + * it is then responsible for updating the lower and upper values in the series array. + */ + offset(offset: (series: Series[], order: number[]) => void): this; +} + +/** + * Constructs a new stack generator with the default settings. + * + * Ensure that the accessors used with the stack generator correspond to the arguments passed into them. + */ +export function stack(): Stack; +/** + * Constructs a new stack generator with the default settings. + * + * Ensure that the accessors used with the stack generator correspond to the arguments passed into them. + * + * The generic corresponds to the data type of an element in the data array passed into the stack generator. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function stack(): Stack; +/** + * Constructs a new stack generator with the default settings. + * + * Ensure that the accessors used with the stack generator correspond to the arguments passed into them. + * + * The first generic corresponds to the data type of an element in the data array passed into the stack generator. + * + * The second generic corresponds to the data type of key used to identify a series. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function stack(): Stack; +/** + * Constructs a new stack generator with the default settings. + * + * Ensure that the accessors used with the stack generator correspond to the arguments passed into them. + * + * The first generic corresponds to the "this" context in which the stack generator and its accessor functions are invoked. + * + * The second generic corresponds to the data type of an element in the data array passed into the stack generator. + * + * The third generic corresponds to the data type of key used to identify a series. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function stack(): Stack; + +/** + * Returns a series order such that the earliest series (according to the maximum value) is at the bottom. + * + * @param series A series generated by a stack generator. + */ +export function stackOrderAppearance(series: Series): number[]; + +/** + * Returns a series order such that the smallest series (according to the sum of values) is at the bottom. + * + * @param series A series generated by a stack generator. + */ +export function stackOrderAscending(series: Series): number[]; + +/** + * Returns a series order such that the largest series (according to the sum of values) is at the bottom. + * + * @param series A series generated by a stack generator. + */ +export function stackOrderDescending(series: Series): number[]; + +/** + * Returns a series order such that the larger series (according to the sum of values) are on the inside and the smaller series are on the outside. + * This order is recommended for streamgraphs in conjunction with the wiggle offset. See Stacked Graphs—Geometry & Aesthetics by Byron & Wattenberg for more information. + * + * @param series A series generated by a stack generator. + */ +export function stackOrderInsideOut(series: Series): number[]; + +/** + * Returns the given series order [0, 1, … n - 1] where n is the number of elements in series. Thus, the stack order is given by the key accessor. + * + * @param series A series generated by a stack generator. + */ +export function stackOrderNone(series: Series): number[]; + +/** + * Returns the reverse of the given series order [n - 1, n - 2, … 0] where n is the number of elements in series. Thus, the stack order is given by the reverse of the key accessor. + * + * @param series A series generated by a stack generator. + */ +export function stackOrderReverse(series: Series): number[]; + +/** + * Applies a zero baseline and normalizes the values for each point such that the topline is always one. + * + * @param series A series array generated by a stack generator. + * @param order An array of numeric indexes representing the stack order. + */ +export function stackOffsetExpand(series: Series[], order: Iterable): void; + +/** + * Positive values are stacked above zero, while negative values are stacked below zero. + * + * @param series A series array generated by a stack generator. + * @param order An array of numeric indexes representing the stack order. + */ +export function stackOffsetDiverging(series: Series[], order: Iterable): void; + +/** + * Applies a zero baseline. + * + * @param series A series array generated by a stack generator. + * @param order An array of numeric indexes representing the stack order. + */ +export function stackOffsetNone(series: Series[], order: Iterable): void; + +/** + * Shifts the baseline down such that the center of the streamgraph is always at zero. + * + * @param series A series array generated by a stack generator. + * @param order An array of numeric indexes representing the stack order. + */ +export function stackOffsetSilhouette(series: Series[], order: Iterable): void; + +/** + * Shifts the baseline so as to minimize the weighted wiggle of layers. This offset is recommended for streamgraphs in conjunction with the inside-out order. + * See Stacked Graphs—Geometry & Aesthetics by Bryon & Wattenberg for more information. + * + * @param series A series array generated by a stack generator. + * @param order An array of numeric indexes representing the stack order. + */ +export function stackOffsetWiggle(series: Series[], order: Iterable): void; diff --git a/tools/ui/node_modules/@types/d3-shape/package.json b/tools/ui/node_modules/@types/d3-shape/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4ab5da4a2f423a161fe303083285e6e777e85186 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-shape/package.json @@ -0,0 +1,53 @@ +{ + "name": "@types/d3-shape", + "version": "3.1.8", + "description": "TypeScript definitions for d3-shape", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-shape", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + }, + { + "name": "Fil", + "githubUsername": "Fil", + "url": "https://github.com/Fil" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-shape" + }, + "scripts": {}, + "dependencies": { + "@types/d3-path": "*" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "c63f7faa7fd70d5689095623946e70f1369c54cb6490949c7f581beabbfd61e6", + "typeScriptVersion": "5.2" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-time-format/LICENSE b/tools/ui/node_modules/@types/d3-time-format/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-time-format/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-time-format/README.md b/tools/ui/node_modules/@types/d3-time-format/README.md new file mode 100644 index 0000000000000000000000000000000000000000..57f018ed30cc0f9f0227d74a3cf8c11eb2cd7451 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-time-format/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-time-format` + +# Summary +This package contains type definitions for d3-time-format (https://github.com/d3/d3-time-format/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-time-format. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:37 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-time-format/index.d.ts b/tools/ui/node_modules/@types/d3-time-format/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bea0de18eef920124663a2305f0533f3239d0a89 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-time-format/index.d.ts @@ -0,0 +1,202 @@ +// Last module patch version validated against: 4.0.0 + +/** + * Specification of time locale to use when creating a new TimeLocaleObject + */ +export interface TimeLocaleDefinition { + /** + * The date and time (%c) format specifier (e.g., "%a %b %e %X %Y"). + */ + dateTime: string; + /** + * The date (%x) format specifier (e.g., "%m/%d/%Y"). + */ + date: string; + /** + * The time (%X) format specifier (e.g., "%H:%M:%S"). + */ + time: string; + /** + * The A.M. and P.M. equivalents (e.g., ["AM", "PM"]). + */ + periods: [string, string]; + /** + * The full names of the weekdays, starting with Sunday. + */ + days: [string, string, string, string, string, string, string]; + /** + * The abbreviated names of the weekdays, starting with Sunday. + */ + shortDays: [string, string, string, string, string, string, string]; + /** + * The full names of the months (starting with January). + */ + months: [string, string, string, string, string, string, string, string, string, string, string, string]; + /** + * the abbreviated names of the months (starting with January). + */ + shortMonths: [string, string, string, string, string, string, string, string, string, string, string, string]; +} + +/** + * Interface describing a time-locale-based object which exposes time-formatting/parsing + * methods for a specified locale definition. + */ +export interface TimeLocaleObject { + /** + * Returns a new formatter for the given string specifier. The specifier string may contain the following directives: + * - %a - abbreviated weekday name.* + * - %A - full weekday name.* + * - %b - abbreviated month name.* + * - %B - full month name.* + * - %c - the locale’s date and time, such as %x, %X.* + * - %d - zero-padded day of the month as a decimal number [01,31]. + * - %e - space-padded day of the month as a decimal number [ 1,31]; equivalent to %_d. + * - %f - microseconds as a decimal number [000000, 999999]. + * - %g - ISO 8601 week-based year without century as a decimal number [00,99]. + * - %G - ISO 8601 week-based year with century as a decimal number. + * - %H - hour (24-hour clock) as a decimal number [00,23]. + * - %I - hour (12-hour clock) as a decimal number [01,12]. + * - %j - day of the year as a decimal number [001,366]. + * - %m - month as a decimal number [01,12]. + * - %M - minute as a decimal number [00,59]. + * - %L - milliseconds as a decimal number [000, 999]. + * - %p - either AM or PM.* + * - %q - quarter of the year as a decimal number [1,4]. + * - %Q - milliseconds since UNIX epoch. + * - %s - seconds since UNIX epoch. + * - %S - second as a decimal number [00,61]. + * - %u - Monday-based (ISO) weekday as a decimal number [1,7]. + * - %U - Sunday-based week of the year as a decimal number [00,53]. + * - %V - ISO 8601 week number of the year as a decimal number [01, 53]. + * - %w - Sunday-based weekday as a decimal number [0,6]. + * - %W - Monday-based week of the year as a decimal number [00,53]. + * - %x - the locale’s date, such as %-m/%-d/%Y.* + * - %X - the locale’s time, such as %-I:%M:%S %p.* + * - %y - year without century as a decimal number [00,99]. + * - %Y - year with century as a decimal number. + * - %Z - time zone offset, such as -0700, -07:00, -07, or Z. + * - %% - a literal percent sign (%). + * + * Directives marked with an asterisk (*) may be affected by the locale definition. + * + * For %U, all days in a new year preceding the first Sunday are considered to be in week 0. + * For %W, all days in a new year preceding the first Monday are considered to be in week 0. + * Week numbers are computed using interval.count. For example, 2015-52 and 2016-00 represent Monday, December 28, 2015, while 2015-53 and 2016-01 represent Monday, January 4, 2016. + * This differs from the ISO week date specification (%V), which uses a more complicated definition! + * + * For %V,%g and %G, per the strftime man page: + * + * In this system, weeks start on a Monday, and are numbered from 01, for the first week, up to 52 or 53, for the last week. + * Week 1 is the first week where four or more days fall within the new year (or, synonymously, week 01 is: the first week of the year that contains a Thursday; + * or, the week that has 4 January in it). If the ISO week number belongs to the previous or next year, that year is used instead. + * + * The % sign indicating a directive may be immediately followed by a padding modifier: + * + * 1) 0 - zero-padding + * 2) _ - space-padding + * 3) - disable padding + * + * If no padding modifier is specified, the default is 0 for all directives except %e, which defaults to _. + * (In some implementations of strftime and strptime, a directive may include an optional field width or precision; this feature is not yet implemented.) + * + * The returned function formats a specified date, returning the corresponding string. + * + * @param specifier A specifier string for the date format. + */ + format(specifier: string): (date: Date) => string; + /** + * Returns a new parser for the given string specifier. The specifier string may contain the same directives as locale.format (TimeLocaleObject.format). + * The %d and %e directives are considered equivalent for parsing. + * + * The returned function parses a specified string, returning the corresponding date or null if the string could not be parsed according to this format’s specifier. + * Parsing is strict: if the specified string does not exactly match the associated specifier, this method returns null. + * + * For example, if the associated specifier is %Y-%m-%dT%H:%M:%SZ, then the string "2011-07-01T19:15:28Z" will be parsed as expected, + * but "2011-07-01T19:15:28", "2011-07-01 19:15:28" and "2011-07-01" will return null. (Note that the literal Z here is different from the time zone offset directive %Z.) + * If a more flexible parser is desired, try multiple formats sequentially until one returns non-null. + * + * @param specifier A specifier string for the date format. + */ + parse(specifier: string): (dateString: string) => Date | null; + /** + * Equivalent to locale.format (TimeLocaleObject.format), except all directives are interpreted as Coordinated Universal Time (UTC) rather than local time. + * + * @param specifier A specifier string for the date format. + */ + utcFormat(specifier: string): (date: Date) => string; + /** + * Equivalent to locale.parse (TimeLocaleObject.parse), except all directives are interpreted as Coordinated Universal Time (UTC) rather than local time. + * + * @param specifier A specifier string for the date format. + */ + utcParse(specifier: string): (dateString: string) => Date | null; +} + +/** + * Create a new time-locale-based object which exposes time-formatting + * methods for the specified locale definition. + * + * @param definition A time locale definition. + */ +export function timeFormatLocale(definition: TimeLocaleDefinition): TimeLocaleObject; + +/** + * Create a new time-locale-based object which exposes time-formatting + * methods for the specified locale definition. The new time locale definition + * will be set as the new default time locale. + * + * @param definition A time locale definition. + */ +export function timeFormatDefaultLocale(definition: TimeLocaleDefinition): TimeLocaleObject; + +/** + * Returns a new formatter for the given string specifier. The returned function formats a specified date, returning the corresponding string. + * + * An alias for locale.format (TimeLocaleObject.format) on the default locale. + * + * @param specifier A specifier string for the date format. + */ +export function timeFormat(specifier: string): (date: Date) => string; + +/** + * Returns a new parser for the given string specifier. + * + * An alias for locale.parse (TimeLocaleObject.parse) on the default locale. + * + * @param specifier A specifier string for the date format. + */ +export function timeParse(specifier: string): (dateString: string) => Date | null; + +/** + * Equivalent to timeFormat, except all directives are interpreted as Coordinated Universal Time (UTC) rather than local time. + * + * An alias for locale.utcFormat (TimeLocaleObject.utcFormat) on the default locale. + * + * @param specifier A specifier string for the date format. + */ +export function utcFormat(specifier: string): (date: Date) => string; + +/** + * Equivalent to timeParse, except all directives are interpreted as Coordinated Universal Time (UTC) rather than local time. + * + * An alias for locale.utcParse (TimeLocaleObject.utcParse) on the default locale. + * + * @param specifier A specifier string for the date format. + */ +export function utcParse(specifier: string): (dateString: string) => Date | null; + +/** + * The full ISO 8601 UTC time formatter. Where available, this method will use Date.toISOString to format. + * + * @param date A date to format. + */ +export function isoFormat(date: Date): string; + +/** + * The full ISO 8601 UTC time parser. Where available, this method will use the Date constructor to parse strings. + * If you depend on strict validation of the input format according to ISO 8601, you should construct a UTC parser function using utcParse. + * + * @param dateString A string encoded date to parse. + */ +export function isoParse(dateString: string): Date | null; diff --git a/tools/ui/node_modules/@types/d3-time-format/package.json b/tools/ui/node_modules/@types/d3-time-format/package.json new file mode 100644 index 0000000000000000000000000000000000000000..40781d2881ca8fa803b47ecf74d7c5e98b93693c --- /dev/null +++ b/tools/ui/node_modules/@types/d3-time-format/package.json @@ -0,0 +1,40 @@ +{ + "name": "@types/d3-time-format", + "version": "4.0.3", + "description": "TypeScript definitions for d3-time-format", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-time-format", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-time-format" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "13657d5e1edb1a96227fd858aab67f2d7687422010ecd995e26c61e70ea56a40", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-time/LICENSE b/tools/ui/node_modules/@types/d3-time/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-time/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-time/README.md b/tools/ui/node_modules/@types/d3-time/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4e79c08df8c91f86b4969c4b59f9c0f62a8db0bf --- /dev/null +++ b/tools/ui/node_modules/@types/d3-time/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-time` + +# Summary +This package contains type definitions for d3-time (https://github.com/d3/d3-time/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-time. + +### Additional Details + * Last updated: Mon, 25 Nov 2024 10:02:27 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [denisname](https://github.com/denisname), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-time/index.d.ts b/tools/ui/node_modules/@types/d3-time/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8b24264c58f2893d1c8dee098d5be9743223c13e --- /dev/null +++ b/tools/ui/node_modules/@types/d3-time/index.d.ts @@ -0,0 +1,697 @@ +// Last module patch version validated against: 3.0.0 + +// --------------------------------------------------------------- +// Interfaces +// --------------------------------------------------------------- + +/** + * A D3 Time Interval + */ +export interface TimeInterval { + /** + * Returns a new date representing the latest interval boundary date before or equal to date. + * Equivalent to interval.floor, except it date is not specified, it defaults to the current time. + * For example, d3.timeYear(date) and d3.timeYear.floor(date) are equivalent. + * + * For example, timeDay(date) typically returns 12:00 AM local time on the given date. + * + * This function is idempotent: if the specified date is already floored to the current interval, + * a new date with an identical time is returned. + * Furthermore, the returned date is the minimum expressible value of the associated interval, + * such that interval.floor(interval.floor(date) - 1) returns the preceding interval boundary date. + * + * Note that the == and === operators do not compare by value with Date objects, + * and thus you cannot use them to tell whether the specified date has already been floored. + * Instead, coerce to a number and then compare. + * + * This is more reliable than testing whether the time is 12:00 AM, as in some time zones midnight may not exist due to daylight saving. + * + * @param date A date object. + */ + (date?: Date): Date; + + /** + * Returns a new date representing the latest interval boundary date before or equal to date. + * + * For example, timeDay.floor(date) typically returns 12:00 AM local time on the given date. + * + * This method is idempotent: if the specified date is already floored to the current interval, + * a new date with an identical time is returned. + * Furthermore, the returned date is the minimum expressible value of the associated interval, + * such that interval.floor(interval.floor(date) - 1) returns the preceding interval boundary date. + * + * Note that the == and === operators do not compare by value with Date objects, + * and thus you cannot use them to tell whether the specified date has already been floored. + * Instead, coerce to a number and then compare. + * + * This is more reliable than testing whether the time is 12:00 AM, as in some time zones midnight may not exist due to daylight saving. + * + * @param date A date object. + */ + floor(date: Date): Date; + + /** + * Returns a new date representing the closest interval boundary date to date. + * + * For example, timeDay.round(date) typically returns 12:00 AM local time on the given date if it is on or before noon, + * and 12:00 AM of the following day if it is after noon. + * + * This method is idempotent: if the specified date is already rounded to the current interval, a new date with an identical time is returned. + * + * @param date A date object. + */ + round(date: Date): Date; + + /** + * Returns a new date representing the earliest interval boundary date after or equal to date. + * + * For example, timeDay.ceil(date) typically returns 12:00 AM local time on the date following the given date. + * + * This method is idempotent: if the specified date is already ceilinged to the current interval, + * a new date with an identical time is returned. Furthermore, + * the returned date is the maximum expressible value of the associated interval, + * such that interval.ceil(interval.ceil(date) + 1) returns the following interval boundary date. + * + * @param date A date object. + */ + ceil(date: Date): Date; + + /** + * Returns a new date equal to date plus step intervals. + * + * If step is not specified it defaults to 1. + * + * This method does not round the specified date to the interval. For example, if date is today at 5:34 PM, + * then timeDay.offset(date, 1) returns 5:34 PM tomorrow (even if daylight saving changes!). + * + * @param date A date object. + * @param step An optional number of steps to apply when calculating the offset date. + * If step is negative, then the returned date will be before the specified date; + * if step is zero, then a copy of the specified date is returned; if step is not an integer, it is floored. + */ + offset(date: Date, step?: number): Date; + + /** + * Returns an array of dates representing every interval boundary after or equal to start (inclusive) and before stop (exclusive). + * + * If step is specified, then every step-th boundary will be returned; for example, + * for the timeDay interval a step of 2 will return every other day. + * If step is not an integer, it is floored. + * + * The first date in the returned array is the earliest boundary after or equal to start; + * subsequent dates are offset by step intervals and floored. + * Thus, two overlapping ranges may be inconsistent. + * + * To make ranges consistent when a step is specified, use CountableInterval.every instead. + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ + range(start: Date, stop: Date, step?: number): Date[]; + + /** + * Returns a new interval that is a filtered subset of this interval using the specified test function. + * + * @param test A test function which is passed a date and should return true if and only if + * the specified date should be considered part of the interval. + */ + filter(test: (date: Date) => boolean): TimeInterval; +} + +/** + * A D3 Countable Time Interval + */ +export interface CountableTimeInterval extends TimeInterval { + /** + * Returns the number of interval boundaries after start (exclusive) and before or equal to end (inclusive). + * + * Note that this behavior is slightly different than interval.range, + * because its purpose is to return the zero-based number of the specified end date relative to the specified start date. + * + * @param start A start date object. + * @param end An end date object. + */ + count(start: Date, end: Date): number; + /** + * Returns a filtered view of this interval representing every stepth date. + * + * The meaning of step is dependent on this interval’s parent interval as defined by the field function. + * + * For example, timeMinute.every(15) returns an interval representing every fifteen minutes, + * starting on the hour: :00, :15, :30, :45, etc. Note that for some intervals, + * the resulting dates may not be uniformly-spaced; + * timeDay’s parent interval is timeMonth, and thus the interval number resets at the start of each month. + * + * If step is not valid, returns null. If step is one, returns this interval. + * + * This method can be used in conjunction with interval.range to ensure that two overlapping ranges are consistent. + * + * The returned filtered interval does not support interval.count. See also interval.filter. + * + * @param step Number of steps. + */ + every(step: number): TimeInterval | null; +} + +// --------------------------------------------------------------- +// Custom (Countable)Interval Factories +// --------------------------------------------------------------- + +/** + * Constructs a new custom interval given the specified floor and offset functions. + * + * The returned custom interval is not countable, i.e. does not expose the methods "count(..)" and "every(...)". + * + * @param floor A floor function which takes a single date as an argument and rounds it down to the nearest interval boundary. + * @param offset An offset function which takes a date and an integer step as arguments and advances + * the specified date by the specified number of boundaries; the step may be positive, negative or zero. + */ +export function timeInterval( + floor: (date: Date) => void, + offset: (date: Date, step: number) => void, +): TimeInterval; +/** + * Constructs a new custom interval given the specified floor, offset and count functions. + * + * The returned custom interval is countable and exposes the methods "count(..)" and "every(...)". + * + * Note: due to an internal optimization, the specified count function must not invoke interval.count on other time intervals. + * + * @param floor A floor function which takes a single date as an argument and rounds it down to the nearest interval boundary. + * @param offset An offset function which takes a date and an integer step as arguments and advances + * the specified date by the specified number of boundaries; the step may be positive, negative or zero. + * @param count A count function which takes a start date and an end date, already floored to the current interval, + * and returns the number of boundaries between the start (exclusive) and end (inclusive). + * Note: due to an internal optimization, the specified count function must not invoke interval.count on other time intervals. + * @param field An optional field function which takes a date, already floored to the current interval, + * and returns the field value of the specified date, + * corresponding to the number of boundaries between this date (exclusive) and the latest previous parent boundary. + * For example, for the timeDay interval, this returns the number of days since the start of the month. + * If a field function is not specified, it defaults to counting the number of interval boundaries since + * the UNIX epoch of January 1, 1970 UTC. The field function defines the behavior of interval.every. + */ +export function timeInterval( + floor: (date: Date) => void, + offset: (date: Date, step: number) => void, + count: (start: Date, end: Date) => number, + field?: (date: Date) => number, +): CountableTimeInterval; + +// --------------------------------------------------------------- +// Built-In Factories and Date Array Creators +// --------------------------------------------------------------- + +// local time ---------------------------------------------------------- + +/** + * Milliseconds Interval in Local Time; the shortest available time unit. + */ +export const timeMillisecond: CountableTimeInterval; + +/** + * This is a convenience alias for timeMillisecond.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function timeMilliseconds(start: Date, stop: Date, step?: number): Date[]; + +/** + * Seconds Interval in Local Time; seconds (e.g., 01:23:45.0000 AM); 1,000 milliseconds. + */ +export const timeSecond: CountableTimeInterval; + +/** + * This is a convenience alias for timeSecond.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function timeSeconds(start: Date, stop: Date, step?: number): Date[]; + +/** + * Minutes Interval in Local Time; minutes (e.g., 01:02:00 AM); 60 seconds. Note that ECMAScript ignores leap seconds. + */ +export const timeMinute: CountableTimeInterval; + +/** + * This is a convenience alias for timeMinute.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function timeMinutes(start: Date, stop: Date, step?: number): Date[]; + +/** + * Hours Interval in Local Time; Hours (e.g., 01:00 AM); 60 minutes. + * + * Note that advancing time by one hour in local time can return the same hour or skip an hour due to daylight saving. + */ +export const timeHour: CountableTimeInterval; + +/** + * This is a convenience alias for timeHour.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function timeHours(start: Date, stop: Date, step?: number): Date[]; + +/** + * Days Interval in Local Time; days (e.g., February 7, 2012 at 12:00 AM); typically 24 hours. + * Days in local time may range from 23 to 25 hours due to daylight saving. + */ +export const timeDay: CountableTimeInterval; + +/** + * This is a convenience alias for timeDay.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function timeDays(start: Date, stop: Date, step?: number): Date[]; + +/** + * Week Interval in Local Time. Alias for sunday; 7 days and typically 168 hours. + * + * Weeks in local time may range from 167 to 169 hours due on daylight saving. + */ +export const timeWeek: CountableTimeInterval; + +/** + * This is a convenience alias for timeWeek.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function timeWeeks(start: Date, stop: Date, step?: number): Date[]; + +/** + * Week Interval for Sunday-based weeks in Local Time (e.g., February 5, 2012 at 12:00 AM). + * 7 days and typically 168 hours. + * + * Weeks in local time may range from 167 to 169 hours due on daylight saving. + */ +export const timeSunday: CountableTimeInterval; + +/** + * This is a convenience alias for timeSunday.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function timeSundays(start: Date, stop: Date, step?: number): Date[]; + +/** + * Week Interval for Monday-based weeks in Local Time (e.g., February 6, 2012 at 12:00 AM). + * 7 days and typically 168 hours. + * + * Weeks in local time may range from 167 to 169 hours due on daylight saving. + */ +export const timeMonday: CountableTimeInterval; + +/** + * This is a convenience alias for timeMonday.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function timeMondays(start: Date, stop: Date, step?: number): Date[]; + +/** + * Week Interval for Tuesday-based weeks in Local Time (e.g., February 7, 2012 at 12:00 AM). + * 7 days and typically 168 hours. + * + * Weeks in local time may range from 167 to 169 hours due on daylight saving. + */ +export const timeTuesday: CountableTimeInterval; + +/** + * This is a convenience alias for timeTuesday.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function timeTuesdays(start: Date, stop: Date, step?: number): Date[]; + +/** + * Week Interval for Wednesday-based weeks in Local Time (e.g., February 8, 2012 at 12:00 AM). + * 7 days and typically 168 hours. + * + * Weeks in local time may range from 167 to 169 hours due on daylight saving. + */ +export const timeWednesday: CountableTimeInterval; + +/** + * This is a convenience alias for timeWednesday.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function timeWednesdays(start: Date, stop: Date, step?: number): Date[]; + +/** + * Week Interval for Thursday-based weeks in Local Time (e.g., February 9, 2012 at 12:00 AM). + * 7 days and typically 168 hours. + * + * Weeks in local time may range from 167 to 169 hours due on daylight saving. + */ +export const timeThursday: CountableTimeInterval; + +/** + * This is a convenience alias for timeThursday.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function timeThursdays(start: Date, stop: Date, step?: number): Date[]; + +/** + * Week Interval for Friday-based weeks in Local Time (e.g., February 10, 2012 at 12:00 AM). + * 7 days and typically 168 hours. + * + * Weeks in local time may range from 167 to 169 hours due on daylight saving. + */ +export const timeFriday: CountableTimeInterval; + +/** + * This is a convenience alias for timeFriday.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function timeFridays(start: Date, stop: Date, step?: number): Date[]; + +/** + * Week Interval for Saturday-based weeks in Local Time (e.g., February 11, 2012 at 12:00 AM). + * 7 days and typically 168 hours. + * + * Weeks in local time may range from 167 to 169 hours due on daylight saving. + */ +export const timeSaturday: CountableTimeInterval; + +/** + * This is a convenience alias for timeSaturday.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function timeSaturdays(start: Date, stop: Date, step?: number): Date[]; + +/** + * Month Interval in Local Time; months (e.g., February 1, 2012 at 12:00 AM); ranges from 28 to 31 days. + */ +export const timeMonth: CountableTimeInterval; + +/** + * This is a convenience alias for timeMonth.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function timeMonths(start: Date, stop: Date, step?: number): Date[]; + +/** + * Year Interval in Local Time; years (e.g., January 1, 2012 at 12:00 AM); ranges from 365 to 366 days. + */ +export const timeYear: CountableTimeInterval; + +/** + * This is a convenience alias for timeYear.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function timeYears(start: Date, stop: Date, step?: number): Date[]; + +// utc Coordinated Universal Time ---------------------------------------------------------- + +/** + * Milliseconds Interval in Coordinated Universal Time (UTC); the shortest available time unit. + */ +export const utcMillisecond: CountableTimeInterval; + +/** + * This is a convenience alias for utcMillisecond.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function utcMilliseconds(start: Date, stop: Date, step?: number): Date[]; + +/** + * Seconds Interval in Coordinated Universal Time (UTC); seconds (e.g., 01:23:45.0000 AM); 1,000 milliseconds. + */ +export const utcSecond: CountableTimeInterval; + +/** + * This is a convenience alias for utcSecond.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function utcSeconds(start: Date, stop: Date, step?: number): Date[]; + +/** + * Minutes Interval in Coordinated Universal Time (UTC); minutes (e.g., 01:02:00 AM); 60 seconds. + * Note that ECMAScript ignores leap seconds. + */ +export const utcMinute: CountableTimeInterval; + +/** + * This is a convenience alias for utcMinute.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function utcMinutes(start: Date, stop: Date, step?: number): Date[]; + +/** + * Hours Interval in Coordinated Universal Time (UTC); Hours (e.g., 01:00 AM); 60 minutes. + */ +export const utcHour: CountableTimeInterval; + +/** + * This is a convenience alias for utcHour.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function utcHours(start: Date, stop: Date, step?: number): Date[]; + +/** + * Days Interval in Coordinated Universal Time (UTC); days (e.g., February 7, 2012 at 12:00 AM); 24 hours. + */ +export const utcDay: CountableTimeInterval; + +/** + * This is a convenience alias for utcDay.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function utcDays(start: Date, stop: Date, step?: number): Date[]; + +/** + * Week Interval in Local Time. Alias for sunday; 7 days and 168 hours. + */ +export const utcWeek: CountableTimeInterval; + +/** + * This is a convenience alias for utcWeek.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function utcWeeks(start: Date, stop: Date, step?: number): Date[]; + +/** + * Week Interval for Sunday-based weeks in Coordinated Universal Time (UTC) (e.g., February 5, 2012 at 12:00 AM). + * 7 days and 168 hours. + */ +export const utcSunday: CountableTimeInterval; + +/** + * This is a convenience alias for utcSunday.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function utcSundays(start: Date, stop: Date, step?: number): Date[]; + +/** + * Week Interval for Monday-based weeks in Coordinated Universal Time (UTC) (e.g., February 6, 2012 at 12:00 AM). + * 7 days and 168 hours. + */ +export const utcMonday: CountableTimeInterval; + +/** + * This is a convenience alias for utcMonday.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function utcMondays(start: Date, stop: Date, step?: number): Date[]; + +/** + * Week Interval for Tuesday-based weeks in Coordinated Universal Time (UTC) (e.g., February 7, 2012 at 12:00 AM). + * 7 days and 168 hours. + */ +export const utcTuesday: CountableTimeInterval; + +/** + * This is a convenience alias for utcTuesday.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function utcTuesdays(start: Date, stop: Date, step?: number): Date[]; + +/** + * Week Interval for Wednesday-based weeks in Coordinated Universal Time (UTC) (e.g., February 8, 2012 at 12:00 AM). + * 7 days and 168 hours. + */ +export const utcWednesday: CountableTimeInterval; + +/** + * This is a convenience alias for utcWednesday.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function utcWednesdays(start: Date, stop: Date, step?: number): Date[]; + +/** + * Week Interval for Thursday-based weeks in Coordinated Universal Time (UTC) (e.g., February 9, 2012 at 12:00 AM). + * 7 days and 168 hours. + */ +export const utcThursday: CountableTimeInterval; + +/** + * This is a convenience alias for utcThursday.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function utcThursdays(start: Date, stop: Date, step?: number): Date[]; + +/** + * Week Interval for Friday-based weeks in Coordinated Universal Time (UTC) (e.g., February 10, 2012 at 12:00 AM). + * 7 days and 168 hours. + */ +export const utcFriday: CountableTimeInterval; + +/** + * This is a convenience alias for utcFriday.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function utcFridays(start: Date, stop: Date, step?: number): Date[]; + +/** + * Week Interval for Saturday-based weeks in Coordinated Universal Time (UTC) (e.g., February 11, 2012 at 12:00 AM). + * 7 days and 168 hours. + */ +export const utcSaturday: CountableTimeInterval; + +/** + * This is a convenience alias for utcSaturday.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function utcSaturdays(start: Date, stop: Date, step?: number): Date[]; + +/** + * Month Interval in Coordinated Universal Time (UTC); months (e.g., February 1, 2012 at 12:00 AM); ranges from 28 to 31 days. + */ +export const utcMonth: CountableTimeInterval; + +/** + * This is a convenience alias for utcMonth.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function utcMonths(start: Date, stop: Date, step?: number): Date[]; + +/** + * Year Interval in Coordinated Universal Time (UTC); years (e.g., January 1, 2012 at 12:00 AM); ranges from 365 to 366 days. + */ +export const utcYear: CountableTimeInterval; + +/** + * This is a convenience alias for utcYear.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function utcYears(start: Date, stop: Date, step?: number): Date[]; + +/** + * Like d3.utcDay, except it counts days since the UNIX epoch (January 1, 1970) such that interval.every returns uniformly-spaced dates rather than varying based on day-of-month. + */ +export const unixDay: CountableTimeInterval; + +/** + * This is a convenience alias for unixDay.range(...). + * + * @param start A start date object for the range. + * @param stop A stop date object for the range. + * @param step An optional number of steps to apply when calculating the dates in the range. + */ +export function unixDays(start: Date, stop: Date, step?: number): Date[]; + +/** + * Equivalent to d3.utcTicks, but in local time. + */ +export function timeTicks(start: Date, stop: Date, count: number): Date[]; + +/** + * Returns the time interval that would be used by d3.timeTicks given the same arguments. + */ +export function timeTickInterval(start: Date, stop: Date, count: number): TimeInterval | null; + +/** + * Returns an array of approximately count dates at regular intervals between start and stop (inclusive). + * If stop is before start, dates are returned in reverse chronological order; otherwise dates are returned in chronological order. + */ +export function utcTicks(start: Date, stop: Date, count: number): Date[]; + +/** + * Returns the time interval that would be used by d3.utcTicks given the same arguments. + * If there is no associated interval, such as when start or stop is invalid, returns null. + */ +export function utcTickInterval(start: Date, stop: Date, count: number): TimeInterval | null; diff --git a/tools/ui/node_modules/@types/d3-time/package.json b/tools/ui/node_modules/@types/d3-time/package.json new file mode 100644 index 0000000000000000000000000000000000000000..363809d1e4b986851f5e0cc272924fd51a0b4864 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-time/package.json @@ -0,0 +1,46 @@ +{ + "name": "@types/d3-time", + "version": "3.0.4", + "description": "TypeScript definitions for d3-time", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-time", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-time" + }, + "scripts": {}, + "dependencies": {}, + "peerDependencies": {}, + "typesPublisherContentHash": "995c6a7a1f21328f5dceb32804c5f3d92ab20a98694246d9c8f213f4eef298ed", + "typeScriptVersion": "4.9" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-timer/LICENSE b/tools/ui/node_modules/@types/d3-timer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-timer/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-timer/README.md b/tools/ui/node_modules/@types/d3-timer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e82a16f2207035356e615999e03403a22998cc2a --- /dev/null +++ b/tools/ui/node_modules/@types/d3-timer/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-timer` + +# Summary +This package contains type definitions for d3-timer (https://github.com/d3/d3-timer/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-timer. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:37 GMT + * Dependencies: none + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [denisname](https://github.com/denisname), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-timer/index.d.ts b/tools/ui/node_modules/@types/d3-timer/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..66d882490afe81fe85163be6e8e7dd8eb81358b5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-timer/index.d.ts @@ -0,0 +1,68 @@ +// Last module patch version validated against: 3.0.1 + +/** + * Returns the current time as defined by performance.now if available, and Date.now if not. + * The current time is updated at the start of a frame; it is thus consistent during the frame, and any timers scheduled during the same frame will be synchronized. + * If this method is called outside of a frame, such as in response to a user event, the current time is calculated and then fixed until the next frame, + * again ensuring consistent timing during event handling. + */ +export function now(): number; + +export interface Timer { + /** + * Restart a timer with the specified callback and optional delay and time. + * This is equivalent to stopping this timer and creating a new timer with the specified arguments, + * although this timer retains the original invocation priority. + * + * @param callback A callback function to be invoked and passed in the apparent + * elapsed time since the timer became active in milliseconds. + * @param delay An optional numeric delay in milliseconds (default = 0) relative to time. + * @param time An optional time in milliseconds relative to which the delay is calculated (default = now). + */ + restart(callbackFn: (elapsed: number) => void, delay?: number, time?: number): void; + + /** + * Stop the timer. + */ + stop(): void; +} + +/** + * Schedules and returns a new timer, invoking the specified callback repeatedly until the timer is stopped. + * The callback is passed the (apparent) elapsed time since the timer became active. + * + * @param callback A callback function to be invoked and passed in the apparent + * elapsed time since the timer became active in milliseconds. + * @param delay An optional numeric delay in milliseconds (default = 0) relative to time. + * @param time An optional time in milliseconds relative to which the delay is calculated (default = now). + */ +export function timer(callback: (elapsed: number) => void, delay?: number, time?: number): Timer; + +/** + * Immediately invoke any eligible timer callbacks. + */ +export function timerFlush(): void; + +/** + * Schedules and returns a new timer, invoking the specified callback. The timer is stopped automatically + * on its first callback. The callback is passed the (apparent) elapsed time since the timer became active. + * + * @param callback A callback function to be invoked and passed in the apparent + * elapsed time since the timer became active in milliseconds. + * @param delay An optional numeric delay in milliseconds (default = 0) relative to time. + * @param time An optional time in milliseconds relative to which the delay is calculated (default = now). + */ +export function timeout(callback: (elapsed: number) => void, delay?: number, time?: number): Timer; + +/** + * Schedules and returns a new timer, invoking the specified callback repeatedly every 'delay' milliseconds + * until the timer is stopped. + * The callback is passed the (apparent) elapsed time since the timer became active. + * + * @param callback A callback function to be invoked and passed in the apparent + * elapsed time since the timer became active in milliseconds. + * @param delay An optional numeric delay in milliseconds between repeat invocations of the callback. + * If not specified, the interval timer behaves like the regular timer. + * @param time An optional time in milliseconds relative to which the initial delay is calculated (default = now). + */ +export function interval(callback: (elapsed: number) => void, delay?: number, time?: number): Timer; diff --git a/tools/ui/node_modules/@types/d3-timer/package.json b/tools/ui/node_modules/@types/d3-timer/package.json new file mode 100644 index 0000000000000000000000000000000000000000..25669dac3c93379c7dc2b2c895471defed02b598 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-timer/package.json @@ -0,0 +1,45 @@ +{ + "name": "@types/d3-timer", + "version": "3.0.2", + "description": "TypeScript definitions for d3-timer", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-timer", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-timer" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "a51fc6981e6d12715fd052f7e598dd291c354465025cbb33ece1895bdab4109c", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-transition/LICENSE b/tools/ui/node_modules/@types/d3-transition/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-transition/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-transition/README.md b/tools/ui/node_modules/@types/d3-transition/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f5e0439113487609aa291b91f594d686a39b53eb --- /dev/null +++ b/tools/ui/node_modules/@types/d3-transition/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-transition` + +# Summary +This package contains type definitions for d3-transition (https://github.com/d3/d3-transition/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-transition. + +### Additional Details + * Last updated: Mon, 07 Oct 2024 22:38:10 GMT + * Dependencies: [@types/d3-selection](https://npmjs.com/package/@types/d3-selection) + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [Robert Moura](https://github.com/robertmoura), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-transition/index.d.ts b/tools/ui/node_modules/@types/d3-transition/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..046b08096ef3ca31d897432c7109063b16fb9def --- /dev/null +++ b/tools/ui/node_modules/@types/d3-transition/index.d.ts @@ -0,0 +1,664 @@ +// Last module patch version validated against: 3.0.1 + +import { ArrayLike, BaseType, Selection, ValueFn } from "d3-selection"; + +/** + * Extend interface 'Selection' by declaration merging with 'd3-selection' + */ +declare module "d3-selection" { + /** + * A D3 Selection of elements. + * + * The first generic "GElement" refers to the type of the selected element(s). + * The second generic "Datum" refers to the type of the datum of a selected element(s). + * The third generic "PElement" refers to the type of the parent element(s) in the D3 selection. + * The fourth generic "PDatum" refers to the type of the datum of the parent element(s). + */ + interface Selection { + /** + * Interrupts the active transition of the specified name on the selected elements, and cancels any pending transitions with the specified name, if any. + * If a name is not specified, null is used. + * + * IMPORTANT: Interrupting a transition on an element has no effect on any transitions on any descendant elements. + * For example, an axis transition consists of multiple independent, synchronized transitions on the descendants of the axis G element + * (the tick lines, the tick labels, the domain path, etc.). To interrupt the axis transition, you must therefore interrupt the descendants. + * + * @param name Name of the transition. + */ + interrupt(name?: string): this; + /** + * Returns a new transition on the given selection with the specified name. If a name is not specified, null is used. + * The new transition is only exclusive with other transitions of the same name. + * + * @param name Name of the transition. + */ + transition(name?: string): Transition; + /** + * Returns a new transition on the given selection. + * + * When using a transition instance, the returned transition has the same id and name as the specified transition. + * If a transition with the same id already exists on a selected element, the existing transition is returned for that element. + * Otherwise, the timing of the returned transition is inherited from the existing transition of the same id on the nearest ancestor of each selected element. + * Thus, this method can be used to synchronize a transition across multiple selections, + * or to re-select a transition for specific elements and modify its configuration. + * + * If the specified transition is not found on a selected node or its ancestors (such as if the transition already ended), + * the default timing parameters are used; however, in a future release, this will likely be changed to throw an error. + * + * @param transition A transition instance. + */ + transition(transition: Transition): Transition; + } +} + +/** + * Return the active transition on the specified node with the specified name, if any. + * If no name is specified, null is used. Returns null if there is no such active transition on the specified node. + * This method is useful for creating chained transitions. + * + * The first generic "GElement" refers to the type of element on which the returned active transition was defined. The second generic "Datum" refers to the type of the + * datum, of a selected element on which the transition is defined. The third generic refers to the type of the parent elements in the returned Transition. + * The fourth generic refers to the type of the datum defined on the parent elements in the returned Transition. + * + * @param node Element for which the active transition should be returned. + * @param name Name of the transition. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function active( + node: GElement, + name?: string, +): Transition | null; + +/** + * Interrupts the active transition of the specified name on the specified node, and cancels any pending transitions with the specified name, if any. + * If a name is not specified, null is used. + * + * @param node Element for which the transition should be interrupted. + * @param name Name of the transition to be interrupted. If a name is not specified, null is used. + */ +export function interrupt(node: BaseType, name?: string): void; + +/** + * A D3 Transition. + * + * The first generic "GElement" refers to the type of the selected element(s) in the Transition. + * The second generic "Datum" refers to the type of the datum of a selected element(s) in the Transition. + * The third generic "PElement" refers to the type of the parent element(s) in the D3 selection in the Transition. + * The fourth generic "PDatum" refers to the type of the datum of the parent element(s) in the Transition. + */ +export interface Transition { + // Sub-selection ------------------------- + + /** + * For each selected element, select the first descendant element that matches the specified selector string, if any, + * and returns a transition on the resulting selection. The new transition has the same id, name and timing as this transition; + * however, if a transition with the same id already exists on a selected element, + * the existing transition is returned for that element. + * + * The generic represents the type of the descendant element to be selected. + * + * @param selector CSS selector string + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + select(selector: string): Transition; + /** + * For each selected element, select the descendant element returned by the selector function, if any, + * and returns a transition on the resulting selection. The new transition has the same id, name and timing as this transition; + * however, if a transition with the same id already exists on a selected element, + * the existing transition is returned for that element. + * + * The generic represents the type of the descendant element to be selected. + * + * @param selector A selector function, which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). + * It must return an element, or null if there is no matching element. + */ + select( + selector: ValueFn, + ): Transition; + + /** + * For each selected element, select all descendant elements that match the specified selector string, if any, + * and returns a transition on the resulting selection. The new transition has the same id, name and timing as this transition; + * however, if a transition with the same id already exists on a selected element, the existing transition is returned for that element. + * + * The first generic "DescElement" refers to the type of descendant element to be selected. The second generic "OldDatum" refers to the type of the + * datum, of a selected element. This is useful when re-selecting elements with a previously set, know datum type. + * + * @param selector CSS selector string + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + selectAll( + selector: string, + ): Transition; + /** + * For each selected element, select all descendant elements returned by the selector function, if any, + * and returns a transition on the resulting selection. The new transition has the same id, name and timing as this transition; + * however, if a transition with the same id already exists on a selected element, the existing transition is returned for that element. + * + * The first generic "DescElement" refers to the type of descendant element to be selected. The second generic "OldDatum" refers to the type of the + * datum, of a selected element. This is useful when re-selecting elements with a previously set, know datum type. + * + * @param selector A selector function which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). It must return an array of elements + * (or a pseudo-array, such as a NodeList), or the empty array if there are no matching elements. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + selectAll( + selector: ValueFn>, + ): Transition; + + /** + * For each selected element, selects the first child element that matches the specified selector string, if any, and returns a transition on the resulting selection. + * The selector may be specified either as a selector string or a function. + * If a function, it is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element. + * The new transition has the same id, name and timing as this transition; + * however, if a transition with the same id already exists on a selected element, the existing transition is returned for that element. + * This method is equivalent to deriving the selection for this transition via transition.selection, + * creating a subselection via selection.selectChild, and then creating a new transition via selection.transition. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + selectChild( + selector?: string | ValueFn, + ): Transition; + + /** + * For each selected element, selects all children that match the specified selector string, if any, and returns a transition on the resulting selection. + * The selector may be specified either as a selector string or a function. + * If a function, it is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element. + * The new transition has the same id, name and timing as this transition; + * however, if a transition with the same id already exists on a selected element, the existing transition is returned for that element. + * This method is equivalent to deriving the selection for this transition via transition.selection, + * creating a subselection via selection.selectChildren, and then creating a new transition via selection.transition. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + selectChildren( + selector?: string | ValueFn, + ): Transition; + + /** + * Return the selection corresponding to this transition. + */ + selection(): Selection; + + /** + * Returns a new transition on the same selected elements as this transition, scheduled to start when this transition ends. + * The new transition inherits a reference time equal to this transition’s time plus its delay and duration. + * The new transition also inherits this transition’s name, duration, and easing. + * This method can be used to schedule a sequence of chained transitions. + * + * A delay configured for the new transition will be relative to the previous transition. + */ + transition(): Transition; + + // Modifying ------------------------------- + + /** + * For each selected element, assigns the attribute tween for the attribute with the specified name to the specified target value. + * The starting value of the tween is the attribute’s value when the transition starts. + * If the target value is null, the attribute is removed when the transition starts. + */ + attr(name: string, value: null | string | number | boolean): this; + /** + * For each selected element, assigns the attribute tween for the attribute with the specified name to the specified target value. + * The starting value of the tween is the attribute’s value when the transition starts. + * The target value is return value of the value function evaluated for the selected element. + * + * An interpolator is chosen based on the type of the target value, using the following algorithm: + * 1.) If value is a number, use interpolateNumber. + * 2.) If value is a color or a string coercible to a color, use interpolateRgb. + * 3.) Use interpolateString. + * + * To apply a different interpolator, use transition.attrTween. + * + * @param name Name of the attribute. + * @param value A value function which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). + * A null value will clear the attribute at the start of the transition. + */ + attr(name: string, value: ValueFn): this; + + /** + * Return the current interpolator factory for attribute with the specified name, or undefined if no such tween exists. + * + * @param name Name of attribute. + */ + attrTween(name: string): ValueFn string> | undefined; + /** + * Remove the previously-assigned attribute tween of the specified name, if any. + * + * @param name Name of attribute. + * @param factory Use null to remove previously-assigned attribute tween. + */ + attrTween(name: string, factory: null): this; + /** + * Assign the attribute tween for the attribute with the specified name to the specified interpolator factory. + * An interpolator factory is a function that returns an interpolator; when the transition starts, the factory is evaluated for each selected element. + * The returned interpolator will then be invoked for each frame of the transition, in order, + * being passed the eased time t, typically in the range [0, 1]. Lastly, the return value of the interpolator will be used to set the attribute value. + * The interpolator must return a string. + * + * @param name Name of attribute. + * @param factory An interpolator factory which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). The interpolator factory returns a string interpolator, + * which takes as its argument eased time t, typically in the range [0, 1] and returns the interpolated string. + */ + attrTween(name: string, factory: ValueFn string>): this; + + /** + * For each selected element, the style with the specified name will be cleared at the start of the transition. + * + * @param name Name of the style. + * @param value Use null to clear the style. + */ + style(name: string, value: null): this; + /** + * For each selected element, assigns the style tween for the style with the specified name to the specified target value with the + * specified priority. + * The starting value of the tween is the style’s inline value if present, and otherwise its computed value. + * The target value is the specified constant value for all elements. + * + * An interpolator is chosen based on the type of the target value, using the following algorithm: + * 1.) If value is a number, use interpolateNumber. + * 2.) If value is a color or a string coercible to a color, use interpolateRgb. + * 3.) Use interpolateString. + * + * To apply a different interpolator, use transition.attrTween. + * + * @param name Name of the style. + * @param value Target value for the style. + * @param priority An optional priority flag, either null or the string important (without the exclamation point) + */ + style(name: string, value: string | number | boolean, priority?: null | "important"): this; + /** + * For each selected element, assigns the style tween for the style with the specified name to the specified target value with the + * specified priority. + * The starting value of the tween is the style's inline value if present, and otherwise its computed value. + * The target value is return value of the value function evaluated for the selected element. + * + * An interpolator is chosen based on the type of the target value, using the following algorithm: + * 1.) If value is a number, use interpolateNumber. + * 2.) If value is a color or a string coercible to a color, use interpolateRgb. + * 3.) Use interpolateString. + * + * To apply a different interpolator, use transition.attrTween. + * + * @param name Name of the style. + * @param value A value function which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). + * A null value will clear the style at the start of the transition. + * @param priority An optional priority flag, either null or the string important (without the exclamation point) + */ + style( + name: string, + value: ValueFn, + priority?: null | "important", + ): this; + + /** + * Return the current interpolator factory for style with the specified name, or undefined if no such tween exists. + * + * @param name Name of style. + */ + styleTween(name: string): ValueFn string> | undefined; + /** + * Remove the previously-assigned style tween of the specified name, if any. + * + * @param name Name of style. + * @param factory Use null to remove previously-assigned style tween. + */ + styleTween(name: string, factory: null): this; + /** + * Assign the style tween for the style with the specified name to the specified interpolator factory. + * An interpolator factory is a function that returns an interpolator; when the transition starts, the factory is evaluated for each selected element. + * The returned interpolator will then be invoked for each frame of the transition, in order, + * being passed the eased time t, typically in the range [0, 1]. Lastly, the return value of the interpolator will be used to set the style value. + * The interpolator must return a string. + * + * @param name Name of style. + * @param factory An interpolator factory which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). The interpolator factory returns a string interpolator, + * which takes as its argument eased time t, typically in the range [0, 1] and returns the interpolated string. + * @param priority An optional priority flag, either null or the string important (without the exclamation point) + */ + styleTween( + name: string, + factory: ValueFn string>, + priority?: null | "important", + ): this; + + /** + * For each selected element, sets the text content to the specified target value when the transition starts. + * A null value will clear the content. + */ + text(value: null | string | number | boolean): this; + /** + * For each selected element, sets the text content returned by the value function for each selected element when the transition starts. + * + * To interpolate text rather than to set it on start, use transition.textTween (for example) or append a replacement element and cross-fade opacity (for example). + * Text is not interpolated by default because it is usually undesirable. + * + * @param value A value function which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). + * A null value will clear the text content at the start of the transition. + */ + text(value: ValueFn): this; + + /** + * Returns the current interpolator factory for text, or undefined if no such tween exists. + */ + textTween(): ValueFn string> | undefined; + /** + * Removes the previously-assigned text tween, if any + * + * @param factory Use null to remove previously-assigned text tween. + */ + textTween(factory: null): this; + /** + * Assigns the text tween to the specified interpolator factory. + * An interpolator factory is a function that returns an interpolator; when the transition starts, the factory is evaluated for each selected element, + * in order, being passed the current datum d and index i, with the this context as the current DOM element. + * The returned interpolator will then be invoked for each frame of the transition, in order, being passed the eased time t, typically in the range [0, 1]. + * Lastly, the return value of the interpolator will be used to set the text. + * The interpolator must return a string. + * + * @param factory An interpolator factory is a function that returns an interpolator; when the transition starts, the factory is evaluated for each selected element, + * in order, being passed the current datum d and index i, with the this context as the current DOM element. + * The returned interpolator will then be invoked for each frame of the transition, in order, being passed the eased time t, typically in the range [0, 1]. + * Lastly, the return value of the interpolator will be used to set the text. + * The interpolator must return a string. + */ + textTween(factory: ValueFn string>): this; + + /** + * For each selected element, removes the element when the transition ends, as long as the element has no other active or pending transitions. + * If the element has other active or pending transitions, does nothing. + */ + remove(): this; + + /** + * Returns the tween with the specified name, or undefined, if no tween was previously assigned to + * that name. + * + * @param name Name of tween. + */ + tween(name: string): ValueFn void> | undefined; + /** + * Removes the tween with the specified name, if a tween was previously assigned to + * that name. + * + * @param name Name of tween. + * @param tweenFn Use null to remove a previously-assigned tween. + */ + tween(name: string, tweenFn: null): this; + /** + * For each selected element, assigns the tween with the specified name with the specified value function. + * The value must be specified as a function that returns a function. + * When the transition starts, the value function is evaluated for each selected element. + * The returned function is then invoked for each frame of the transition, in order, + * being passed the eased time t, typically in the range [0, 1]. + * + * @param name Name of tween. + * @param tweenFn A tween function which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). The tween function returns a function + * which takes as its argument eased time t, typically in the range [0, 1] and performs the tweening activities for each transition frame. + */ + tween(name: string, tweenFn: ValueFn void>): this; + + /** + * Returns a new transition merging this transition with the specified other transition, + * which must have the same id as this transition. The returned transition has the same number of groups, + * the same parents, the same name and the same id as this transition. + * Any missing (null) elements in this transition are filled with the corresponding element, if present (not null), from the other transition. + * + * @param other The transition to be merged. + */ + merge(other: Transition): Transition; + + /** + * For each selected element, selects only the elements that match the specified filter, and returns a transition on the resulting selection. + * + * The new transition has the same id, name and timing as this transition; however, if a transition with the same id already exists on a selected element, + * the existing transition is returned for that element. + * + * @param filter A CSS selector string. + */ + filter(filter: string): Transition; + /** + * For each selected element, selects only the elements that match the specified filter, and returns a transition on the resulting selection. + * + * The new transition has the same id, name and timing as this transition; however, if a transition with the same id already exists on a selected element, + * the existing transition is returned for that element. + * + * The generic refers to the type of element which will be selected after applying the filter, i.e. if the element types + * contained in a pre-filter selection are narrowed to a subset as part of the filtering. + * + * @param filter A CSS selector string. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + filter(filter: string): Transition; + /** + * For each selected element, selects only the elements that match the specified filter, and returns a transition on the resulting selection. + * + * The new transition has the same id, name and timing as this transition; however, if a transition with the same id already exists on a selected element, + * the existing transition is returned for that element. + * + * @param filter A filter function which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). The filter function returns a boolean indicating, + * whether the selected element matches. + */ + filter(filter: ValueFn): Transition; + /** + * For each selected element, selects only the elements that match the specified filter, and returns a transition on the resulting selection. + * + * The new transition has the same id, name and timing as this transition; however, if a transition with the same id already exists on a selected element, + * the existing transition is returned for that element. + * + * The generic refers to the type of element which will be selected after applying the filter, i.e. if the element types + * contained in a pre-filter selection are narrowed to a subset as part of the filtering. + * + * @param filter A filter function which is evaluated for each selected element, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). The filter function returns a boolean indicating, + * whether the selected element matches. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + filter( + filter: ValueFn, + ): Transition; + + // Event Handling ------------------- + + /** + * Return the currently-assigned listener for the specified event typename on the first (non-null) selected element, if any. + * If multiple typenames are specified, the first matching listener is returned. + * + * @param typenames The typenames is one of the following string event types: start (when the transition starts), end (when the transition ends), + * interrupt (when the transition is interrupted), cancel(when the transition is cancelled). + * Note that these are not native DOM events. The type may be optionally followed by a period (.) and a name; + * the optional name allows multiple callbacks to be registered to receive events of the same type, such as "start.foo"" and "start.bar". + * To specify multiple typenames, separate typenames with spaces, such as "interrupt end"" or "start.foo start.bar". + */ + on(typenames: string): ValueFn | undefined; + /** + * Remove all listeners for a given name. + * + * @param typenames Name of the event type for which the listener should be removed. To remove all listeners for a given name use ".foo" + * as the typename, where foo is the name; to remove all listeners with no name, specify "." as the typename. + * @param listener Use null to remove listeners. + */ + on(typenames: string, listener: null): this; + /** + * Add a listener to each selected element for the specified event typenames. + * + * When a specified transition event is dispatched on a selected node, the specified listener will be invoked for each transitioning element. + * Listeners always see the latest datum for their element, but the index is a property of the selection and is fixed when the listener is assigned; + * to update the index, re-assign the listener. + * + * @param typenames The typenames is one of the following string event types: start (when the transition starts), end (when the transition ends), + * interrupt (when the transition is interrupted), cancel(when the transition is cancelled). + * Note that these are not native DOM events. The type may be optionally followed by a period (.) and a name; + * the optional name allows multiple callbacks to be registered to receive events of the same type, such as "start.foo"" and "start.bar". + * To specify multiple typenames, separate typenames with spaces, such as "interrupt end"" or "start.foo start.bar". + * @param listener A listener function which will be evaluated for each selected element, being passed the current datum (d), the current index (i), + * and the current group (nodes), with this as the current DOM element (nodes[i]). Listeners always see the latest datum for their element, + * but the index is a property of the selection and is fixed when the listener is assigned; to update the index, re-assign the listener. + */ + on(typenames: string, listener: ValueFn): this; + + /** + * Returns a promise that resolves when every selected element finishes transitioning. If any element’s transition is cancelled or interrupted, the promise rejects. + */ + end(): Promise; + + // Control Flow ---------------------- + + /** + * Invoke the specified function for each selected element, passing the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). + * This method can be used to invoke arbitrary code for each selected element, and is useful for creating a context to access parent and child data simultaneously. + * + * @param func A function which is invoked for each selected element, + * being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). + */ + each(func: ValueFn): this; + + /** + * Invoke the specified function exactly once, passing in this transition along with any optional arguments. + * Returns this transition. + * + * @param func A function which is passed this transition as the first argument along with any optional arguments. + * @param args List of optional arguments to be passed to the callback function. + */ + call( + func: (transition: Transition, ...args: any[]) => any, + ...args: any[] + ): this; + + /** + * Return true if this transition contains no (non-null) elements. + */ + empty(): boolean; + + /** + * Return the first (non-null) element in this transition. If the transition is empty, returns null. + */ + node(): GElement | null; + + /** + * Return an array of all (non-null) elements in this transition. + */ + nodes(): GElement[]; + + /** + * Returns the total number of elements in this transition. + */ + size(): number; + + // Transition Configuration ---------------------- + + /** + * Returns the current value of the delay for the first (non-null) element in the transition. + * This is generally useful only if you know that the transition contains exactly one element. + */ + delay(): number; + /** + * For each selected element, sets the transition delay to the specified value in milliseconds. + * If a delay is not specified, it defaults to zero. + * + * @param milliseconds Number of milliseconds for the delay. + */ + delay(milliseconds: number): this; + /** + * For each selected element, sets the transition delay to the value in milliseconds returned by the + * value function. + * + * @param milliseconds A value function which is evaluated for each selected element, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). The return value is a number + * specifying the delay in milliseconds. + */ + delay(milliseconds: ValueFn): this; + + /** + * Returns the current value of the duration for the first (non-null) element in the transition. + * This is generally useful only if you know that the transition contains exactly one element. + */ + duration(): number; + /** + * For each selected element, sets the transition duration to the specified value in milliseconds. + * If a duration is not specified, it defaults to 250ms. + * + * @param duration Number of milliseconds for the duration. + */ + duration(milliseconds: number): this; + /** + * For each selected element, sets the transition duration to the value in milliseconds returned by the + * value function. + * + * @param milliseconds A value function which is evaluated for each selected element, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). The return value is a number + * specifying the duration in milliseconds. + */ + duration(milliseconds: ValueFn): this; + + /** + * Returns the current easing function for the first (non-null) element in the transition. + * This is generally useful only if you know that the transition contains exactly one element. + */ + ease(): (normalizedTime: number) => number; + /** + * Specifies the transition easing function for all selected elements. The value must be specified as a function. + * The easing function is invoked for each frame of the animation, being passed the normalized time t in the range [0, 1]; + * it must then return the eased time tʹ which is typically also in the range [0, 1]. + * A good easing function should return 0 if t = 0 and 1 if t = 1. If an easing function is not specified, + * it defaults to d3.easeCubic. + * + * @param easingFn An easing function which is passed the normalized time t in the range [0, 1]; + * it must then return the eased time tʹ which is typically also in the range [0, 1]. + * A good easing function should return 0 if t = 0 and 1 if t = 1. + */ + ease(easingFn: (normalizedTime: number) => number): this; + + /** + * Specifies a factory for the transition easing function. + * + * @param factory The factory must be a function. + * It is invoked for each node of the selection, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element. + * It must return an easing function. + */ + easeVarying(factory: ValueFn number>): this; +} + +/** + * Represents the union of the Selection and Transition types for any usages that operate on both. + * Typically used for functions which take in either a selection or transition and set or update attributes. + */ +export type SelectionOrTransition = + | Selection + | Transition; + +/** + * Returns a new transition with the specified name. If a name is not specified, null is used. + * The new transition is only exclusive with other transitions of the same name. + * + * The generic "OldDatum" refers to the type of a previously-set datum of the selected element in the Transition. + * + * @param name Name of the transition. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function transition(name?: string): Transition; + +/** + * Returns a new transition from an existing transition. + * + * When using a transition instance, the returned transition has the same id and name as the specified transition. + * + * The generic "OldDatum" refers to the type of a previously-set datum of the selected element in the Transition. + * + * @param transition A transition instance. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function transition( + transition: Transition, +): Transition; diff --git a/tools/ui/node_modules/@types/d3-transition/package.json b/tools/ui/node_modules/@types/d3-transition/package.json new file mode 100644 index 0000000000000000000000000000000000000000..564ad4abdf051c98af6260d3e2d3ab41f32bff41 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-transition/package.json @@ -0,0 +1,47 @@ +{ + "name": "@types/d3-transition", + "version": "3.0.9", + "description": "TypeScript definitions for d3-transition", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-transition", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "Robert Moura", + "githubUsername": "robertmoura", + "url": "https://github.com/robertmoura" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-transition" + }, + "scripts": {}, + "dependencies": { + "@types/d3-selection": "*" + }, + "typesPublisherContentHash": "69cd5510811e76132548e17770c16a10a8ffe039c97e6d45b3663749af4591dd", + "typeScriptVersion": "4.8" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3-zoom/LICENSE b/tools/ui/node_modules/@types/d3-zoom/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-zoom/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3-zoom/README.md b/tools/ui/node_modules/@types/d3-zoom/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5deea64bb07fd10f12e0f4fa2b0ce67cfcd76a05 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-zoom/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/d3-zoom` + +# Summary +This package contains type definitions for d3-zoom (https://github.com/d3/d3-zoom/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-zoom. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:37 GMT + * Dependencies: [@types/d3-interpolate](https://npmjs.com/package/@types/d3-interpolate), [@types/d3-selection](https://npmjs.com/package/@types/d3-selection) + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [denisname](https://github.com/denisname), and [Nathan Bierema](https://github.com/Methuselah96). diff --git a/tools/ui/node_modules/@types/d3-zoom/index.d.ts b/tools/ui/node_modules/@types/d3-zoom/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..36c083833d4cec345a41205e38ad1e4bab4ceeea --- /dev/null +++ b/tools/ui/node_modules/@types/d3-zoom/index.d.ts @@ -0,0 +1,611 @@ +// Last module patch version validated against: 3.0.0 + +import { ZoomView } from "d3-interpolate"; +import { Selection, TransitionLike, ValueFn } from "d3-selection"; + +// -------------------------------------------------------------------------- +// Shared Type Definitions and Interfaces +// -------------------------------------------------------------------------- + +/** + * ZoomedElementBaseType serves as an alias for the 'minimal' data type which can be selected + * without 'd3-zoom' (and related code in 'd3-selection') trying to use properties internally which would otherwise not + * be supported. + */ +export type ZoomedElementBaseType = Element; + +/** + * Minimal interface for a continuous scale. + * This interface is used as a minimum contract for scale objects + * that can be passed into zoomTransform methods rescaleX and rescaleY + */ +export interface ZoomScale { + domain(): number[] | Date[]; + domain(domain: Array): this; + range(): number[]; + range(range: number[]): this; + copy(): ZoomScale; + invert(value: number): number | Date; +} + +// -------------------------------------------------------------------------- +// Zoom Behavior +// -------------------------------------------------------------------------- + +/** + * A D3 Zoom Behavior + * + * The first generic refers to the type of reference element to which the zoom behavior is attached. + * The second generic refers to the type of the datum of the reference element. + */ +export interface ZoomBehavior extends Function { + /** + * Applies this zoom behavior to the specified selection, binding the necessary event listeners to + * allow panning and zooming, and initializing the zoom transform on each selected element to the identity transform if not already defined. This function is typically not invoked directly, + * and is instead invoked via selection.call. + * + * For details see: {@link https://github.com/d3/d3-zoom#_zoom} + * + * @param selection A D3 selection of elements. + * @param args Optional arguments to be passed in. + */ + (selection: Selection, ...args: any[]): void; + /** + * If selection is a selection, sets the current zoom transform of the selected elements to the specified transform, instantaneously emitting start, zoom and end events. + * If selection is a transition, defines a “zoom” tween to the specified transform using d3.interpolateZoom, emitting a start event when the transition starts, + * zoom events for each tick of the transition, and then an end event when the transition ends (or is interrupted). + * The transition will attempt to minimize the visual movement around the specified point; if the point is not specified, it defaults to the center of the viewport extent. + * + * This function is typically not invoked directly, and is instead invoked via selection.call or transition.call. + * + * @param selection A selection or a transition. + * @param transform A zoom transform or a function that returns a zoom transform. + * If a function, it is invoked for each selected element, being passed the current event (event) and datum d, with the this context as the current DOM element. + * @param point A two-element array [x, y] or a function that returns such an array. + * If a function, it is invoked for each selected element, being passed the current event (event) and datum d, with the this context as the current DOM element. + */ + transform( + selection: Selection | TransitionLike, + transform: ZoomTransform | ((this: ZoomRefElement, event: any, d: Datum) => ZoomTransform), + point?: [number, number] | ((this: ZoomRefElement, event: any, d: Datum) => [number, number]), + ): void; + + /** + * If selection is a selection, translates the current zoom transform of the selected elements by x and y, such that the new tx1 = tx0 + kx and ty1 = ty0 + ky. + * If selection is a transition, defines a “zoom” tween translating the current transform. + * This method is a convenience method for zoom.transform. + * + * @param selection A selection or a transition. + * @param x A number or a function that returns a number. + * If a function, it is invoked for each selected element, being passed the current datum d and index i, with the this context as the current DOM element. + * @param y A number or a function that returns a number. + * If a function, it is invoked for each selected element, being passed the current datum d and index i, with the this context as the current DOM element. + */ + translateBy( + selection: Selection | TransitionLike, + x: number | ValueFn, + y: number | ValueFn, + ): void; + + /** + * If selection is a selection, translates the current zoom transform of the selected elements such that the given position ⟨x,y⟩ appears at given point p. + * The new tx = px - kx and ty = py - ky. If p is not specified, it defaults to the center of the viewport extent. + * If selection is a transition, defines a “zoom” tween translating the current transform. This method is a convenience method for zoom.transform. + * + * Translates the current zoom transform of the selected elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided as a constant for all elements. + * y is provided as a constant for all elements. + * + * @param selection A selection or a transition. + * @param x A number or a function that returns a number. + * If a function, it is invoked for each selected element, being passed the current datum d and index i, with the this context as the current DOM element. + * @param y A number or a function that returns a number. + * If a function, it is invoked for each selected element, being passed the current datum d and index i, with the this context as the current DOM element. + * @param p A two-element array [px,py] or a function + * If a function, it is invoked for each selected element, being passed the current datum d and index i, with the this context as the current DOM element. + */ + translateTo( + selection: Selection | TransitionLike, + x: number | ValueFn, + y: number | ValueFn, + p?: [number, number] | ValueFn, + ): void; + + /** + * If selection is a selection, scales the current zoom transform of the selected elements by k, such that the new k₁ = k₀k. + * The reference point p does move. + * If p is not specified, it defaults to the center of the viewport extent. + * If selection is a transition, defines a “zoom” tween translating the current transform. + * This method is a convenience method for zoom.transform. + * + * @param selection A selection or a transition. + * @param k Scale factor. A number or a function that returns a number. + * If a function, it is invoked for each selected element, being passed the current datum d and index i, with the this context as the current DOM element. + * @param p A two-element array [px,py] or a function. + * If a function, it is invoked for each selected element, being passed the current datum d and index i, with the this context as the current DOM element. + */ + scaleBy( + selection: Selection | TransitionLike, + k: number | ValueFn, + p?: [number, number] | ValueFn, + ): void; + + /** + * If selection is a selection, scales the current zoom transform of the selected elements to k, such that the new k₁ = k. + * The reference point p does move. + * If p is not specified, it defaults to the center of the viewport extent. + * If selection is a transition, defines a “zoom” tween translating the current transform. + * This method is a convenience method for zoom.transform. + * + * @param selection: A selection or a transition. + * @param k Scale factor. A number or a function that returns a number. + * If a function, it is invoked for each selected element, being passed the current datum d and index i, with the this context as the current DOM element. + * @param p A two-element array [px,py] or a function. + * If a function, it is invoked for each selected element, being passed the current datum d and index i, with the this context as the current DOM element. + */ + scaleTo( + selection: Selection | TransitionLike, + k: number | ValueFn, + p?: [number, number], + ): void; + + /** + * Returns the current constraint function. + * The default implementation attempts to ensure that the viewport extent does not go outside the translate extent. + */ + constrain(): ( + transform: ZoomTransform, + extent: [[number, number], [number, number]], + translateExtent: [[number, number], [number, number]], + ) => ZoomTransform; + /** + * Sets the transform constraint function to the specified function and returns the zoom behavior. + * + * @param constraint A constraint function which returns a transform given the current transform, viewport extent and translate extent. + * The default implementation attempts to ensure that the viewport extent does not go outside the translate extent. + */ + constrain( + constraint: ( + transform: ZoomTransform, + extent: [[number, number], [number, number]], + translateExtent: [[number, number], [number, number]], + ) => ZoomTransform, + ): this; + + /** + * Returns the current filter function. + */ + filter(): (this: ZoomRefElement, event: any, datum: Datum) => boolean; + /** + * Sets the filter to the specified filter function and returns the zoom behavior. + * The filter function is invoked in the zoom initiating event handlers of each element to which the zoom behavior was applied. + * + * If the filter returns falsey, the initiating event is ignored and no zoom gesture is started. + * Thus, the filter determines which input events are ignored. The default filter ignores mousedown events on secondary buttons, + * since those buttons are typically intended for other purposes, such as the context menu. + * + * @param filter A filter function which is invoked in the zoom initiating event handlers of each element to which the zoom behavior was applied, + * in order, being passed the current event (event) and datum d, with the this context as the current DOM element. + * The function returns a boolean value. + */ + filter(filter: (this: ZoomRefElement, event: any, datum: Datum) => boolean): this; + + /** + * Returns the current touch support detector, which defaults to a function returning true, + * if the "ontouchstart" event is supported on the current element. + */ + touchable(): ValueFn; + /** + * Sets the touch support detector to the specified boolean value and returns the zoom behavior. + * + * Touch event listeners are only registered if the detector returns truthy for the corresponding element when the zoom behavior is applied. + * The default detector works well for most browsers that are capable of touch input, but not all; Chrome’s mobile device emulator, for example, + * fails detection. + * + * @param touchable A boolean value. true when touch event listeners should be applied to the corresponding element, otherwise false. + */ + touchable(touchable: boolean): this; + /** + * Sets the touch support detector to the specified function and returns the zoom behavior. + * + * Touch event listeners are only registered if the detector returns truthy for the corresponding element when the zoom behavior is applied. + * The default detector works well for most browsers that are capable of touch input, but not all; Chrome’s mobile device emulator, for example, + * fails detection. + * + * @param touchable A touch support detector function, which returns true when touch event listeners should be applied to the corresponding element. + * The function is evaluated for each selected element to which the zoom behavior was applied, in order, being passed the current datum (d), + * the current index (i), and the current group (nodes), with this as the current DOM element. The function returns a boolean value. + */ + touchable(touchable: ValueFn): this; + + /** + * Returns the current wheelDelta function. + */ + wheelDelta(): ValueFn; + /** + * Sets the wheel delta function to the specified function and returns the zoom behavior. The wheel delta function which is invoked in the wheel event handler + * of each element to which the zoom behavior was applied. + * The value Δ returned by the wheel delta function determines the amount of scaling applied in response to a WheelEvent. + * The scale factor transform.k is multiplied by 2Δ; for example, a Δ of +1 doubles the scale factor, Δ of -1 halves the scale factor. + * + * @param delta Wheel delta function which is invoked in the wheel event handler of each element to which the zoom behavior was applied, + * in order, being passed the wheel event that triggered the handler, + * with this as the current DOM element. The function returns a numeric value. + */ + wheelDelta(delta: ((event: WheelEvent) => number) | number): this; + + /** + * Return the current extent accessor, which defaults to [[0, 0], [width, height]] where width is the client width of the element and height is its client height; + * for SVG elements, the nearest ancestor SVG element’s width and height is used. In this case, + * the owner SVG element must have defined width and height attributes rather than (for example) relying on CSS properties or the viewBox attribute; + * SVG provides no programmatic method for retrieving the initial viewport size. Alternatively, consider using element.getBoundingClientRect. + * (In Firefox, element.clientWidth and element.clientHeight is zero for SVG elements!) + */ + extent(): (this: ZoomRefElement, datum: Datum) => [[number, number], [number, number]]; + /** + * Set the viewport extent to the specified array of points [[x0, y0], [x1, y1]], + * where [x0, y0] is the top-left corner of the viewport and [x1, y1] is the bottom-right corner of the viewport, + * and return this zoom behavior. + * + * The viewport extent affects several functions: the center of the viewport remains fixed during changes by zoom.scaleBy and zoom.scaleTo; + * the viewport center and dimensions affect the path chosen by d3.interpolateZoom; and the viewport extent is needed to enforce the optional translate extent. + * + * @param extent An extent specified as an array of two coordinates. + */ + extent(extent: [[number, number], [number, number]]): this; + /** + * Set the viewport extent to the array of points [[x0, y0], [x1, y1]] returned by the + * extent accessor function, and return this zoom behavior. + * The extent accessor function is evaluated for each element. + * + * [x0, y0] is the top-left corner of the viewport and [x1, y1] is the bottom-right corner of the viewport. + * + * The viewport extent affects several functions: the center of the viewport remains fixed during changes by zoom.scaleBy and zoom.scaleTo; + * the viewport center and dimensions affect the path chosen by d3.interpolateZoom; and the viewport extent is needed to enforce the optional translate extent. + * + * The default is [[0, 0], [width, height]] where width is the client width of the element and height is its client height; + * for SVG elements, the nearest ancestor SVG element’s width and height is used. + * In this case, the owner SVG element must have defined width and height attributes rather than (for example) relying on CSS properties or the viewBox attribute; + * SVG provides no programmatic method for retrieving the initial viewport size. Alternatively, consider using element.getBoundingClientRect. + * (In Firefox, element.clientWidth and element.clientHeight is zero for SVG elements!) + * + * @param extent An extent accessor function which is evaluated for each selected element, being passed the current datum d, with the this context as the current DOM element. + * The function returns the extent array. + */ + extent(extent: (this: ZoomRefElement, datum: Datum) => [[number, number], [number, number]]): this; + + /** + * Return the current scale extent. + */ + scaleExtent(): [number, number]; + /** + * Set the scale extent to the specified array of numbers [k0, k1] where k0 is the minimum allowed scale factor and k1 is the maximum allowed scale factor, + * and return this zoom behavior. + * + * The scale extent restricts zooming in and out. It is enforced on interaction and when using zoom.scaleBy, zoom.scaleTo and zoom.translateBy; + * however, it is not enforced when using zoom.transform to set the transform explicitly. + * + * The default scale extent is [0, infinity]. + * + * If the user tries to zoom by wheeling when already at the corresponding limit of the scale extent, the wheel events will be ignored and not initiate a zoom gesture. + * This allows the user to scroll down past a zoomable area after zooming in, or to scroll up after zooming out. + * If you would prefer to always prevent scrolling on wheel input regardless of the scale extent, register a wheel event listener to prevent the browser default behavior + * + * @param extent A scale extent array of two numbers representing the scale boundaries. + */ + scaleExtent(extent: [number, number]): this; + + /** + * Return the current translate extent. + */ + translateExtent(): [[number, number], [number, number]]; + /** + * Set the translate extent to the specified array of points [[x0, y0], [x1, y1]], where [x0, y0] is the top-left corner of the world and [x1, y1] + * is the bottom-right corner of the world, and return this zoom behavior. + * + * The translate extent restricts panning, and may cause translation on zoom out. It is enforced on interaction and when using zoom.scaleBy, zoom.scaleTo and zoom.translateBy; + * however, it is not enforced when using zoom.transform to set the transform explicitly. + * + * The default scale extent is [[-infinity, infinity], [-infinity, infinity]]. + * + * @param extent A translate extent array, i.e. an array of two arrays, each representing a point. + */ + translateExtent(extent: [[number, number], [number, number]]): this; + + /** + * Return the current click distance threshold, which defaults to zero. + */ + clickDistance(): number; + /** + * Set the maximum distance that the mouse can move between mousedown and mouseup that will trigger + * a subsequent click event. If at any point between mousedown and mouseup the mouse is greater than or equal to + * distance from its position on mousedown, the click event following mouseup will be suppressed. + * + * @param distance The distance threshold between mousedown and mouseup measured in client coordinates (event.clientX and event.clientY). + * The default is zero. + */ + clickDistance(distance: number): this; + + /** + * Return the current tap distance threshold, which defaults to 10. + */ + tapDistance(): number; + /** + * Sets the maximum distance that a double-tap gesture can move between first touchstart and second touchend that will trigger a subsequent double-click event. + * + * @param distance The distance threshold between mousedown and mouseup measured in client coordinates (event.clientX and event.clientY). + * The default is 10. + */ + tapDistance(distance: number): this; + + /** + * Get the duration for zoom transitions on double-click and double-tap in milliseconds. + */ + duration(): number; + /** + * Set the duration for zoom transitions on double-click and double-tap to the specified number of milliseconds and returns the zoom behavior. + * + * To disable double-click and double-tap transitions, you can remove the zoom behavior’s dblclick event listener after applying the zoom behavior to the selection. + * + * @param duration in milliseconds. + */ + duration(duration: number): this; + + /** + * Returns the current interpolation factory, which defaults to d3.interpolateZoom to implement smooth zooming. + */ + interpolate< + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + InterpolationFactory extends (a: ZoomView, b: ZoomView) => (t: number) => ZoomView, + >(): InterpolationFactory; + + /** + * Sets the interpolation factory for zoom transitions to the specified function. + * Use the default d3.interpolateZoom to implement smooth zooming. + * To apply direct interpolation between two views, try d3.interpolate instead. + * + * Each view is defined as an array of three numbers: cx, cy and width. The first two coordinates cx, cy represent the center of the viewport; + * the last coordinate width represents the size of the viewport. + * + * @param interpolatorFactory An interpolator factory to be used to generate interpolators between zooms for transitions. + */ + interpolate(interpolatorFactory: (a: ZoomView, b: ZoomView) => (t: number) => ZoomView): this; + + /** + * Return the first currently-assigned listener matching the specified typenames, if any. + * + * @param typenames The typenames is a string containing one or more typename separated by whitespace. + * Each typename is a type, optionally followed by a period (.) and a name, such as "drag.foo"" and "drag.bar"; + * the name allows multiple listeners to be registered for the same type. The type must be one of the following: + * start (after zooming begins [such as mousedown]), zoom (after a change to the zoom transform [such as mousemove], or + * end (after an active pointer becomes inactive [such as on mouseup].) + */ + on(typenames: string): ((this: ZoomRefElement, event: any, d: Datum) => void) | undefined; + /** + * Remove the current event listeners for the specified typenames, if any, return the drag behavior. + * + * @param typenames The typenames is a string containing one or more typename separated by whitespace. + * Each typename is a type, optionally followed by a period (.) and a name, such as "drag.foo"" and "drag.bar"; + * the name allows multiple listeners to be registered for the same type. The type must be one of the following: + * start (after zooming begins [such as mousedown]), zoom (after a change to the zoom transform [such as mousemove], or + * end (after an active pointer becomes inactive [such as on mouseup].) + * @param listener Use null to remove the listener. + */ + on(typenames: string, listener: null): this; + /** + * Set the event listener for the specified typenames and return the zoom behavior. + * If an event listener was already registered for the same type and name, + * the existing listener is removed before the new listener is added. + * When a specified event is dispatched, each listener will be invoked with the same context and arguments as selection.on listeners. + * + * @param typenames The typenames is a string containing one or more typename separated by whitespace. + * Each typename is a type, optionally followed by a period (.) and a name, such as "drag.foo"" and "drag.bar"; + * the name allows multiple listeners to be registered for the same type. The type must be one of the following: + * start (after zooming begins [such as mousedown]), zoom (after a change to the zoom transform [such as mousemove], or + * end (after an active pointer becomes inactive [such as on mouseup].) + * @param listener An event listener function which is evaluated for each selected element, + * in order, being passed the current event (event) and datum d, with the this context as the current DOM element. + */ + on(typenames: string, listener: (this: ZoomRefElement, event: any, d: Datum) => void): this; +} + +/** + * Creates a new zoom behavior. The returned behavior, zoom, is both an object and a function, + * and is typically applied to selected elements via selection.call. + * + * The first generic refers to the type of reference element to which the zoom behavior is attached. + * The second generic refers to the type of the datum of the reference element. + */ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export function zoom(): ZoomBehavior; + +// -------------------------------------------------------------------------- +// Zoom Event +// -------------------------------------------------------------------------- + +/** + * A D3 Zoom Event + * + * The first generic refers to the type of reference element to which the zoom behavior is attached. + * The second generic refers to the type of the datum of the reference element. + */ +export interface D3ZoomEvent { + /** + * The ZoomBehavior associated with the event + */ + target: ZoomBehavior; + /** + * The event type for the zoom event + */ + type: "start" | "zoom" | "end" | string; // Leave failsafe string type for cases like 'zoom.foo' + /** + * The current zoom transform + */ + transform: ZoomTransform; + /** + * The underlying input event, such as mousemove or touchmove. + */ + sourceEvent: any; +} + +// -------------------------------------------------------------------------- +// Zoom Transforms +// -------------------------------------------------------------------------- + +/** + * A zoom transform + * + * The zoom behavior stores the zoom state on the element to which the zoom behavior was applied, not on the zoom behavior itself. + * This is because the zoom behavior can be applied to many elements simultaneously, and each element can be zoomed independently. + * The zoom state can change either on user interaction or programmatically via zoom.transform. + * + * To retrieve the zoom state, use event.transform on the current zoom event within a zoom event listener (see zoom.on), or use d3.zoomTransform for a given node. + * The latter is particularly useful for modifying the zoom state programmatically, + * say to implement buttons for zooming in and out. + * + * For details see {@link https://github.com/d3/d3-zoom#zoom-transforms} + */ +export class ZoomTransform { + /** + * Returns a transform with scale k and translation (x, y). + */ + constructor(k: number, x: number, y: number); + + /** + * The translation amount tx along the x-axis. + * This property should be considered read-only; instead of mutating a transform, + * use transform.scale and transform.translate to derive a new transform. + * Also see zoom.scaleBy, zoom.scaleTo and zoom.translateBy for convenience methods on the zoom behavior. + */ + readonly x: number; + + /** + * The translation amount ty along the y-axis + * This property should be considered read-only; instead of mutating a transform, + * use transform.scale and transform.translate to derive a new transform. + * Also see zoom.scaleBy, zoom.scaleTo and zoom.translateBy for convenience methods on the zoom behavior. + */ + readonly y: number; + + /** + * The scale factor k. + * This property should be considered read-only; instead of mutating a transform, + * use transform.scale and transform.translate to derive a new transform. + * Also see zoom.scaleBy, zoom.scaleTo and zoom.translateBy for convenience methods on the zoom behavior. + */ + readonly k: number; + + /** + * Return the transformation of the specified point which is a two-element array of numbers [x, y]. + * The returned point is equal to [xk + tx, yk + ty]. + * + * @param point Point coordinates [x, y] + */ + apply(point: [number, number]): [number, number]; + + /** + * Return the transformation of the specified x-coordinate, xk + tx. + * + * @param x Value of x-coordinate. + */ + applyX(x: number): number; + + /** + * Return the transformation of the specified y-coordinate, yk + ty. + * + * @param y Value of y-coordinate. + */ + applyY(y: number): number; + + /** + * Return the inverse transformation of the specified point which is a two-element array of numbers [x, y]. + * The returned point is equal to [(x - tx) / k, (y - ty) / k]. + * + * @param point Point coordinates [x, y] + */ + invert(point: [number, number]): [number, number]; + + /** + * Return the inverse transformation of the specified x-coordinate, (x - tx) / k. + * + * @param x Value of x-coordinate. + */ + invertX(x: number): number; + + /** + * Return the inverse transformation of the specified y-coordinate, (y - ty) / k. + * + * @param y Value of y-coordinate. + */ + invertY(y: number): number; + + /** + * Returns a copy of the continuous scale x whose domain is transformed. + * This is implemented by first applying the inverse x-transform on the scale’s range, + * and then applying the inverse scale to compute the corresponding domain + * + * The scale x must use d3.interpolateNumber; do not use continuous.rangeRound as this + * reduces the accuracy of continuous.invert and can lead to an inaccurate rescaled domain. + * This method does not modify the input scale x; x thus represents the untransformed scale, + * while the returned scale represents its transformed view. + * + * @param xScale A continuous scale for x-dimension. + */ + rescaleX(xScale: S): S; + + /** + * Returns a copy of the continuous scale y whose domain is transformed. + * This is implemented by first applying the inverse y-transform on the scale’s range, + * and then applying the inverse scale to compute the corresponding domain + * + * The scale y must use d3.interpolateNumber; do not use continuous.rangeRound as this + * reduces the accuracy of continuous.invert and can lead to an inaccurate rescaled domain. + * This method does not modify the input scale x; x thus represents the untransformed scale, + * while the returned scale represents its transformed view. + * + * @param yScale A continuous scale for y-dimension. + */ + rescaleY(yScale: S): S; + + /** + * Return a transform whose scale k1 is equal to k0 × k, where k0 is this transform’s scale. + * + * @param k A scale factor. + */ + scale(k: number): ZoomTransform; + + /** + * Return a string representing the SVG transform corresponding to this transform. + */ + toString(): string; + + /** + * Returns a transform whose translation tx1 and ty1 is equal to tx0 + tkx and ty0 + tky, + * where tx0 and ty0 is this transform’s translation and tk is this transform’s scale. + * + * @param x Amount of translation in x-direction. + * @param y Amount of translation in y-direction. + */ + translate(x: number, y: number): ZoomTransform; +} + +/** + * Returns the current transform for the specified node. Note that node should typically be a DOM element, and not a selection. + * (A selection may consist of multiple nodes, in different states, and this function only returns a single transform.) If you have a selection, call selection.node first. + * In the context of an event listener, the node is typically the element that received the input event (which should be equal to event.transform), "this". + * Internally, an element’s transform is stored as element.__zoom; however, you should use this method rather than accessing it directly. + * If the given node has no defined transform, returns the identity transformation. + * The returned transform represents a two-dimensional transformation matrix + * + * For details see {@link https://github.com/d3/d3-zoom#zoom-transforms} + * + * @param node An element for which to retrieve its current zoom transform. + */ +export function zoomTransform(node: ZoomedElementBaseType): ZoomTransform; + +/** + * The identity transform, where k = 1, tx = ty = 0. + */ +export const zoomIdentity: ZoomTransform; diff --git a/tools/ui/node_modules/@types/d3-zoom/package.json b/tools/ui/node_modules/@types/d3-zoom/package.json new file mode 100644 index 0000000000000000000000000000000000000000..32099168fcae4c20dae3872d6df747f976496bd9 --- /dev/null +++ b/tools/ui/node_modules/@types/d3-zoom/package.json @@ -0,0 +1,48 @@ +{ + "name": "@types/d3-zoom", + "version": "3.0.8", + "description": "TypeScript definitions for d3-zoom", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3-zoom", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3-zoom" + }, + "scripts": {}, + "dependencies": { + "@types/d3-interpolate": "*", + "@types/d3-selection": "*" + }, + "typesPublisherContentHash": "19cbff2a5c60ea95d9eaa6d3d1a4ec6f8e60ec8a8560cf1bd2e359f057335776", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/d3/LICENSE b/tools/ui/node_modules/@types/d3/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/d3/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/d3/README.md b/tools/ui/node_modules/@types/d3/README.md new file mode 100644 index 0000000000000000000000000000000000000000..28fd35805be37cecc5acbb2333cd02e7e462e5ba --- /dev/null +++ b/tools/ui/node_modules/@types/d3/README.md @@ -0,0 +1,58 @@ +# Installation +> `npm install --save @types/d3` + +# Summary +This package contains type definitions for d3 (https://github.com/d3/d3). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3. +## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3/index.d.ts) +````ts +// Last module patch version validated against: 7.4.4 + +export as namespace d3; + +/** + * Version number in format _Major.Minor.BugFix_, like 7.0.0. + */ +export const version: string; + +export * from "d3-array"; +export * from "d3-axis"; +export * from "d3-brush"; +export * from "d3-chord"; +export * from "d3-color"; +export * from "d3-contour"; +export * from "d3-delaunay"; +export * from "d3-dispatch"; +export * from "d3-drag"; +export * from "d3-dsv"; +export * from "d3-ease"; +export * from "d3-fetch"; +export * from "d3-force"; +export * from "d3-format"; +export * from "d3-geo"; +export * from "d3-hierarchy"; +export * from "d3-interpolate"; +export * from "d3-path"; +export * from "d3-polygon"; +export * from "d3-quadtree"; +export * from "d3-random"; +export * from "d3-scale"; +export * from "d3-scale-chromatic"; +export * from "d3-selection"; +export * from "d3-shape"; +export * from "d3-time"; +export * from "d3-time-format"; +export * from "d3-timer"; +export * from "d3-transition"; +export * from "d3-zoom"; + +```` + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:36 GMT + * Dependencies: [@types/d3-array](https://npmjs.com/package/@types/d3-array), [@types/d3-axis](https://npmjs.com/package/@types/d3-axis), [@types/d3-brush](https://npmjs.com/package/@types/d3-brush), [@types/d3-chord](https://npmjs.com/package/@types/d3-chord), [@types/d3-color](https://npmjs.com/package/@types/d3-color), [@types/d3-contour](https://npmjs.com/package/@types/d3-contour), [@types/d3-delaunay](https://npmjs.com/package/@types/d3-delaunay), [@types/d3-dispatch](https://npmjs.com/package/@types/d3-dispatch), [@types/d3-drag](https://npmjs.com/package/@types/d3-drag), [@types/d3-dsv](https://npmjs.com/package/@types/d3-dsv), [@types/d3-ease](https://npmjs.com/package/@types/d3-ease), [@types/d3-fetch](https://npmjs.com/package/@types/d3-fetch), [@types/d3-force](https://npmjs.com/package/@types/d3-force), [@types/d3-format](https://npmjs.com/package/@types/d3-format), [@types/d3-geo](https://npmjs.com/package/@types/d3-geo), [@types/d3-hierarchy](https://npmjs.com/package/@types/d3-hierarchy), [@types/d3-interpolate](https://npmjs.com/package/@types/d3-interpolate), [@types/d3-path](https://npmjs.com/package/@types/d3-path), [@types/d3-polygon](https://npmjs.com/package/@types/d3-polygon), [@types/d3-quadtree](https://npmjs.com/package/@types/d3-quadtree), [@types/d3-random](https://npmjs.com/package/@types/d3-random), [@types/d3-scale](https://npmjs.com/package/@types/d3-scale), [@types/d3-scale-chromatic](https://npmjs.com/package/@types/d3-scale-chromatic), [@types/d3-selection](https://npmjs.com/package/@types/d3-selection), [@types/d3-shape](https://npmjs.com/package/@types/d3-shape), [@types/d3-time](https://npmjs.com/package/@types/d3-time), [@types/d3-time-format](https://npmjs.com/package/@types/d3-time-format), [@types/d3-timer](https://npmjs.com/package/@types/d3-timer), [@types/d3-transition](https://npmjs.com/package/@types/d3-transition), [@types/d3-zoom](https://npmjs.com/package/@types/d3-zoom) + +# Credits +These definitions were written by [Tom Wanzek](https://github.com/tomwanzek), [Alex Ford](https://github.com/gustavderdrache), [Boris Yankov](https://github.com/borisyankov), [denisname](https://github.com/denisname), [Nathan Bierema](https://github.com/Methuselah96), and [Fil](https://github.com/Fil). diff --git a/tools/ui/node_modules/@types/d3/index.d.ts b/tools/ui/node_modules/@types/d3/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..442fd43160d13a2da5793d4a4c7eef1c4c893982 --- /dev/null +++ b/tools/ui/node_modules/@types/d3/index.d.ts @@ -0,0 +1,39 @@ +// Last module patch version validated against: 7.4.4 + +export as namespace d3; + +/** + * Version number in format _Major.Minor.BugFix_, like 7.0.0. + */ +export const version: string; + +export * from "d3-array"; +export * from "d3-axis"; +export * from "d3-brush"; +export * from "d3-chord"; +export * from "d3-color"; +export * from "d3-contour"; +export * from "d3-delaunay"; +export * from "d3-dispatch"; +export * from "d3-drag"; +export * from "d3-dsv"; +export * from "d3-ease"; +export * from "d3-fetch"; +export * from "d3-force"; +export * from "d3-format"; +export * from "d3-geo"; +export * from "d3-hierarchy"; +export * from "d3-interpolate"; +export * from "d3-path"; +export * from "d3-polygon"; +export * from "d3-quadtree"; +export * from "d3-random"; +export * from "d3-scale"; +export * from "d3-scale-chromatic"; +export * from "d3-selection"; +export * from "d3-shape"; +export * from "d3-time"; +export * from "d3-time-format"; +export * from "d3-timer"; +export * from "d3-transition"; +export * from "d3-zoom"; diff --git a/tools/ui/node_modules/@types/d3/package.json b/tools/ui/node_modules/@types/d3/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e945e0ca1a9018e4955f7cf8ca2459a4a1dfc975 --- /dev/null +++ b/tools/ui/node_modules/@types/d3/package.json @@ -0,0 +1,81 @@ +{ + "name": "@types/d3", + "version": "7.4.3", + "description": "TypeScript definitions for d3", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3", + "license": "MIT", + "contributors": [ + { + "name": "Tom Wanzek", + "githubUsername": "tomwanzek", + "url": "https://github.com/tomwanzek" + }, + { + "name": "Alex Ford", + "githubUsername": "gustavderdrache", + "url": "https://github.com/gustavderdrache" + }, + { + "name": "Boris Yankov", + "githubUsername": "borisyankov", + "url": "https://github.com/borisyankov" + }, + { + "name": "denisname", + "githubUsername": "denisname", + "url": "https://github.com/denisname" + }, + { + "name": "Nathan Bierema", + "githubUsername": "Methuselah96", + "url": "https://github.com/Methuselah96" + }, + { + "name": "Fil", + "githubUsername": "Fil", + "url": "https://github.com/Fil" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/d3" + }, + "scripts": {}, + "dependencies": { + "@types/d3-array": "*", + "@types/d3-axis": "*", + "@types/d3-brush": "*", + "@types/d3-chord": "*", + "@types/d3-color": "*", + "@types/d3-contour": "*", + "@types/d3-delaunay": "*", + "@types/d3-dispatch": "*", + "@types/d3-drag": "*", + "@types/d3-dsv": "*", + "@types/d3-ease": "*", + "@types/d3-fetch": "*", + "@types/d3-force": "*", + "@types/d3-format": "*", + "@types/d3-geo": "*", + "@types/d3-hierarchy": "*", + "@types/d3-interpolate": "*", + "@types/d3-path": "*", + "@types/d3-polygon": "*", + "@types/d3-quadtree": "*", + "@types/d3-random": "*", + "@types/d3-scale": "*", + "@types/d3-scale-chromatic": "*", + "@types/d3-selection": "*", + "@types/d3-shape": "*", + "@types/d3-time": "*", + "@types/d3-time-format": "*", + "@types/d3-timer": "*", + "@types/d3-transition": "*", + "@types/d3-zoom": "*" + }, + "typesPublisherContentHash": "7585034c2b0d3e0a098ffbe6db8d66a0f5ec671b95619a561c4288d56b7e2128", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/debug/LICENSE b/tools/ui/node_modules/@types/debug/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/debug/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/debug/README.md b/tools/ui/node_modules/@types/debug/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c62700a70deb6836a04abcb04f935f3fbf16431f --- /dev/null +++ b/tools/ui/node_modules/@types/debug/README.md @@ -0,0 +1,69 @@ +# Installation +> `npm install --save @types/debug` + +# Summary +This package contains type definitions for debug (https://github.com/debug-js/debug). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/debug. +## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/debug/index.d.ts) +````ts +declare var debug: debug.Debug & { debug: debug.Debug; default: debug.Debug }; + +export = debug; +export as namespace debug; + +declare namespace debug { + interface Debug { + (namespace: string): Debugger; + coerce: (val: any) => any; + disable: () => string; + enable: (namespaces: string) => void; + enabled: (namespaces: string) => boolean; + formatArgs: (this: Debugger, args: any[]) => void; + log: (...args: any[]) => any; + selectColor: (namespace: string) => string | number; + humanize: typeof import("ms"); + + names: string[]; + skips: string[]; + + formatters: Formatters; + + inspectOpts?: { + hideDate?: boolean | number | null; + colors?: boolean | number | null; + depth?: boolean | number | null; + showHidden?: boolean | number | null; + }; + } + + type IDebug = Debug; + + interface Formatters { + [formatter: string]: (v: any) => string; + } + + type IDebugger = Debugger; + + interface Debugger { + (formatter: any, ...args: any[]): void; + + color: string; + diff: number; + enabled: boolean; + log: (...args: any[]) => any; + namespace: string; + destroy: () => boolean; + extend: (namespace: string, delimiter?: string) => Debugger; + } +} + +```` + +### Additional Details + * Last updated: Thu, 19 Mar 2026 06:47:22 GMT + * Dependencies: [@types/ms](https://npmjs.com/package/@types/ms) + +# Credits +These definitions were written by [Seon-Wook Park](https://github.com/swook), [Gal Talmor](https://github.com/galtalmor), [John McLaughlin](https://github.com/zamb3zi), [Brasten Sager](https://github.com/brasten), [Nicolas Penin](https://github.com/npenin), [Kristian Brünn](https://github.com/kristianmitk), and [Caleb Gregory](https://github.com/calebgregory). diff --git a/tools/ui/node_modules/@types/debug/index.d.ts b/tools/ui/node_modules/@types/debug/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..38bef7b37669d83a817a72ed60f14a00c936ade2 --- /dev/null +++ b/tools/ui/node_modules/@types/debug/index.d.ts @@ -0,0 +1,50 @@ +declare var debug: debug.Debug & { debug: debug.Debug; default: debug.Debug }; + +export = debug; +export as namespace debug; + +declare namespace debug { + interface Debug { + (namespace: string): Debugger; + coerce: (val: any) => any; + disable: () => string; + enable: (namespaces: string) => void; + enabled: (namespaces: string) => boolean; + formatArgs: (this: Debugger, args: any[]) => void; + log: (...args: any[]) => any; + selectColor: (namespace: string) => string | number; + humanize: typeof import("ms"); + + names: string[]; + skips: string[]; + + formatters: Formatters; + + inspectOpts?: { + hideDate?: boolean | number | null; + colors?: boolean | number | null; + depth?: boolean | number | null; + showHidden?: boolean | number | null; + }; + } + + type IDebug = Debug; + + interface Formatters { + [formatter: string]: (v: any) => string; + } + + type IDebugger = Debugger; + + interface Debugger { + (formatter: any, ...args: any[]): void; + + color: string; + diff: number; + enabled: boolean; + log: (...args: any[]) => any; + namespace: string; + destroy: () => boolean; + extend: (namespace: string, delimiter?: string) => Debugger; + } +} diff --git a/tools/ui/node_modules/@types/debug/package.json b/tools/ui/node_modules/@types/debug/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0dacd20243330febd5232e1e6ff9d29c3092b76f --- /dev/null +++ b/tools/ui/node_modules/@types/debug/package.json @@ -0,0 +1,58 @@ +{ + "name": "@types/debug", + "version": "4.1.13", + "description": "TypeScript definitions for debug", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/debug", + "license": "MIT", + "contributors": [ + { + "name": "Seon-Wook Park", + "githubUsername": "swook", + "url": "https://github.com/swook" + }, + { + "name": "Gal Talmor", + "githubUsername": "galtalmor", + "url": "https://github.com/galtalmor" + }, + { + "name": "John McLaughlin", + "githubUsername": "zamb3zi", + "url": "https://github.com/zamb3zi" + }, + { + "name": "Brasten Sager", + "githubUsername": "brasten", + "url": "https://github.com/brasten" + }, + { + "name": "Nicolas Penin", + "githubUsername": "npenin", + "url": "https://github.com/npenin" + }, + { + "name": "Kristian Brünn", + "githubUsername": "kristianmitk", + "url": "https://github.com/kristianmitk" + }, + { + "name": "Caleb Gregory", + "githubUsername": "calebgregory", + "url": "https://github.com/calebgregory" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/debug" + }, + "scripts": {}, + "dependencies": { + "@types/ms": "*" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "1c506e100366b85350ff1c28c9cf4cc09e9a07275546bb050993c241c9821cd9", + "typeScriptVersion": "5.2" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/deep-eql/LICENSE b/tools/ui/node_modules/@types/deep-eql/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/deep-eql/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/deep-eql/README.md b/tools/ui/node_modules/@types/deep-eql/README.md new file mode 100644 index 0000000000000000000000000000000000000000..48d96fc640646ee93d86361629362e069b02d943 --- /dev/null +++ b/tools/ui/node_modules/@types/deep-eql/README.md @@ -0,0 +1,57 @@ +# Installation +> `npm install --save @types/deep-eql` + +# Summary +This package contains type definitions for deep-eql (https://github.com/chaijs/deep-eql). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/deep-eql. +## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/deep-eql/index.d.ts) +````ts +declare namespace deepEqual { + /** + * Memoization class used to speed up comparison. + */ + class MemoizeMap extends WeakMap {} + + interface DeepEqualOptions { + /** + * Override default algorithm, determining custom equality. + */ + comparator?: (leftHandOperand: T1, rightHandOperand: T2) => boolean | null; + + /** + * Provide a custom memoization object which will cache the results of + * complex objects for a speed boost. + * + * By passing `false` you can disable memoization, but this will cause circular + * references to blow the stack. + */ + memoize?: MemoizeMap | false; + } +} + +/** + * Assert deeply nested sameValue equality between two objects of any type. + * + * @param leftHandOperand + * @param rightHandOperand + * @param [options] Additional options + * @return equal match + */ +declare function deepEqual( + leftHandOperand: T1, + rightHandOperand: T2, + options?: deepEqual.DeepEqualOptions, +): boolean; + +export = deepEqual; + +```` + +### Additional Details + * Last updated: Mon, 06 Nov 2023 22:41:05 GMT + * Dependencies: none + +# Credits +These definitions were written by [Rodrigo Pietnechuk](https://github.com/ghnoob). diff --git a/tools/ui/node_modules/@types/deep-eql/index.d.ts b/tools/ui/node_modules/@types/deep-eql/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0cdbefe9301da39d735b3ea6f4a49b89fe7e3a53 --- /dev/null +++ b/tools/ui/node_modules/@types/deep-eql/index.d.ts @@ -0,0 +1,38 @@ +declare namespace deepEqual { + /** + * Memoization class used to speed up comparison. + */ + class MemoizeMap extends WeakMap {} + + interface DeepEqualOptions { + /** + * Override default algorithm, determining custom equality. + */ + comparator?: (leftHandOperand: T1, rightHandOperand: T2) => boolean | null; + + /** + * Provide a custom memoization object which will cache the results of + * complex objects for a speed boost. + * + * By passing `false` you can disable memoization, but this will cause circular + * references to blow the stack. + */ + memoize?: MemoizeMap | false; + } +} + +/** + * Assert deeply nested sameValue equality between two objects of any type. + * + * @param leftHandOperand + * @param rightHandOperand + * @param [options] Additional options + * @return equal match + */ +declare function deepEqual( + leftHandOperand: T1, + rightHandOperand: T2, + options?: deepEqual.DeepEqualOptions, +): boolean; + +export = deepEqual; diff --git a/tools/ui/node_modules/@types/deep-eql/package.json b/tools/ui/node_modules/@types/deep-eql/package.json new file mode 100644 index 0000000000000000000000000000000000000000..876158157acfa7714bd4716d9a49781d906b682a --- /dev/null +++ b/tools/ui/node_modules/@types/deep-eql/package.json @@ -0,0 +1,25 @@ +{ + "name": "@types/deep-eql", + "version": "4.0.2", + "description": "TypeScript definitions for deep-eql", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/deep-eql", + "license": "MIT", + "contributors": [ + { + "name": "Rodrigo Pietnechuk", + "githubUsername": "ghnoob", + "url": "https://github.com/ghnoob" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/deep-eql" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "3b8981ce557947fc00ca08cbd93b4206bfc0943360956867381a0a3f6b1eabf5", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/estree/LICENSE b/tools/ui/node_modules/@types/estree/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/estree/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/estree/README.md b/tools/ui/node_modules/@types/estree/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3e3e70f01583cd5430652cfa6db8f08d309d37b5 --- /dev/null +++ b/tools/ui/node_modules/@types/estree/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/estree` + +# Summary +This package contains type definitions for estree (https://github.com/estree/estree). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree. + +### Additional Details + * Last updated: Wed, 06 May 2026 21:01:00 GMT + * Dependencies: none + +# Credits +These definitions were written by [RReverser](https://github.com/RReverser). diff --git a/tools/ui/node_modules/@types/estree/flow.d.ts b/tools/ui/node_modules/@types/estree/flow.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9d001a92b55a9323e827ee90ef353df47f3c2fa0 --- /dev/null +++ b/tools/ui/node_modules/@types/estree/flow.d.ts @@ -0,0 +1,167 @@ +declare namespace ESTree { + interface FlowTypeAnnotation extends Node {} + + interface FlowBaseTypeAnnotation extends FlowTypeAnnotation {} + + interface FlowLiteralTypeAnnotation extends FlowTypeAnnotation, Literal {} + + interface FlowDeclaration extends Declaration {} + + interface AnyTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface ArrayTypeAnnotation extends FlowTypeAnnotation { + elementType: FlowTypeAnnotation; + } + + interface BooleanLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface BooleanTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface ClassImplements extends Node { + id: Identifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface ClassProperty { + key: Expression; + value?: Expression | null; + typeAnnotation?: TypeAnnotation | null; + computed: boolean; + static: boolean; + } + + interface DeclareClass extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + body: ObjectTypeAnnotation; + extends: InterfaceExtends[]; + } + + interface DeclareFunction extends FlowDeclaration { + id: Identifier; + } + + interface DeclareModule extends FlowDeclaration { + id: Literal | Identifier; + body: BlockStatement; + } + + interface DeclareVariable extends FlowDeclaration { + id: Identifier; + } + + interface FunctionTypeAnnotation extends FlowTypeAnnotation { + params: FunctionTypeParam[]; + returnType: FlowTypeAnnotation; + rest?: FunctionTypeParam | null; + typeParameters?: TypeParameterDeclaration | null; + } + + interface FunctionTypeParam { + name: Identifier; + typeAnnotation: FlowTypeAnnotation; + optional: boolean; + } + + interface GenericTypeAnnotation extends FlowTypeAnnotation { + id: Identifier | QualifiedTypeIdentifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface InterfaceExtends extends Node { + id: Identifier | QualifiedTypeIdentifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface InterfaceDeclaration extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + extends: InterfaceExtends[]; + body: ObjectTypeAnnotation; + } + + interface IntersectionTypeAnnotation extends FlowTypeAnnotation { + types: FlowTypeAnnotation[]; + } + + interface MixedTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface NullableTypeAnnotation extends FlowTypeAnnotation { + typeAnnotation: TypeAnnotation; + } + + interface NumberLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface NumberTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface StringLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface StringTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface TupleTypeAnnotation extends FlowTypeAnnotation { + types: FlowTypeAnnotation[]; + } + + interface TypeofTypeAnnotation extends FlowTypeAnnotation { + argument: FlowTypeAnnotation; + } + + interface TypeAlias extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + right: FlowTypeAnnotation; + } + + interface TypeAnnotation extends Node { + typeAnnotation: FlowTypeAnnotation; + } + + interface TypeCastExpression extends Expression { + expression: Expression; + typeAnnotation: TypeAnnotation; + } + + interface TypeParameterDeclaration extends Node { + params: Identifier[]; + } + + interface TypeParameterInstantiation extends Node { + params: FlowTypeAnnotation[]; + } + + interface ObjectTypeAnnotation extends FlowTypeAnnotation { + properties: ObjectTypeProperty[]; + indexers: ObjectTypeIndexer[]; + callProperties: ObjectTypeCallProperty[]; + } + + interface ObjectTypeCallProperty extends Node { + value: FunctionTypeAnnotation; + static: boolean; + } + + interface ObjectTypeIndexer extends Node { + id: Identifier; + key: FlowTypeAnnotation; + value: FlowTypeAnnotation; + static: boolean; + } + + interface ObjectTypeProperty extends Node { + key: Expression; + value: FlowTypeAnnotation; + optional: boolean; + static: boolean; + } + + interface QualifiedTypeIdentifier extends Node { + qualification: Identifier | QualifiedTypeIdentifier; + id: Identifier; + } + + interface UnionTypeAnnotation extends FlowTypeAnnotation { + types: FlowTypeAnnotation[]; + } + + interface VoidTypeAnnotation extends FlowBaseTypeAnnotation {} +} diff --git a/tools/ui/node_modules/@types/estree/index.d.ts b/tools/ui/node_modules/@types/estree/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d4ab36f42613e5314fec0a386ac49aa5262b172 --- /dev/null +++ b/tools/ui/node_modules/@types/estree/index.d.ts @@ -0,0 +1,694 @@ +// This definition file follows a somewhat unusual format. ESTree allows +// runtime type checks based on the `type` parameter. In order to explain this +// to typescript we want to use discriminated union types: +// https://github.com/Microsoft/TypeScript/pull/9163 +// +// For ESTree this is a bit tricky because the high level interfaces like +// Node or Function are pulling double duty. We want to pass common fields down +// to the interfaces that extend them (like Identifier or +// ArrowFunctionExpression), but you can't extend a type union or enforce +// common fields on them. So we've split the high level interfaces into two +// types, a base type which passes down inherited fields, and a type union of +// all types which extend the base type. Only the type union is exported, and +// the union is how other types refer to the collection of inheriting types. +// +// This makes the definitions file here somewhat more difficult to maintain, +// but it has the notable advantage of making ESTree much easier to use as +// an end user. + +export interface BaseNodeWithoutComments { + // Every leaf interface that extends BaseNode must specify a type property. + // The type property should be a string literal. For example, Identifier + // has: `type: "Identifier"` + type: string; + loc?: SourceLocation | null | undefined; + range?: [number, number] | undefined; +} + +export interface BaseNode extends BaseNodeWithoutComments { + leadingComments?: Comment[] | undefined; + trailingComments?: Comment[] | undefined; +} + +export interface NodeMap { + AssignmentProperty: AssignmentProperty; + CatchClause: CatchClause; + Class: Class; + ClassBody: ClassBody; + Expression: Expression; + Function: Function; + Identifier: Identifier; + Literal: Literal; + MethodDefinition: MethodDefinition; + ModuleDeclaration: ModuleDeclaration; + ModuleSpecifier: ModuleSpecifier; + Pattern: Pattern; + PrivateIdentifier: PrivateIdentifier; + Program: Program; + Property: Property; + PropertyDefinition: PropertyDefinition; + SpreadElement: SpreadElement; + Statement: Statement; + Super: Super; + SwitchCase: SwitchCase; + TemplateElement: TemplateElement; + VariableDeclarator: VariableDeclarator; +} + +export type Node = NodeMap[keyof NodeMap]; + +export interface Comment extends BaseNodeWithoutComments { + type: "Line" | "Block"; + value: string; +} + +export interface SourceLocation { + source?: string | null | undefined; + start: Position; + end: Position; +} + +export interface Position { + /** >= 1 */ + line: number; + /** >= 0 */ + column: number; +} + +export interface Program extends BaseNode { + type: "Program"; + sourceType: "script" | "module"; + body: Array; + comments?: Comment[] | undefined; +} + +export interface Directive extends BaseNode { + type: "ExpressionStatement"; + expression: Literal; + directive: string; +} + +export interface BaseFunction extends BaseNode { + params: Pattern[]; + generator?: boolean | undefined; + async?: boolean | undefined; + // The body is either BlockStatement or Expression because arrow functions + // can have a body that's either. FunctionDeclarations and + // FunctionExpressions have only BlockStatement bodies. + body: BlockStatement | Expression; +} + +export type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression; + +export type Statement = + | ExpressionStatement + | BlockStatement + | StaticBlock + | EmptyStatement + | DebuggerStatement + | WithStatement + | ReturnStatement + | LabeledStatement + | BreakStatement + | ContinueStatement + | IfStatement + | SwitchStatement + | ThrowStatement + | TryStatement + | WhileStatement + | DoWhileStatement + | ForStatement + | ForInStatement + | ForOfStatement + | Declaration; + +export interface BaseStatement extends BaseNode {} + +export interface EmptyStatement extends BaseStatement { + type: "EmptyStatement"; +} + +export interface BlockStatement extends BaseStatement { + type: "BlockStatement"; + body: Statement[]; + innerComments?: Comment[] | undefined; +} + +export interface StaticBlock extends Omit { + type: "StaticBlock"; +} + +export interface ExpressionStatement extends BaseStatement { + type: "ExpressionStatement"; + expression: Expression; +} + +export interface IfStatement extends BaseStatement { + type: "IfStatement"; + test: Expression; + consequent: Statement; + alternate?: Statement | null | undefined; +} + +export interface LabeledStatement extends BaseStatement { + type: "LabeledStatement"; + label: Identifier; + body: Statement; +} + +export interface BreakStatement extends BaseStatement { + type: "BreakStatement"; + label?: Identifier | null | undefined; +} + +export interface ContinueStatement extends BaseStatement { + type: "ContinueStatement"; + label?: Identifier | null | undefined; +} + +export interface WithStatement extends BaseStatement { + type: "WithStatement"; + object: Expression; + body: Statement; +} + +export interface SwitchStatement extends BaseStatement { + type: "SwitchStatement"; + discriminant: Expression; + cases: SwitchCase[]; +} + +export interface ReturnStatement extends BaseStatement { + type: "ReturnStatement"; + argument?: Expression | null | undefined; +} + +export interface ThrowStatement extends BaseStatement { + type: "ThrowStatement"; + argument: Expression; +} + +export interface TryStatement extends BaseStatement { + type: "TryStatement"; + block: BlockStatement; + handler?: CatchClause | null | undefined; + finalizer?: BlockStatement | null | undefined; +} + +export interface WhileStatement extends BaseStatement { + type: "WhileStatement"; + test: Expression; + body: Statement; +} + +export interface DoWhileStatement extends BaseStatement { + type: "DoWhileStatement"; + body: Statement; + test: Expression; +} + +export interface ForStatement extends BaseStatement { + type: "ForStatement"; + init?: VariableDeclaration | Expression | null | undefined; + test?: Expression | null | undefined; + update?: Expression | null | undefined; + body: Statement; +} + +export interface BaseForXStatement extends BaseStatement { + left: VariableDeclaration | Pattern; + right: Expression; + body: Statement; +} + +export interface ForInStatement extends BaseForXStatement { + type: "ForInStatement"; +} + +export interface DebuggerStatement extends BaseStatement { + type: "DebuggerStatement"; +} + +export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration; + +export interface BaseDeclaration extends BaseStatement {} + +export interface MaybeNamedFunctionDeclaration extends BaseFunction, BaseDeclaration { + type: "FunctionDeclaration"; + /** It is null when a function declaration is a part of the `export default function` statement */ + id: Identifier | null; + body: BlockStatement; +} + +export interface FunctionDeclaration extends MaybeNamedFunctionDeclaration { + id: Identifier; +} + +export interface VariableDeclaration extends BaseDeclaration { + type: "VariableDeclaration"; + declarations: VariableDeclarator[]; + kind: "var" | "let" | "const" | "using" | "await using"; +} + +export interface VariableDeclarator extends BaseNode { + type: "VariableDeclarator"; + id: Pattern; + init?: Expression | null | undefined; +} + +export interface ExpressionMap { + ArrayExpression: ArrayExpression; + ArrowFunctionExpression: ArrowFunctionExpression; + AssignmentExpression: AssignmentExpression; + AwaitExpression: AwaitExpression; + BinaryExpression: BinaryExpression; + CallExpression: CallExpression; + ChainExpression: ChainExpression; + ClassExpression: ClassExpression; + ConditionalExpression: ConditionalExpression; + FunctionExpression: FunctionExpression; + Identifier: Identifier; + ImportExpression: ImportExpression; + Literal: Literal; + LogicalExpression: LogicalExpression; + MemberExpression: MemberExpression; + MetaProperty: MetaProperty; + NewExpression: NewExpression; + ObjectExpression: ObjectExpression; + SequenceExpression: SequenceExpression; + TaggedTemplateExpression: TaggedTemplateExpression; + TemplateLiteral: TemplateLiteral; + ThisExpression: ThisExpression; + UnaryExpression: UnaryExpression; + UpdateExpression: UpdateExpression; + YieldExpression: YieldExpression; +} + +export type Expression = ExpressionMap[keyof ExpressionMap]; + +export interface BaseExpression extends BaseNode {} + +export type ChainElement = SimpleCallExpression | MemberExpression; + +export interface ChainExpression extends BaseExpression { + type: "ChainExpression"; + expression: ChainElement; +} + +export interface ThisExpression extends BaseExpression { + type: "ThisExpression"; +} + +export interface ArrayExpression extends BaseExpression { + type: "ArrayExpression"; + elements: Array; +} + +export interface ObjectExpression extends BaseExpression { + type: "ObjectExpression"; + properties: Array; +} + +export interface PrivateIdentifier extends BaseNode { + type: "PrivateIdentifier"; + name: string; +} + +export interface Property extends BaseNode { + type: "Property"; + key: Expression; + value: Expression | Pattern; // Could be an AssignmentProperty + kind: "init" | "get" | "set"; + method: boolean; + shorthand: boolean; + computed: boolean; +} + +export interface PropertyDefinition extends BaseNode { + type: "PropertyDefinition"; + key: Expression | PrivateIdentifier; + value?: Expression | null | undefined; + computed: boolean; + static: boolean; +} + +export interface FunctionExpression extends BaseFunction, BaseExpression { + id?: Identifier | null | undefined; + type: "FunctionExpression"; + body: BlockStatement; +} + +export interface SequenceExpression extends BaseExpression { + type: "SequenceExpression"; + expressions: Expression[]; +} + +export interface UnaryExpression extends BaseExpression { + type: "UnaryExpression"; + operator: UnaryOperator; + prefix: true; + argument: Expression; +} + +export interface BinaryExpression extends BaseExpression { + type: "BinaryExpression"; + operator: BinaryOperator; + left: Expression | PrivateIdentifier; + right: Expression; +} + +export interface AssignmentExpression extends BaseExpression { + type: "AssignmentExpression"; + operator: AssignmentOperator; + left: Pattern | MemberExpression; + right: Expression; +} + +export interface UpdateExpression extends BaseExpression { + type: "UpdateExpression"; + operator: UpdateOperator; + argument: Expression; + prefix: boolean; +} + +export interface LogicalExpression extends BaseExpression { + type: "LogicalExpression"; + operator: LogicalOperator; + left: Expression; + right: Expression; +} + +export interface ConditionalExpression extends BaseExpression { + type: "ConditionalExpression"; + test: Expression; + alternate: Expression; + consequent: Expression; +} + +export interface BaseCallExpression extends BaseExpression { + callee: Expression | Super; + arguments: Array; +} +export type CallExpression = SimpleCallExpression | NewExpression; + +export interface SimpleCallExpression extends BaseCallExpression { + type: "CallExpression"; + optional: boolean; +} + +export interface NewExpression extends BaseCallExpression { + type: "NewExpression"; +} + +export interface MemberExpression extends BaseExpression, BasePattern { + type: "MemberExpression"; + object: Expression | Super; + property: Expression | PrivateIdentifier; + computed: boolean; + optional: boolean; +} + +export type Pattern = Identifier | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression; + +export interface BasePattern extends BaseNode {} + +export interface SwitchCase extends BaseNode { + type: "SwitchCase"; + test?: Expression | null | undefined; + consequent: Statement[]; +} + +export interface CatchClause extends BaseNode { + type: "CatchClause"; + param: Pattern | null; + body: BlockStatement; +} + +export interface Identifier extends BaseNode, BaseExpression, BasePattern { + type: "Identifier"; + name: string; +} + +export type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral; + +export interface SimpleLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value: string | boolean | number | null; + raw?: string | undefined; +} + +export interface RegExpLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: RegExp | null | undefined; + regex: { + pattern: string; + flags: string; + }; + raw?: string | undefined; +} + +export interface BigIntLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: bigint | null | undefined; + bigint: string; + raw?: string | undefined; +} + +export type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"; + +export type BinaryOperator = + | "==" + | "!=" + | "===" + | "!==" + | "<" + | "<=" + | ">" + | ">=" + | "<<" + | ">>" + | ">>>" + | "+" + | "-" + | "*" + | "/" + | "%" + | "**" + | "|" + | "^" + | "&" + | "in" + | "instanceof"; + +export type LogicalOperator = "||" | "&&" | "??"; + +export type AssignmentOperator = + | "=" + | "+=" + | "-=" + | "*=" + | "/=" + | "%=" + | "**=" + | "<<=" + | ">>=" + | ">>>=" + | "|=" + | "^=" + | "&=" + | "||=" + | "&&=" + | "??="; + +export type UpdateOperator = "++" | "--"; + +export interface ForOfStatement extends BaseForXStatement { + type: "ForOfStatement"; + await: boolean; +} + +export interface Super extends BaseNode { + type: "Super"; +} + +export interface SpreadElement extends BaseNode { + type: "SpreadElement"; + argument: Expression; +} + +export interface ArrowFunctionExpression extends BaseExpression, BaseFunction { + type: "ArrowFunctionExpression"; + expression: boolean; + body: BlockStatement | Expression; +} + +export interface YieldExpression extends BaseExpression { + type: "YieldExpression"; + argument?: Expression | null | undefined; + delegate: boolean; +} + +export interface TemplateLiteral extends BaseExpression { + type: "TemplateLiteral"; + quasis: TemplateElement[]; + expressions: Expression[]; +} + +export interface TaggedTemplateExpression extends BaseExpression { + type: "TaggedTemplateExpression"; + tag: Expression; + quasi: TemplateLiteral; +} + +export interface TemplateElement extends BaseNode { + type: "TemplateElement"; + tail: boolean; + value: { + /** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */ + cooked?: string | null | undefined; + raw: string; + }; +} + +export interface AssignmentProperty extends Property { + value: Pattern; + kind: "init"; + method: boolean; // false +} + +export interface ObjectPattern extends BasePattern { + type: "ObjectPattern"; + properties: Array; +} + +export interface ArrayPattern extends BasePattern { + type: "ArrayPattern"; + elements: Array; +} + +export interface RestElement extends BasePattern { + type: "RestElement"; + argument: Pattern; +} + +export interface AssignmentPattern extends BasePattern { + type: "AssignmentPattern"; + left: Pattern; + right: Expression; +} + +export type Class = ClassDeclaration | ClassExpression; +export interface BaseClass extends BaseNode { + superClass?: Expression | null | undefined; + body: ClassBody; +} + +export interface ClassBody extends BaseNode { + type: "ClassBody"; + body: Array; +} + +export interface MethodDefinition extends BaseNode { + type: "MethodDefinition"; + key: Expression | PrivateIdentifier; + value: FunctionExpression; + kind: "constructor" | "method" | "get" | "set"; + computed: boolean; + static: boolean; +} + +export interface MaybeNamedClassDeclaration extends BaseClass, BaseDeclaration { + type: "ClassDeclaration"; + /** It is null when a class declaration is a part of the `export default class` statement */ + id: Identifier | null; +} + +export interface ClassDeclaration extends MaybeNamedClassDeclaration { + id: Identifier; +} + +export interface ClassExpression extends BaseClass, BaseExpression { + type: "ClassExpression"; + id?: Identifier | null | undefined; +} + +export interface MetaProperty extends BaseExpression { + type: "MetaProperty"; + meta: Identifier; + property: Identifier; +} + +export type ModuleDeclaration = + | ImportDeclaration + | ExportNamedDeclaration + | ExportDefaultDeclaration + | ExportAllDeclaration; +export interface BaseModuleDeclaration extends BaseNode {} + +export type ModuleSpecifier = ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier; +export interface BaseModuleSpecifier extends BaseNode { + local: Identifier; +} + +export interface ImportDeclaration extends BaseModuleDeclaration { + type: "ImportDeclaration"; + specifiers: Array; + attributes: ImportAttribute[]; + source: Literal; +} + +export interface ImportSpecifier extends BaseModuleSpecifier { + type: "ImportSpecifier"; + imported: Identifier | Literal; +} + +export interface ImportAttribute extends BaseNode { + type: "ImportAttribute"; + key: Identifier | Literal; + value: Literal; +} + +export interface ImportExpression extends BaseExpression { + type: "ImportExpression"; + source: Expression; + options?: Expression | null | undefined; +} + +export interface ImportDefaultSpecifier extends BaseModuleSpecifier { + type: "ImportDefaultSpecifier"; +} + +export interface ImportNamespaceSpecifier extends BaseModuleSpecifier { + type: "ImportNamespaceSpecifier"; +} + +export interface ExportNamedDeclaration extends BaseModuleDeclaration { + type: "ExportNamedDeclaration"; + declaration?: Declaration | null | undefined; + specifiers: ExportSpecifier[]; + attributes: ImportAttribute[]; + source?: Literal | null | undefined; +} + +export interface ExportSpecifier extends Omit { + type: "ExportSpecifier"; + local: Identifier | Literal; + exported: Identifier | Literal; +} + +export interface ExportDefaultDeclaration extends BaseModuleDeclaration { + type: "ExportDefaultDeclaration"; + declaration: MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression; +} + +export interface ExportAllDeclaration extends BaseModuleDeclaration { + type: "ExportAllDeclaration"; + exported: Identifier | Literal | null; + attributes: ImportAttribute[]; + source: Literal; +} + +export interface AwaitExpression extends BaseExpression { + type: "AwaitExpression"; + argument: Expression; +} diff --git a/tools/ui/node_modules/@types/estree/package.json b/tools/ui/node_modules/@types/estree/package.json new file mode 100644 index 0000000000000000000000000000000000000000..367a5d94af266a93e60d5c48d9400a948f120762 --- /dev/null +++ b/tools/ui/node_modules/@types/estree/package.json @@ -0,0 +1,27 @@ +{ + "name": "@types/estree", + "version": "1.0.9", + "description": "TypeScript definitions for estree", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree", + "license": "MIT", + "contributors": [ + { + "name": "RReverser", + "githubUsername": "RReverser", + "url": "https://github.com/RReverser" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/estree" + }, + "scripts": {}, + "dependencies": {}, + "peerDependencies": {}, + "typesPublisherContentHash": "db16da859cb0bee641414117047a4becba2e9f39d3e14a6745f887c47ef68482", + "typeScriptVersion": "5.3", + "nonNpm": true +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/geojson/LICENSE b/tools/ui/node_modules/@types/geojson/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/geojson/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/geojson/README.md b/tools/ui/node_modules/@types/geojson/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0497bc5e80a92a3f316eb152600e63b037ecb403 --- /dev/null +++ b/tools/ui/node_modules/@types/geojson/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/geojson` + +# Summary +This package contains type definitions for geojson (https://geojson.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/geojson. + +### Additional Details + * Last updated: Thu, 23 Jan 2025 18:36:51 GMT + * Dependencies: none + +# Credits +These definitions were written by [Jacob Bruun](https://github.com/cobster), [Arne Schubert](https://github.com/atd-schubert), [Jeff Jacobson](https://github.com/JeffJacobson), [Ilia Choly](https://github.com/icholy), and [Dan Vanderkam](https://github.com/danvk). diff --git a/tools/ui/node_modules/@types/geojson/index.d.ts b/tools/ui/node_modules/@types/geojson/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e964ce34894f13bdb1a7f0f7b7416ce94d1ccc10 --- /dev/null +++ b/tools/ui/node_modules/@types/geojson/index.d.ts @@ -0,0 +1,202 @@ +// Note: as of the RFC 7946 version of GeoJSON, Coordinate Reference Systems +// are no longer supported. (See https://tools.ietf.org/html/rfc7946#appendix-B)} + +export as namespace GeoJSON; + +/** + * The valid values for the "type" property of GeoJSON geometry objects. + * https://tools.ietf.org/html/rfc7946#section-1.4 + */ +export type GeoJsonGeometryTypes = Geometry["type"]; + +/** + * The value values for the "type" property of GeoJSON Objects. + * https://tools.ietf.org/html/rfc7946#section-1.4 + */ +export type GeoJsonTypes = GeoJSON["type"]; + +/** + * Bounding box + * https://tools.ietf.org/html/rfc7946#section-5 + */ +export type BBox = [number, number, number, number] | [number, number, number, number, number, number]; + +/** + * A Position is an array of coordinates. + * https://tools.ietf.org/html/rfc7946#section-3.1.1 + * Array should contain between two and three elements. + * The previous GeoJSON specification allowed more elements (e.g., which could be used to represent M values), + * but the current specification only allows X, Y, and (optionally) Z to be defined. + * + * Note: the type will not be narrowed down to `[number, number] | [number, number, number]` due to + * marginal benefits and the large impact of breaking change. + * + * See previous discussions on the type narrowing: + * - {@link https://github.com/DefinitelyTyped/DefinitelyTyped/pull/21590|Nov 2017} + * - {@link https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/67773|Dec 2023} + * - {@link https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/71441| Dec 2024} + * + * One can use a + * {@link https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates|user-defined type guard that returns a type predicate} + * to determine if a position is a 2D or 3D position. + * + * @example + * import type { Position } from 'geojson'; + * + * type StrictPosition = [x: number, y: number] | [x: number, y: number, z: number] + * + * function isStrictPosition(position: Position): position is StrictPosition { + * return position.length === 2 || position.length === 3 + * }; + * + * let position: Position = [-116.91, 45.54]; + * + * let x: number; + * let y: number; + * let z: number | undefined; + * + * if (isStrictPosition(position)) { + * // `tsc` would throw an error if we tried to destructure a fourth parameter + * [x, y, z] = position; + * } else { + * throw new TypeError("Position is not a 2D or 3D point"); + * } + */ +export type Position = number[]; + +/** + * The base GeoJSON object. + * https://tools.ietf.org/html/rfc7946#section-3 + * The GeoJSON specification also allows foreign members + * (https://tools.ietf.org/html/rfc7946#section-6.1) + * Developers should use "&" type in TypeScript or extend the interface + * to add these foreign members. + */ +export interface GeoJsonObject { + // Don't include foreign members directly into this type def. + // in order to preserve type safety. + // [key: string]: any; + /** + * Specifies the type of GeoJSON object. + */ + type: GeoJsonTypes; + /** + * Bounding box of the coordinate range of the object's Geometries, Features, or Feature Collections. + * The value of the bbox member is an array of length 2*n where n is the number of dimensions + * represented in the contained geometries, with all axes of the most southwesterly point + * followed by all axes of the more northeasterly point. + * The axes order of a bbox follows the axes order of geometries. + * https://tools.ietf.org/html/rfc7946#section-5 + */ + bbox?: BBox | undefined; +} + +/** + * Union of GeoJSON objects. + */ +export type GeoJSON = + | G + | Feature + | FeatureCollection; + +/** + * Geometry object. + * https://tools.ietf.org/html/rfc7946#section-3 + */ +export type Geometry = Point | MultiPoint | LineString | MultiLineString | Polygon | MultiPolygon | GeometryCollection; +export type GeometryObject = Geometry; + +/** + * Point geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.2 + */ +export interface Point extends GeoJsonObject { + type: "Point"; + coordinates: Position; +} + +/** + * MultiPoint geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.3 + */ +export interface MultiPoint extends GeoJsonObject { + type: "MultiPoint"; + coordinates: Position[]; +} + +/** + * LineString geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.4 + */ +export interface LineString extends GeoJsonObject { + type: "LineString"; + coordinates: Position[]; +} + +/** + * MultiLineString geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.5 + */ +export interface MultiLineString extends GeoJsonObject { + type: "MultiLineString"; + coordinates: Position[][]; +} + +/** + * Polygon geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.6 + */ +export interface Polygon extends GeoJsonObject { + type: "Polygon"; + coordinates: Position[][]; +} + +/** + * MultiPolygon geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.7 + */ +export interface MultiPolygon extends GeoJsonObject { + type: "MultiPolygon"; + coordinates: Position[][][]; +} + +/** + * Geometry Collection + * https://tools.ietf.org/html/rfc7946#section-3.1.8 + */ +export interface GeometryCollection extends GeoJsonObject { + type: "GeometryCollection"; + geometries: G[]; +} + +export type GeoJsonProperties = { [name: string]: any } | null; + +/** + * A feature object which contains a geometry and associated properties. + * https://tools.ietf.org/html/rfc7946#section-3.2 + */ +export interface Feature extends GeoJsonObject { + type: "Feature"; + /** + * The feature's geometry + */ + geometry: G; + /** + * A value that uniquely identifies this feature in a + * https://tools.ietf.org/html/rfc7946#section-3.2. + */ + id?: string | number | undefined; + /** + * Properties associated with this feature. + */ + properties: P; +} + +/** + * A collection of feature objects. + * https://tools.ietf.org/html/rfc7946#section-3.3 + */ +export interface FeatureCollection extends GeoJsonObject { + type: "FeatureCollection"; + features: Array>; +} diff --git a/tools/ui/node_modules/@types/geojson/package.json b/tools/ui/node_modules/@types/geojson/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f80ca895e94a055a783bca2ad7cea49ad4726610 --- /dev/null +++ b/tools/ui/node_modules/@types/geojson/package.json @@ -0,0 +1,46 @@ +{ + "name": "@types/geojson", + "version": "7946.0.16", + "description": "TypeScript definitions for geojson", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/geojson", + "license": "MIT", + "contributors": [ + { + "name": "Jacob Bruun", + "githubUsername": "cobster", + "url": "https://github.com/cobster" + }, + { + "name": "Arne Schubert", + "githubUsername": "atd-schubert", + "url": "https://github.com/atd-schubert" + }, + { + "name": "Jeff Jacobson", + "githubUsername": "JeffJacobson", + "url": "https://github.com/JeffJacobson" + }, + { + "name": "Ilia Choly", + "githubUsername": "icholy", + "url": "https://github.com/icholy" + }, + { + "name": "Dan Vanderkam", + "githubUsername": "danvk", + "url": "https://github.com/danvk" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/geojson" + }, + "scripts": {}, + "dependencies": {}, + "peerDependencies": {}, + "typesPublisherContentHash": "e7997f4827a9a92b60c7a6cb27e8f18fa760803e9dd021965e95604338b72e88", + "typeScriptVersion": "5.0" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/hast/LICENSE b/tools/ui/node_modules/@types/hast/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/hast/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/hast/README.md b/tools/ui/node_modules/@types/hast/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7c1e49931c7e30565dadbc6fe984d43c09e738d5 --- /dev/null +++ b/tools/ui/node_modules/@types/hast/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/hast` + +# Summary +This package contains type definitions for hast (https://github.com/syntax-tree/hast). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/hast. + +### Additional Details + * Last updated: Tue, 30 Jan 2024 21:35:45 GMT + * Dependencies: [@types/unist](https://npmjs.com/package/@types/unist) + +# Credits +These definitions were written by [lukeggchapman](https://github.com/lukeggchapman), [Junyoung Choi](https://github.com/rokt33r), [Christian Murphy](https://github.com/ChristianMurphy), and [Remco Haszing](https://github.com/remcohaszing). diff --git a/tools/ui/node_modules/@types/hast/index.d.ts b/tools/ui/node_modules/@types/hast/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..122b5b4d3684ca9647e5a5f9bf16feccfbf26c25 --- /dev/null +++ b/tools/ui/node_modules/@types/hast/index.d.ts @@ -0,0 +1,282 @@ +import type { Data as UnistData, Literal as UnistLiteral, Node as UnistNode, Parent as UnistParent } from "unist"; + +// ## Interfaces + +/** + * Info associated with hast nodes by the ecosystem. + * + * This space is guaranteed to never be specified by unist or hast. + * But you can use it in utilities and plugins to store data. + * + * This type can be augmented to register custom data. + * For example: + * + * ```ts + * declare module 'hast' { + * interface Data { + * // `someNode.data.myId` is typed as `number | undefined` + * myId?: number | undefined + * } + * } + * ``` + */ +export interface Data extends UnistData {} + +/** + * Info associated with an element. + */ +export interface Properties { + [PropertyName: string]: boolean | number | string | null | undefined | Array; +} + +// ## Content maps + +/** + * Union of registered hast nodes that can occur in {@link Element}. + * + * To register mote custom hast nodes, add them to {@link ElementContentMap}. + * They will be automatically added here. + */ +export type ElementContent = ElementContentMap[keyof ElementContentMap]; + +/** + * Registry of all hast nodes that can occur as children of {@link Element}. + * + * For a union of all {@link Element} children, see {@link ElementContent}. + */ +export interface ElementContentMap { + comment: Comment; + element: Element; + text: Text; +} + +/** + * Union of registered hast nodes that can occur in {@link Root}. + * + * To register custom hast nodes, add them to {@link RootContentMap}. + * They will be automatically added here. + */ +export type RootContent = RootContentMap[keyof RootContentMap]; + +/** + * Registry of all hast nodes that can occur as children of {@link Root}. + * + * > 👉 **Note**: {@link Root} does not need to be an entire document. + * > it can also be a fragment. + * + * For a union of all {@link Root} children, see {@link RootContent}. + */ +export interface RootContentMap { + comment: Comment; + doctype: Doctype; + element: Element; + text: Text; +} + +// ### Special content types + +/** + * Union of registered hast nodes that can occur in {@link Root}. + * + * @deprecated Use {@link RootContent} instead. + */ +export type Content = RootContent; + +/** + * Union of registered hast literals. + * + * To register custom hast nodes, add them to {@link RootContentMap} and other + * places where relevant. + * They will be automatically added here. + */ +export type Literals = Extract; + +/** + * Union of registered hast nodes. + * + * To register custom hast nodes, add them to {@link RootContentMap} and other + * places where relevant. + * They will be automatically added here. + */ +export type Nodes = Root | RootContent; + +/** + * Union of registered hast parents. + * + * To register custom hast nodes, add them to {@link RootContentMap} and other + * places where relevant. + * They will be automatically added here. + */ +export type Parents = Extract; + +// ## Abstract nodes + +/** + * Abstract hast node. + * + * This interface is supposed to be extended. + * If you can use {@link Literal} or {@link Parent}, you should. + * But for example in HTML, a `Doctype` is neither literal nor parent, but + * still a node. + * + * To register custom hast nodes, add them to {@link RootContentMap} and other + * places where relevant (such as {@link ElementContentMap}). + * + * For a union of all registered hast nodes, see {@link Nodes}. + */ +export interface Node extends UnistNode { + /** + * Info from the ecosystem. + */ + data?: Data | undefined; +} + +/** + * Abstract hast node that contains the smallest possible value. + * + * This interface is supposed to be extended if you make custom hast nodes. + * + * For a union of all registered hast literals, see {@link Literals}. + */ +export interface Literal extends Node { + /** + * Plain-text value. + */ + value: string; +} + +/** + * Abstract hast node that contains other hast nodes (*children*). + * + * This interface is supposed to be extended if you make custom hast nodes. + * + * For a union of all registered hast parents, see {@link Parents}. + */ +export interface Parent extends Node { + /** + * List of children. + */ + children: RootContent[]; +} + +// ## Concrete nodes + +/** + * HTML comment. + */ +export interface Comment extends Literal { + /** + * Node type of HTML comments in hast. + */ + type: "comment"; + /** + * Data associated with the comment. + */ + data?: CommentData | undefined; +} + +/** + * Info associated with hast comments by the ecosystem. + */ +export interface CommentData extends Data {} + +/** + * HTML document type. + */ +export interface Doctype extends UnistNode { + /** + * Node type of HTML document types in hast. + */ + type: "doctype"; + /** + * Data associated with the doctype. + */ + data?: DoctypeData | undefined; +} + +/** + * Info associated with hast doctypes by the ecosystem. + */ +export interface DoctypeData extends Data {} + +/** + * HTML element. + */ +export interface Element extends Parent { + /** + * Node type of elements. + */ + type: "element"; + /** + * Tag name (such as `'body'`) of the element. + */ + tagName: string; + /** + * Info associated with the element. + */ + properties: Properties; + /** + * Children of element. + */ + children: ElementContent[]; + /** + * When the `tagName` field is `'template'`, a `content` field can be + * present. + */ + content?: Root | undefined; + /** + * Data associated with the element. + */ + data?: ElementData | undefined; +} + +/** + * Info associated with hast elements by the ecosystem. + */ +export interface ElementData extends Data {} + +/** + * Document fragment or a whole document. + * + * Should be used as the root of a tree and must not be used as a child. + * + * Can also be used as the value for the content field on a `'template'` element. + */ +export interface Root extends Parent { + /** + * Node type of hast root. + */ + type: "root"; + /** + * Children of root. + */ + children: RootContent[]; + /** + * Data associated with the hast root. + */ + data?: RootData | undefined; +} + +/** + * Info associated with hast root nodes by the ecosystem. + */ +export interface RootData extends Data {} + +/** + * HTML character data (plain text). + */ +export interface Text extends Literal { + /** + * Node type of HTML character data (plain text) in hast. + */ + type: "text"; + /** + * Data associated with the text. + */ + data?: TextData | undefined; +} + +/** + * Info associated with hast texts by the ecosystem. + */ +export interface TextData extends Data {} diff --git a/tools/ui/node_modules/@types/hast/package.json b/tools/ui/node_modules/@types/hast/package.json new file mode 100644 index 0000000000000000000000000000000000000000..464e3f7b8866d3157344326164b027f7a0544da0 --- /dev/null +++ b/tools/ui/node_modules/@types/hast/package.json @@ -0,0 +1,42 @@ +{ + "name": "@types/hast", + "version": "3.0.4", + "description": "TypeScript definitions for hast", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/hast", + "license": "MIT", + "contributors": [ + { + "name": "lukeggchapman", + "githubUsername": "lukeggchapman", + "url": "https://github.com/lukeggchapman" + }, + { + "name": "Junyoung Choi", + "githubUsername": "rokt33r", + "url": "https://github.com/rokt33r" + }, + { + "name": "Christian Murphy", + "githubUsername": "ChristianMurphy", + "url": "https://github.com/ChristianMurphy" + }, + { + "name": "Remco Haszing", + "githubUsername": "remcohaszing", + "url": "https://github.com/remcohaszing" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/hast" + }, + "scripts": {}, + "dependencies": { + "@types/unist": "*" + }, + "typesPublisherContentHash": "3f3f73826d79157c12087f5bb36195319c6f435b9e218fa7a8de88d1cc64d097", + "typeScriptVersion": "4.6" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/json-schema/LICENSE b/tools/ui/node_modules/@types/json-schema/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/json-schema/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/json-schema/README.md b/tools/ui/node_modules/@types/json-schema/README.md new file mode 100644 index 0000000000000000000000000000000000000000..78c610f06d93954d8e0570d896be98bfb1c79cb6 --- /dev/null +++ b/tools/ui/node_modules/@types/json-schema/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/json-schema` + +# Summary +This package contains type definitions for json-schema (https://github.com/kriszyp/json-schema). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/json-schema. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 03:09:37 GMT + * Dependencies: none + +# Credits +These definitions were written by [Boris Cherny](https://github.com/bcherny), [Lucian Buzzo](https://github.com/lucianbuzzo), [Roland Groza](https://github.com/rolandjitsu), and [Jason Kwok](https://github.com/JasonHK). diff --git a/tools/ui/node_modules/@types/json-schema/index.d.ts b/tools/ui/node_modules/@types/json-schema/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9381e999b435d0c90af07362c56b65fe23036277 --- /dev/null +++ b/tools/ui/node_modules/@types/json-schema/index.d.ts @@ -0,0 +1,749 @@ +// ================================================================================================== +// JSON Schema Draft 04 +// ================================================================================================== + +/** + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1 + */ +export type JSONSchema4TypeName = + | "string" // + | "number" + | "integer" + | "boolean" + | "object" + | "array" + | "null" + | "any"; + +/** + * @see https://tools.ietf.org/html/draft-zyp-json-schema-04#section-3.5 + */ +export type JSONSchema4Type = + | string // + | number + | boolean + | JSONSchema4Object + | JSONSchema4Array + | null; + +// Workaround for infinite type recursion +export interface JSONSchema4Object { + [key: string]: JSONSchema4Type; +} + +// Workaround for infinite type recursion +// https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540 +export interface JSONSchema4Array extends Array {} + +/** + * Meta schema + * + * Recommended values: + * - 'http://json-schema.org/schema#' + * - 'http://json-schema.org/hyper-schema#' + * - 'http://json-schema.org/draft-04/schema#' + * - 'http://json-schema.org/draft-04/hyper-schema#' + * - 'http://json-schema.org/draft-03/schema#' + * - 'http://json-schema.org/draft-03/hyper-schema#' + * + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 + */ +export type JSONSchema4Version = string; + +/** + * JSON Schema V4 + * @see https://tools.ietf.org/html/draft-zyp-json-schema-04 + */ +export interface JSONSchema4 { + id?: string | undefined; + $ref?: string | undefined; + $schema?: JSONSchema4Version | undefined; + + /** + * This attribute is a string that provides a short description of the + * instance property. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.21 + */ + title?: string | undefined; + + /** + * This attribute is a string that provides a full description of the of + * purpose the instance property. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.22 + */ + description?: string | undefined; + + default?: JSONSchema4Type | undefined; + multipleOf?: number | undefined; + maximum?: number | undefined; + exclusiveMaximum?: boolean | undefined; + minimum?: number | undefined; + exclusiveMinimum?: boolean | undefined; + maxLength?: number | undefined; + minLength?: number | undefined; + pattern?: string | undefined; + + /** + * May only be defined when "items" is defined, and is a tuple of JSONSchemas. + * + * This provides a definition for additional items in an array instance + * when tuple definitions of the items is provided. This can be false + * to indicate additional items in the array are not allowed, or it can + * be a schema that defines the schema of the additional items. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.6 + */ + additionalItems?: boolean | JSONSchema4 | undefined; + + /** + * This attribute defines the allowed items in an instance array, and + * MUST be a schema or an array of schemas. The default value is an + * empty schema which allows any value for items in the instance array. + * + * When this attribute value is a schema and the instance value is an + * array, then all the items in the array MUST be valid according to the + * schema. + * + * When this attribute value is an array of schemas and the instance + * value is an array, each position in the instance array MUST conform + * to the schema in the corresponding position for this array. This + * called tuple typing. When tuple typing is used, additional items are + * allowed, disallowed, or constrained by the "additionalItems" + * (Section 5.6) attribute using the same rules as + * "additionalProperties" (Section 5.4) for objects. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.5 + */ + items?: JSONSchema4 | JSONSchema4[] | undefined; + + maxItems?: number | undefined; + minItems?: number | undefined; + uniqueItems?: boolean | undefined; + maxProperties?: number | undefined; + minProperties?: number | undefined; + + /** + * This attribute indicates if the instance must have a value, and not + * be undefined. This is false by default, making the instance + * optional. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.7 + */ + required?: boolean | string[] | undefined; + + /** + * This attribute defines a schema for all properties that are not + * explicitly defined in an object type definition. If specified, the + * value MUST be a schema or a boolean. If false is provided, no + * additional properties are allowed beyond the properties defined in + * the schema. The default value is an empty schema which allows any + * value for additional properties. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.4 + */ + additionalProperties?: boolean | JSONSchema4 | undefined; + + definitions?: { + [k: string]: JSONSchema4; + } | undefined; + + /** + * This attribute is an object with property definitions that define the + * valid values of instance object property values. When the instance + * value is an object, the property values of the instance object MUST + * conform to the property definitions in this object. In this object, + * each property definition's value MUST be a schema, and the property's + * name MUST be the name of the instance property that it defines. The + * instance property value MUST be valid according to the schema from + * the property definition. Properties are considered unordered, the + * order of the instance properties MAY be in any order. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.2 + */ + properties?: { + [k: string]: JSONSchema4; + } | undefined; + + /** + * This attribute is an object that defines the schema for a set of + * property names of an object instance. The name of each property of + * this attribute's object is a regular expression pattern in the ECMA + * 262/Perl 5 format, while the value is a schema. If the pattern + * matches the name of a property on the instance object, the value of + * the instance's property MUST be valid against the pattern name's + * schema value. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.3 + */ + patternProperties?: { + [k: string]: JSONSchema4; + } | undefined; + dependencies?: { + [k: string]: JSONSchema4 | string[]; + } | undefined; + + /** + * This provides an enumeration of all possible values that are valid + * for the instance property. This MUST be an array, and each item in + * the array represents a possible value for the instance value. If + * this attribute is defined, the instance value MUST be one of the + * values in the array in order for the schema to be valid. + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.19 + */ + enum?: JSONSchema4Type[] | undefined; + + /** + * A single type, or a union of simple types + */ + type?: JSONSchema4TypeName | JSONSchema4TypeName[] | undefined; + + allOf?: JSONSchema4[] | undefined; + anyOf?: JSONSchema4[] | undefined; + oneOf?: JSONSchema4[] | undefined; + not?: JSONSchema4 | undefined; + + /** + * The value of this property MUST be another schema which will provide + * a base schema which the current schema will inherit from. The + * inheritance rules are such that any instance that is valid according + * to the current schema MUST be valid according to the referenced + * schema. This MAY also be an array, in which case, the instance MUST + * be valid for all the schemas in the array. A schema that extends + * another schema MAY define additional attributes, constrain existing + * attributes, or add other constraints. + * + * Conceptually, the behavior of extends can be seen as validating an + * instance against all constraints in the extending schema as well as + * the extended schema(s). + * + * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.26 + */ + extends?: string | string[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-zyp-json-schema-04#section-5.6 + */ + [k: string]: any; + + format?: string | undefined; +} + +// ================================================================================================== +// JSON Schema Draft 06 +// ================================================================================================== + +export type JSONSchema6TypeName = + | "string" // + | "number" + | "integer" + | "boolean" + | "object" + | "array" + | "null" + | "any"; + +export type JSONSchema6Type = + | string // + | number + | boolean + | JSONSchema6Object + | JSONSchema6Array + | null; + +// Workaround for infinite type recursion +export interface JSONSchema6Object { + [key: string]: JSONSchema6Type; +} + +// Workaround for infinite type recursion +// https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540 +export interface JSONSchema6Array extends Array {} + +/** + * Meta schema + * + * Recommended values: + * - 'http://json-schema.org/schema#' + * - 'http://json-schema.org/hyper-schema#' + * - 'http://json-schema.org/draft-06/schema#' + * - 'http://json-schema.org/draft-06/hyper-schema#' + * + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 + */ +export type JSONSchema6Version = string; + +/** + * JSON Schema V6 + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01 + */ +export type JSONSchema6Definition = JSONSchema6 | boolean; +export interface JSONSchema6 { + $id?: string | undefined; + $ref?: string | undefined; + $schema?: JSONSchema6Version | undefined; + + /** + * Must be strictly greater than 0. + * A numeric instance is valid only if division by this keyword's value results in an integer. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.1 + */ + multipleOf?: number | undefined; + + /** + * Representing an inclusive upper limit for a numeric instance. + * This keyword validates only if the instance is less than or exactly equal to "maximum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.2 + */ + maximum?: number | undefined; + + /** + * Representing an exclusive upper limit for a numeric instance. + * This keyword validates only if the instance is strictly less than (not equal to) to "exclusiveMaximum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.3 + */ + exclusiveMaximum?: number | undefined; + + /** + * Representing an inclusive lower limit for a numeric instance. + * This keyword validates only if the instance is greater than or exactly equal to "minimum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.4 + */ + minimum?: number | undefined; + + /** + * Representing an exclusive lower limit for a numeric instance. + * This keyword validates only if the instance is strictly greater than (not equal to) to "exclusiveMinimum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.5 + */ + exclusiveMinimum?: number | undefined; + + /** + * Must be a non-negative integer. + * A string instance is valid against this keyword if its length is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.6 + */ + maxLength?: number | undefined; + + /** + * Must be a non-negative integer. + * A string instance is valid against this keyword if its length is greater than, or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.7 + */ + minLength?: number | undefined; + + /** + * Should be a valid regular expression, according to the ECMA 262 regular expression dialect. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.8 + */ + pattern?: string | undefined; + + /** + * This keyword determines how child instances validate for arrays, and does not directly validate the immediate instance itself. + * Omitting this keyword has the same behavior as an empty schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.9 + */ + items?: JSONSchema6Definition | JSONSchema6Definition[] | undefined; + + /** + * This keyword determines how child instances validate for arrays, and does not directly validate the immediate instance itself. + * If "items" is an array of schemas, validation succeeds if every instance element + * at a position greater than the size of "items" validates against "additionalItems". + * Otherwise, "additionalItems" MUST be ignored, as the "items" schema + * (possibly the default value of an empty schema) is applied to all elements. + * Omitting this keyword has the same behavior as an empty schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.10 + */ + additionalItems?: JSONSchema6Definition | undefined; + + /** + * Must be a non-negative integer. + * An array instance is valid against "maxItems" if its size is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.11 + */ + maxItems?: number | undefined; + + /** + * Must be a non-negative integer. + * An array instance is valid against "maxItems" if its size is greater than, or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.12 + */ + minItems?: number | undefined; + + /** + * If this keyword has boolean value false, the instance validates successfully. + * If it has boolean value true, the instance validates successfully if all of its elements are unique. + * Omitting this keyword has the same behavior as a value of false. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.13 + */ + uniqueItems?: boolean | undefined; + + /** + * An array instance is valid against "contains" if at least one of its elements is valid against the given schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.14 + */ + contains?: JSONSchema6Definition | undefined; + + /** + * Must be a non-negative integer. + * An object instance is valid against "maxProperties" if its number of properties is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.15 + */ + maxProperties?: number | undefined; + + /** + * Must be a non-negative integer. + * An object instance is valid against "maxProperties" if its number of properties is greater than, + * or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.16 + */ + minProperties?: number | undefined; + + /** + * Elements of this array must be unique. + * An object instance is valid against this keyword if every item in the array is the name of a property in the instance. + * Omitting this keyword has the same behavior as an empty array. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.17 + */ + required?: string[] | undefined; + + /** + * This keyword determines how child instances validate for objects, and does not directly validate the immediate instance itself. + * Validation succeeds if, for each name that appears in both the instance and as a name within this keyword's value, + * the child instance for that name successfully validates against the corresponding schema. + * Omitting this keyword has the same behavior as an empty object. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.18 + */ + properties?: { + [k: string]: JSONSchema6Definition; + } | undefined; + + /** + * This attribute is an object that defines the schema for a set of property names of an object instance. + * The name of each property of this attribute's object is a regular expression pattern in the ECMA 262, while the value is a schema. + * If the pattern matches the name of a property on the instance object, the value of the instance's property + * MUST be valid against the pattern name's schema value. + * Omitting this keyword has the same behavior as an empty object. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.19 + */ + patternProperties?: { + [k: string]: JSONSchema6Definition; + } | undefined; + + /** + * This attribute defines a schema for all properties that are not explicitly defined in an object type definition. + * If specified, the value MUST be a schema or a boolean. + * If false is provided, no additional properties are allowed beyond the properties defined in the schema. + * The default value is an empty schema which allows any value for additional properties. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.20 + */ + additionalProperties?: JSONSchema6Definition | undefined; + + /** + * This keyword specifies rules that are evaluated if the instance is an object and contains a certain property. + * Each property specifies a dependency. + * If the dependency value is an array, each element in the array must be unique. + * Omitting this keyword has the same behavior as an empty object. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.21 + */ + dependencies?: { + [k: string]: JSONSchema6Definition | string[]; + } | undefined; + + /** + * Takes a schema which validates the names of all properties rather than their values. + * Note the property name that the schema is testing will always be a string. + * Omitting this keyword has the same behavior as an empty schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.22 + */ + propertyNames?: JSONSchema6Definition | undefined; + + /** + * This provides an enumeration of all possible values that are valid + * for the instance property. This MUST be an array, and each item in + * the array represents a possible value for the instance value. If + * this attribute is defined, the instance value MUST be one of the + * values in the array in order for the schema to be valid. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.23 + */ + enum?: JSONSchema6Type[] | undefined; + + /** + * More readable form of a one-element "enum" + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.24 + */ + const?: JSONSchema6Type | undefined; + + /** + * A single type, or a union of simple types + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.25 + */ + type?: JSONSchema6TypeName | JSONSchema6TypeName[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.26 + */ + allOf?: JSONSchema6Definition[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.27 + */ + anyOf?: JSONSchema6Definition[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.28 + */ + oneOf?: JSONSchema6Definition[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.29 + */ + not?: JSONSchema6Definition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.1 + */ + definitions?: { + [k: string]: JSONSchema6Definition; + } | undefined; + + /** + * This attribute is a string that provides a short description of the instance property. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.2 + */ + title?: string | undefined; + + /** + * This attribute is a string that provides a full description of the of purpose the instance property. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.2 + */ + description?: string | undefined; + + /** + * This keyword can be used to supply a default JSON value associated with a particular schema. + * It is RECOMMENDED that a default value be valid against the associated schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.3 + */ + default?: JSONSchema6Type | undefined; + + /** + * Array of examples with no validation effect the value of "default" is usable as an example without repeating it under this keyword + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.4 + */ + examples?: JSONSchema6Type[] | undefined; + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-8 + */ + format?: string | undefined; +} + +// ================================================================================================== +// JSON Schema Draft 07 +// ================================================================================================== +// https://tools.ietf.org/html/draft-handrews-json-schema-validation-01 +// -------------------------------------------------------------------------------------------------- + +/** + * Primitive type + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1 + */ +export type JSONSchema7TypeName = + | "string" // + | "number" + | "integer" + | "boolean" + | "object" + | "array" + | "null"; + +/** + * Primitive type + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1 + */ +export type JSONSchema7Type = + | string // + | number + | boolean + | JSONSchema7Object + | JSONSchema7Array + | null; + +// Workaround for infinite type recursion +export interface JSONSchema7Object { + [key: string]: JSONSchema7Type; +} + +// Workaround for infinite type recursion +// https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540 +export interface JSONSchema7Array extends Array {} + +/** + * Meta schema + * + * Recommended values: + * - 'http://json-schema.org/schema#' + * - 'http://json-schema.org/hyper-schema#' + * - 'http://json-schema.org/draft-07/schema#' + * - 'http://json-schema.org/draft-07/hyper-schema#' + * + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 + */ +export type JSONSchema7Version = string; + +/** + * JSON Schema v7 + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01 + */ +export type JSONSchema7Definition = JSONSchema7 | boolean; +export interface JSONSchema7 { + $id?: string | undefined; + $ref?: string | undefined; + $schema?: JSONSchema7Version | undefined; + $comment?: string | undefined; + + /** + * @see https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-00#section-8.2.4 + * @see https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#appendix-A + */ + $defs?: { + [key: string]: JSONSchema7Definition; + } | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1 + */ + type?: JSONSchema7TypeName | JSONSchema7TypeName[] | undefined; + enum?: JSONSchema7Type[] | undefined; + const?: JSONSchema7Type | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.2 + */ + multipleOf?: number | undefined; + maximum?: number | undefined; + exclusiveMaximum?: number | undefined; + minimum?: number | undefined; + exclusiveMinimum?: number | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.3 + */ + maxLength?: number | undefined; + minLength?: number | undefined; + pattern?: string | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.4 + */ + items?: JSONSchema7Definition | JSONSchema7Definition[] | undefined; + additionalItems?: JSONSchema7Definition | undefined; + maxItems?: number | undefined; + minItems?: number | undefined; + uniqueItems?: boolean | undefined; + contains?: JSONSchema7Definition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5 + */ + maxProperties?: number | undefined; + minProperties?: number | undefined; + required?: string[] | undefined; + properties?: { + [key: string]: JSONSchema7Definition; + } | undefined; + patternProperties?: { + [key: string]: JSONSchema7Definition; + } | undefined; + additionalProperties?: JSONSchema7Definition | undefined; + dependencies?: { + [key: string]: JSONSchema7Definition | string[]; + } | undefined; + propertyNames?: JSONSchema7Definition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.6 + */ + if?: JSONSchema7Definition | undefined; + then?: JSONSchema7Definition | undefined; + else?: JSONSchema7Definition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.7 + */ + allOf?: JSONSchema7Definition[] | undefined; + anyOf?: JSONSchema7Definition[] | undefined; + oneOf?: JSONSchema7Definition[] | undefined; + not?: JSONSchema7Definition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-7 + */ + format?: string | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-8 + */ + contentMediaType?: string | undefined; + contentEncoding?: string | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-9 + */ + definitions?: { + [key: string]: JSONSchema7Definition; + } | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-10 + */ + title?: string | undefined; + description?: string | undefined; + default?: JSONSchema7Type | undefined; + readOnly?: boolean | undefined; + writeOnly?: boolean | undefined; + examples?: JSONSchema7Type | undefined; +} + +export interface ValidationResult { + valid: boolean; + errors: ValidationError[]; +} + +export interface ValidationError { + property: string; + message: string; +} + +/** + * To use the validator call JSONSchema.validate with an instance object and an optional schema object. + * If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating), + * that schema will be used to validate and the schema parameter is not necessary (if both exist, + * both validations will occur). + */ +export function validate(instance: {}, schema: JSONSchema4 | JSONSchema6 | JSONSchema7): ValidationResult; + +/** + * The checkPropertyChange method will check to see if an value can legally be in property with the given schema + * This is slightly different than the validate method in that it will fail if the schema is readonly and it will + * not check for self-validation, it is assumed that the passed in value is already internally valid. + */ +export function checkPropertyChange( + value: any, + schema: JSONSchema4 | JSONSchema6 | JSONSchema7, + property: string, +): ValidationResult; + +/** + * This checks to ensure that the result is valid and will throw an appropriate error message if it is not. + */ +export function mustBeValid(result: ValidationResult): void; diff --git a/tools/ui/node_modules/@types/json-schema/package.json b/tools/ui/node_modules/@types/json-schema/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3c41bd7f1e46f43c15cb95dfeaaaa6112fc91a6a --- /dev/null +++ b/tools/ui/node_modules/@types/json-schema/package.json @@ -0,0 +1,40 @@ +{ + "name": "@types/json-schema", + "version": "7.0.15", + "description": "TypeScript definitions for json-schema", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/json-schema", + "license": "MIT", + "contributors": [ + { + "name": "Boris Cherny", + "githubUsername": "bcherny", + "url": "https://github.com/bcherny" + }, + { + "name": "Lucian Buzzo", + "githubUsername": "lucianbuzzo", + "url": "https://github.com/lucianbuzzo" + }, + { + "name": "Roland Groza", + "githubUsername": "rolandjitsu", + "url": "https://github.com/rolandjitsu" + }, + { + "name": "Jason Kwok", + "githubUsername": "JasonHK", + "url": "https://github.com/JasonHK" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/json-schema" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "79984fd70cd25c3f7d72b84368778c763c89728ea0073832d745d4691b705257", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/katex/LICENSE b/tools/ui/node_modules/@types/katex/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/katex/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/katex/README.md b/tools/ui/node_modules/@types/katex/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8d95cdf20c9efe8acdc95e1f3c28bddf3c5836d4 --- /dev/null +++ b/tools/ui/node_modules/@types/katex/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/katex` + +# Summary +This package contains type definitions for katex (http://khan.github.io/KaTeX/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/katex. + +### Additional Details + * Last updated: Sat, 10 Jan 2026 00:47:09 GMT + * Dependencies: none + +# Credits +These definitions were written by [Kevin Nguyen](https://github.com/knguyen0125), [bLue](https://github.com/dreamerblue), [Sebastian Weigand](https://github.com/s-weigand), [sapphi-red](https://github.com/sapphi-red), and [Stefaans](https://github.com/Stefaans). diff --git a/tools/ui/node_modules/@types/katex/contrib/auto-render.d.ts b/tools/ui/node_modules/@types/katex/contrib/auto-render.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..86db5d3b98cc28017f6ecae80fce637c67156403 --- /dev/null +++ b/tools/ui/node_modules/@types/katex/contrib/auto-render.d.ts @@ -0,0 +1,67 @@ +import { KatexOptions } from "../index.js"; + +declare namespace renderMathInElement { + interface RenderMathInElementSpecificOptionsDelimiters { + /** + * A string which starts the math expression (i.e. the left delimiter) + */ + left: string; + /** + * A string which ends the math expression (i.e. the right delimiter) + */ + right: string; + /** + * A boolean of whether the math in the expression should be rendered in display mode or not + */ + display: boolean; + } + + interface RenderMathInElementSpecificOptions { + /** + * A list of delimiters to look for math + * + * @default [ + * {left: "$$", right: "$$", display: true}, + * {left: "\\(", right: "\\)", display: false}, + * {left: "\\[", right: "\\]", display: true} + * ] + */ + delimiters?: readonly RenderMathInElementSpecificOptionsDelimiters[] | undefined; + /** + * A list of DOM node types to ignore when recursing through + * + * @default ["script", "noscript", "style", "textarea", "pre", "code"] + */ + ignoredTags?: ReadonlyArray | undefined; + /** + * A list of DOM node class names to ignore when recursing through + * + * @default [] + */ + ignoredClasses?: string[] | undefined; + + /** + * A callback method returning a message and an error stack in case of an critical error during rendering + * @param msg Message generated by KaTeX + * @param err Caught error + * + * @default console.error + */ + errorCallback?(msg: string, err: Error): void; + } + + /** + * renderMathInElement options contain KaTeX render options and renderMathInElement specific options + */ + type RenderMathInElementOptions = KatexOptions & RenderMathInElementSpecificOptions; +} + +/** + * Auto-render TeX expressions in HTML element + * @param elem HTML element to auto-render + * @param options Render options + */ +declare function renderMathInElement(elem: HTMLElement, options?: renderMathInElement.RenderMathInElementOptions): void; + +export = renderMathInElement; +export as namespace renderMathInElement; diff --git a/tools/ui/node_modules/@types/katex/index.d.ts b/tools/ui/node_modules/@types/katex/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..59ec21f75790f921371416e5983cc15c665276e6 --- /dev/null +++ b/tools/ui/node_modules/@types/katex/index.d.ts @@ -0,0 +1,151 @@ +export interface TrustContext { + command: string; + url: string; + protocol: string; +} + +/** Documentation: https://katex.org/docs/options.html */ +export interface KatexOptions { + /** + * If `true`, math will be rendered in display mode + * (math in display style and center math on page) + * + * If `false`, math will be rendered in inline mode + * @default false + */ + displayMode?: boolean | undefined; + /** + * Determines the markup language of the output. The valid choices are: + * - `html`: Outputs KaTeX in HTML only. + * - `mathml`: Outputs KaTeX in MathML only. + * - `htmlAndMathml`: Outputs HTML for visual rendering + * and includes MathML for accessibility. + * + * @default 'htmlAndMathml' + */ + output?: "html" | "mathml" | "htmlAndMathml" | undefined; + /** + * If `true`, display math has \tags rendered on the left + * instead of the right, like \usepackage[leqno]{amsmath} in LaTeX. + * + * @default false + */ + leqno?: boolean | undefined; + /** + * If `true`, display math renders flush left with a 2em left margin, + * like \documentclass[fleqn] in LaTeX with the amsmath package. + * + * @default false + */ + fleqn?: boolean | undefined; + /** + * If `true`, KaTeX will throw a `ParseError` when + * it encounters an unsupported command or invalid LaTex + * + * If `false`, KaTeX will render unsupported commands as + * text, and render invalid LaTeX as its source code with + * hover text giving the error, in color given by errorColor + * @default true + */ + throwOnError?: boolean | undefined; + /** + * A Color string given in format `#XXX` or `#XXXXXX` + */ + errorColor?: string | undefined; + /** + * A collection of custom macros. + * + * See `src/macros.js` for its usage + */ + macros?: any; + /** + * Specifies a minimum thickness, in ems, for fraction lines, + * \sqrt top lines, {array} vertical lines, \hline, \hdashline, + * \underline, \overline, and the borders of \fbox, \boxed, and + * \fcolorbox. + */ + minRuleThickness?: number | undefined; + /** + * If `true`, `\color` will work like LaTeX's `\textcolor` + * and takes 2 arguments + * + * If `false`, `\color` will work like LaTeX's `\color` + * and takes 1 argument + * + * In both cases, `\textcolor` works as in LaTeX + * + * @default false + */ + colorIsTextColor?: boolean | undefined; + /** + * All user-specified sizes will be caped to `maxSize` ems + * + * If set to Infinity, users can make elements and space + * arbitrarily large + * + * @default Infinity + */ + maxSize?: number | undefined; + /** + * Limit the number of macro expansions to specified number + * + * If set to `Infinity`, marco expander will try to fully expand + * as in LaTex + * + * @default 1000 + */ + maxExpand?: number | undefined; + /** + * If `false` or `"ignore"`, allow features that make + * writing in LaTex convenient but not supported by LaTex + * + * If `true` or `"error"`, throw an error for such transgressions + * + * If `"warn"`, warn about behavior via `console.warn` + * + * @default "warn" + */ + strict?: boolean | string | Function | undefined; + /** + * If `false` (do not trust input), prevent any commands that could enable adverse behavior, rendering them instead in errorColor. + * + * If `true` (trust input), allow all such commands. + * + * @default false + */ + trust?: boolean | ((context: TrustContext) => boolean) | undefined; + /** + * Place KaTeX code in the global group. + * + * @default false + */ + globalGroup?: boolean | undefined; +} + +/** + * KaTeX error, usually during parsing. + */ +export class ParseError implements Error { + constructor(message: string, lexer: any, position: number); + + name: string; + message: string; + position: number; +} + +/** + * Renders a TeX expression into the specified DOM element + * @param tex A TeX expression + * @param element The DOM element to render into + * @param options KaTeX options + */ +export function render(tex: string, element: HTMLElement, options?: KatexOptions): void; + +/** + * Renders a TeX expression into an HTML string + * @param tex A TeX expression + * @param options KaTeX options + */ +export function renderToString(tex: string, options?: KatexOptions): string; + +export as namespace katex; diff --git a/tools/ui/node_modules/@types/katex/package.json b/tools/ui/node_modules/@types/katex/package.json new file mode 100644 index 0000000000000000000000000000000000000000..91a5532c6de0481fe77bacc737d11491f9365ad9 --- /dev/null +++ b/tools/ui/node_modules/@types/katex/package.json @@ -0,0 +1,46 @@ +{ + "name": "@types/katex", + "version": "0.16.8", + "description": "TypeScript definitions for katex", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/katex", + "license": "MIT", + "contributors": [ + { + "name": "Kevin Nguyen", + "githubUsername": "knguyen0125", + "url": "https://github.com/knguyen0125" + }, + { + "name": "bLue", + "githubUsername": "dreamerblue", + "url": "https://github.com/dreamerblue" + }, + { + "name": "Sebastian Weigand", + "githubUsername": "s-weigand", + "url": "https://github.com/s-weigand" + }, + { + "name": "sapphi-red", + "githubUsername": "sapphi-red", + "url": "https://github.com/sapphi-red" + }, + { + "name": "Stefaans", + "githubUsername": "Stefaans", + "url": "https://github.com/Stefaans" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/katex" + }, + "scripts": {}, + "dependencies": {}, + "peerDependencies": {}, + "typesPublisherContentHash": "843b74923cb5d38471fb372b663c3c3c10e8f5d383d24b56a11f1e3d2d122e5a", + "typeScriptVersion": "5.2" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/mdast/LICENSE b/tools/ui/node_modules/@types/mdast/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/mdast/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/mdast/README.md b/tools/ui/node_modules/@types/mdast/README.md new file mode 100644 index 0000000000000000000000000000000000000000..957d631eef8711f7c30c0b93e8cd09344e9d8242 --- /dev/null +++ b/tools/ui/node_modules/@types/mdast/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/mdast` + +# Summary +This package contains type definitions for mdast (https://github.com/syntax-tree/mdast). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mdast. + +### Additional Details + * Last updated: Tue, 14 May 2024 07:35:36 GMT + * Dependencies: [@types/unist](https://npmjs.com/package/@types/unist) + +# Credits +These definitions were written by [Christian Murphy](https://github.com/ChristianMurphy), [Jun Lu](https://github.com/lujun2), [Remco Haszing](https://github.com/remcohaszing), [Titus Wormer](https://github.com/wooorm), and [Remco Haszing](https://github.com/remcohaszing). diff --git a/tools/ui/node_modules/@types/mdast/index.d.ts b/tools/ui/node_modules/@types/mdast/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..239875d16a4ae325d8855efc40e037a33f52e353 --- /dev/null +++ b/tools/ui/node_modules/@types/mdast/index.d.ts @@ -0,0 +1,1123 @@ +import type { Data as UnistData, Literal as UnistLiteral, Node as UnistNode, Parent as UnistParent } from "unist"; + +// ## Enumeration + +/** + * How phrasing content is aligned + * ({@link https://drafts.csswg.org/css-text/ | [CSSTEXT]}). + * + * * `'left'`: See the + * {@link https://drafts.csswg.org/css-text/#valdef-text-align-left | left} + * value of the `text-align` CSS property + * * `'right'`: See the + * {@link https://drafts.csswg.org/css-text/#valdef-text-align-right | right} + * value of the `text-align` CSS property + * * `'center'`: See the + * {@link https://drafts.csswg.org/css-text/#valdef-text-align-center | center} + * value of the `text-align` CSS property + * * `null`: phrasing content is aligned as defined by the host environment + * + * Used in GFM tables. + */ +export type AlignType = "center" | "left" | "right" | null; + +/** + * Explicitness of a reference. + * + * `'shortcut'`: the reference is implicit, its identifier inferred from its + * content + * `'collapsed'`: the reference is explicit, its identifier inferred from its + * content + * `'full'`: the reference is explicit, its identifier explicitly set + */ +export type ReferenceType = "shortcut" | "collapsed" | "full"; + +// ## Mixin + +/** + * Node with a fallback. + */ +export interface Alternative { + /** + * Equivalent content for environments that cannot represent the node as + * intended. + */ + alt?: string | null | undefined; +} + +/** + * Internal relation from one node to another. + * + * Whether the value of `identifier` is expected to be a unique identifier or + * not depends on the type of node including the Association. + * An example of this is that they should be unique on {@link Definition}, + * whereas multiple {@link LinkReference}s can be non-unique to be associated + * with one definition. + */ +export interface Association { + /** + * Relation of association. + * + * `identifier` is a source value: character escapes and character + * references are not parsed. + * + * It can match another node. + * + * Its value must be normalized. + * To normalize a value, collapse markdown whitespace (`[\t\n\r ]+`) to a space, + * trim the optional initial and/or final space, and perform Unicode-aware + * case-folding. + */ + identifier: string; + + /** + * Relation of association, in parsed form. + * + * `label` is a `string` value: it works just like `title` on {@link Link} + * or a `lang` on {@link Code}: character escapes and character references + * are parsed. + * + * It can match another node. + */ + label?: string | null | undefined; +} + +/** + * Marker that is associated to another node. + */ +export interface Reference extends Association { + /** + * Explicitness of the reference. + */ + referenceType: ReferenceType; +} + +/** + * Reference to resource. + */ +export interface Resource { + /** + * URL to the referenced resource. + */ + url: string; + /** + * Advisory information for the resource, such as would be appropriate for + * a tooltip. + */ + title?: string | null | undefined; +} + +// ## Interfaces + +/** + * Info associated with mdast nodes by the ecosystem. + * + * This space is guaranteed to never be specified by unist or mdast. + * But you can use it in utilities and plugins to store data. + * + * This type can be augmented to register custom data. + * For example: + * + * ```ts + * declare module 'mdast' { + * interface Data { + * // `someNode.data.myId` is typed as `number | undefined` + * myId?: number | undefined + * } + * } + * ``` + */ +export interface Data extends UnistData {} + +// ## Content maps + +/** + * Union of registered mdast nodes that can occur where block content is + * expected. + * + * To register custom mdast nodes, add them to {@link BlockContentMap}. + * They will be automatically added here. + */ +export type BlockContent = BlockContentMap[keyof BlockContentMap]; + +/** + * Registry of all mdast nodes that can occur where {@link BlockContent} is + * expected. + * + * This interface can be augmented to register custom node types: + * + * ```ts + * declare module 'mdast' { + * interface BlockContentMap { + * // Allow using MDX ESM nodes defined by `remark-mdx`. + * mdxjsEsm: MdxjsEsm; + * } + * } + * ``` + * + * For a union of all block content, see {@link RootContent}. + */ +export interface BlockContentMap { + blockquote: Blockquote; + code: Code; + heading: Heading; + html: Html; + list: List; + paragraph: Paragraph; + table: Table; + thematicBreak: ThematicBreak; +} + +/** + * Union of registered mdast nodes that can occur where definition content is + * expected. + * + * To register custom mdast nodes, add them to {@link DefinitionContentMap}. + * They will be automatically added here. + */ +export type DefinitionContent = DefinitionContentMap[keyof DefinitionContentMap]; + +/** + * Registry of all mdast nodes that can occur where {@link DefinitionContent} + * is expected. + * + * This interface can be augmented to register custom node types: + * + * ```ts + * declare module 'mdast' { + * interface DefinitionContentMap { + * custom: Custom; + * } + * } + * ``` + * + * For a union of all definition content, see {@link RootContent}. + */ +export interface DefinitionContentMap { + definition: Definition; + footnoteDefinition: FootnoteDefinition; +} + +/** + * Union of registered mdast nodes that can occur where frontmatter content is + * expected. + * + * To register custom mdast nodes, add them to {@link FrontmatterContentMap}. + * They will be automatically added here. + */ +export type FrontmatterContent = FrontmatterContentMap[keyof FrontmatterContentMap]; + +/** + * Registry of all mdast nodes that can occur where {@link FrontmatterContent} + * is expected. + * + * This interface can be augmented to register custom node types: + * + * ```ts + * declare module 'mdast' { + * interface FrontmatterContentMap { + * // Allow using toml nodes defined by `remark-frontmatter`. + * toml: TOML; + * } + * } + * ``` + * + * For a union of all frontmatter content, see {@link RootContent}. + */ +export interface FrontmatterContentMap { + yaml: Yaml; +} + +/** + * Union of registered mdast nodes that can occur where list content is + * expected. + * + * To register custom mdast nodes, add them to {@link ListContentMap}. + * They will be automatically added here. + */ +export type ListContent = ListContentMap[keyof ListContentMap]; + +/** + * Registry of all mdast nodes that can occur where {@link ListContent} + * is expected. + * + * This interface can be augmented to register custom node types: + * + * ```ts + * declare module 'mdast' { + * interface ListContentMap { + * custom: Custom; + * } + * } + * ``` + * + * For a union of all list content, see {@link RootContent}. + */ +export interface ListContentMap { + listItem: ListItem; +} + +/** + * Union of registered mdast nodes that can occur where phrasing content is + * expected. + * + * To register custom mdast nodes, add them to {@link PhrasingContentMap}. + * They will be automatically added here. + */ +export type PhrasingContent = PhrasingContentMap[keyof PhrasingContentMap]; + +/** + * Registry of all mdast nodes that can occur where {@link PhrasingContent} + * is expected. + * + * This interface can be augmented to register custom node types: + * + * ```ts + * declare module 'mdast' { + * interface PhrasingContentMap { + * // Allow using MDX JSX (text) nodes defined by `remark-mdx`. + * mdxJsxTextElement: MDXJSXTextElement; + * } + * } + * ``` + * + * For a union of all phrasing content, see {@link RootContent}. + */ +export interface PhrasingContentMap { + break: Break; + delete: Delete; + emphasis: Emphasis; + footnoteReference: FootnoteReference; + html: Html; + image: Image; + imageReference: ImageReference; + inlineCode: InlineCode; + link: Link; + linkReference: LinkReference; + strong: Strong; + text: Text; +} + +/** + * Union of registered mdast nodes that can occur in {@link Root}. + * + * To register custom mdast nodes, add them to {@link RootContentMap}. + * They will be automatically added here. + */ +export type RootContent = RootContentMap[keyof RootContentMap]; + +/** + * Registry of all mdast nodes that can occur as children of {@link Root}. + * + * > **Note**: {@link Root} does not need to be an entire document. + * > it can also be a fragment. + * + * This interface can be augmented to register custom node types: + * + * ```ts + * declare module 'mdast' { + * interface RootContentMap { + * // Allow using toml nodes defined by `remark-frontmatter`. + * toml: TOML; + * } + * } + * ``` + * + * For a union of all {@link Root} children, see {@link RootContent}. + */ +export interface RootContentMap { + blockquote: Blockquote; + break: Break; + code: Code; + definition: Definition; + delete: Delete; + emphasis: Emphasis; + footnoteDefinition: FootnoteDefinition; + footnoteReference: FootnoteReference; + heading: Heading; + html: Html; + image: Image; + imageReference: ImageReference; + inlineCode: InlineCode; + link: Link; + linkReference: LinkReference; + list: List; + listItem: ListItem; + paragraph: Paragraph; + strong: Strong; + table: Table; + tableCell: TableCell; + tableRow: TableRow; + text: Text; + thematicBreak: ThematicBreak; + yaml: Yaml; +} + +/** + * Union of registered mdast nodes that can occur where row content is + * expected. + * + * To register custom mdast nodes, add them to {@link RowContentMap}. + * They will be automatically added here. + */ +export type RowContent = RowContentMap[keyof RowContentMap]; + +/** + * Registry of all mdast nodes that can occur where {@link RowContent} + * is expected. + * + * This interface can be augmented to register custom node types: + * + * ```ts + * declare module 'mdast' { + * interface RowContentMap { + * custom: Custom; + * } + * } + * ``` + * + * For a union of all row content, see {@link RootContent}. + */ +export interface RowContentMap { + tableCell: TableCell; +} + +/** + * Union of registered mdast nodes that can occur where table content is + * expected. + * + * To register custom mdast nodes, add them to {@link TableContentMap}. + * They will be automatically added here. + */ +export type TableContent = TableContentMap[keyof TableContentMap]; + +/** + * Registry of all mdast nodes that can occur where {@link TableContent} + * is expected. + * + * This interface can be augmented to register custom node types: + * + * ```ts + * declare module 'mdast' { + * interface TableContentMap { + * custom: Custom; + * } + * } + * ``` + * + * For a union of all table content, see {@link RootContent}. + */ +export interface TableContentMap { + tableRow: TableRow; +} + +// ### Special content types + +/** + * Union of registered mdast nodes that can occur in {@link Root}. + * + * @deprecated Use {@link RootContent} instead. + */ +export type Content = RootContent; + +/** + * Union of registered mdast literals. + * + * To register custom mdast nodes, add them to {@link RootContentMap} and other + * places where relevant. + * They will be automatically added here. + */ +export type Literals = Extract; + +/** + * Union of registered mdast nodes. + * + * To register custom mdast nodes, add them to {@link RootContentMap} and other + * places where relevant. + * They will be automatically added here. + */ +export type Nodes = Root | RootContent; + +/** + * Union of registered mdast parents. + * + * To register custom mdast nodes, add them to {@link RootContentMap} and other + * places where relevant. + * They will be automatically added here. + */ +export type Parents = Extract; + +/** + * Union of registered mdast nodes that can occur at the top of the document. + * + * To register custom mdast nodes, add them to {@link BlockContent}, + * {@link FrontmatterContent}, or {@link DefinitionContent}. + * They will be automatically added here. + */ +export type TopLevelContent = BlockContent | FrontmatterContent | DefinitionContent; + +// ## Abstract nodes + +/** + * Abstract mdast node that contains the smallest possible value. + * + * This interface is supposed to be extended if you make custom mdast nodes. + * + * For a union of all registered mdast literals, see {@link Literals}. + */ +export interface Literal extends Node { + /** + * Plain-text value. + */ + value: string; +} + +/** + * Abstract mdast node. + * + * This interface is supposed to be extended. + * If you can use {@link Literal} or {@link Parent}, you should. + * But for example in markdown, a thematic break (`***`) is neither literal nor + * parent, but still a node. + * + * To register custom mdast nodes, add them to {@link RootContentMap} and other + * places where relevant (such as {@link ElementContentMap}). + * + * For a union of all registered mdast nodes, see {@link Nodes}. + */ +export interface Node extends UnistNode { + /** + * Info from the ecosystem. + */ + data?: Data | undefined; +} + +/** + * Abstract mdast node that contains other mdast nodes (*children*). + * + * This interface is supposed to be extended if you make custom mdast nodes. + * + * For a union of all registered mdast parents, see {@link Parents}. + */ +export interface Parent extends Node { + /** + * List of children. + */ + children: RootContent[]; +} + +// ## Concrete nodes + +/** + * Markdown block quote. + */ +export interface Blockquote extends Parent { + /** + * Node type of mdast block quote. + */ + type: "blockquote"; + /** + * Children of block quote. + */ + children: Array; + /** + * Data associated with the mdast block quote. + */ + data?: BlockquoteData | undefined; +} + +/** + * Info associated with mdast block quote nodes by the ecosystem. + */ +export interface BlockquoteData extends Data {} + +/** + * Markdown break. + */ +export interface Break extends Node { + /** + * Node type of mdast break. + */ + type: "break"; + /** + * Data associated with the mdast break. + */ + data?: BreakData | undefined; +} + +/** + * Info associated with mdast break nodes by the ecosystem. + */ +export interface BreakData extends Data {} + +/** + * Markdown code (flow) (block). + */ +export interface Code extends Literal { + /** + * Node type of mdast code (flow). + */ + type: "code"; + /** + * Language of computer code being marked up. + */ + lang?: string | null | undefined; + /** + * Custom information relating to the node. + * + * If the lang field is present, a meta field can be present. + */ + meta?: string | null | undefined; + /** + * Data associated with the mdast code (flow). + */ + data?: CodeData | undefined; +} + +/** + * Info associated with mdast code (flow) (block) nodes by the ecosystem. + */ +export interface CodeData extends Data {} + +/** + * Markdown definition. + */ +export interface Definition extends Node, Association, Resource { + /** + * Node type of mdast definition. + */ + type: "definition"; + /** + * Data associated with the mdast definition. + */ + data?: DefinitionData | undefined; +} + +/** + * Info associated with mdast definition nodes by the ecosystem. + */ +export interface DefinitionData extends Data {} + +/** + * Markdown GFM delete (strikethrough). + */ +export interface Delete extends Parent { + /** + * Node type of mdast GFM delete. + */ + type: "delete"; + /** + * Children of GFM delete. + */ + children: PhrasingContent[]; + /** + * Data associated with the mdast GFM delete. + */ + data?: DeleteData | undefined; +} + +/** + * Info associated with mdast GFM delete nodes by the ecosystem. + */ +export interface DeleteData extends Data {} + +/** + * Markdown emphasis. + */ +export interface Emphasis extends Parent { + /** + * Node type of mdast emphasis. + */ + type: "emphasis"; + /** + * Children of emphasis. + */ + children: PhrasingContent[]; + /** + * Data associated with the mdast emphasis. + */ + data?: EmphasisData | undefined; +} + +/** + * Info associated with mdast emphasis nodes by the ecosystem. + */ +export interface EmphasisData extends Data {} + +/** + * Markdown GFM footnote definition. + */ +export interface FootnoteDefinition extends Parent, Association { + /** + * Node type of mdast GFM footnote definition. + */ + type: "footnoteDefinition"; + /** + * Children of GFM footnote definition. + */ + children: Array; + /** + * Data associated with the mdast GFM footnote definition. + */ + data?: FootnoteDefinitionData | undefined; +} + +/** + * Info associated with mdast GFM footnote definition nodes by the ecosystem. + */ +export interface FootnoteDefinitionData extends Data {} + +/** + * Markdown GFM footnote reference. + */ +export interface FootnoteReference extends Association, Node { + /** + * Node type of mdast GFM footnote reference. + */ + type: "footnoteReference"; + /** + * Data associated with the mdast GFM footnote reference. + */ + data?: FootnoteReferenceData | undefined; +} + +/** + * Info associated with mdast GFM footnote reference nodes by the ecosystem. + */ +export interface FootnoteReferenceData extends Data {} + +/** + * Markdown heading. + */ +export interface Heading extends Parent { + /** + * Node type of mdast heading. + */ + type: "heading"; + /** + * Heading rank. + * + * A value of `1` is said to be the highest rank and `6` the lowest. + */ + depth: 1 | 2 | 3 | 4 | 5 | 6; + /** + * Children of heading. + */ + children: PhrasingContent[]; + /** + * Data associated with the mdast heading. + */ + data?: HeadingData | undefined; +} + +/** + * Info associated with mdast heading nodes by the ecosystem. + */ +export interface HeadingData extends Data {} + +/** + * Markdown HTML. + */ +export interface Html extends Literal { + /** + * Node type of mdast HTML. + */ + type: "html"; + /** + * Data associated with the mdast HTML. + */ + data?: HtmlData | undefined; +} + +/** + * Info associated with mdast HTML nodes by the ecosystem. + */ +export interface HtmlData extends Data {} + +/** + * Old name of `Html` node. + * + * @deprecated + * Please use `Html` instead. + */ +export type HTML = Html; + +/** + * Markdown image. + */ +export interface Image extends Alternative, Node, Resource { + /** + * Node type of mdast image. + */ + type: "image"; + /** + * Data associated with the mdast image. + */ + data?: ImageData | undefined; +} + +/** + * Info associated with mdast image nodes by the ecosystem. + */ +export interface ImageData extends Data {} + +/** + * Markdown image reference. + */ +export interface ImageReference extends Alternative, Node, Reference { + /** + * Node type of mdast image reference. + */ + type: "imageReference"; + /** + * Data associated with the mdast image reference. + */ + data?: ImageReferenceData | undefined; +} + +/** + * Info associated with mdast image reference nodes by the ecosystem. + */ +export interface ImageReferenceData extends Data {} + +/** + * Markdown code (text) (inline). + */ +export interface InlineCode extends Literal { + /** + * Node type of mdast code (text). + */ + type: "inlineCode"; + /** + * Data associated with the mdast code (text). + */ + data?: InlineCodeData | undefined; +} + +/** + * Info associated with mdast code (text) (inline) nodes by the ecosystem. + */ +export interface InlineCodeData extends Data {} + +/** + * Markdown link. + */ +export interface Link extends Parent, Resource { + /** + * Node type of mdast link. + */ + type: "link"; + /** + * Children of link. + */ + children: PhrasingContent[]; + /** + * Data associated with the mdast link. + */ + data?: LinkData | undefined; +} + +/** + * Info associated with mdast link nodes by the ecosystem. + */ +export interface LinkData extends Data {} + +/** + * Markdown link reference. + */ +export interface LinkReference extends Parent, Reference { + /** + * Node type of mdast link reference. + */ + type: "linkReference"; + /** + * Children of link reference. + */ + children: PhrasingContent[]; + /** + * Data associated with the mdast link reference. + */ + data?: LinkReferenceData | undefined; +} + +/** + * Info associated with mdast link reference nodes by the ecosystem. + */ +export interface LinkReferenceData extends Data {} + +/** + * Markdown list. + */ +export interface List extends Parent { + /** + * Node type of mdast list. + */ + type: "list"; + /** + * Whether the items have been intentionally ordered (when `true`), or that + * the order of items is not important (when `false` or not present). + */ + ordered?: boolean | null | undefined; + /** + * The starting number of the list, when the `ordered` field is `true`. + */ + start?: number | null | undefined; + /** + * Whether one or more of the children are separated with a blank line from + * its siblings (when `true`), or not (when `false` or not present). + */ + spread?: boolean | null | undefined; + /** + * Children of list. + */ + children: ListContent[]; + /** + * Data associated with the mdast list. + */ + data?: ListData | undefined; +} + +/** + * Info associated with mdast list nodes by the ecosystem. + */ +export interface ListData extends Data {} + +/** + * Markdown list item. + */ +export interface ListItem extends Parent { + /** + * Node type of mdast list item. + */ + type: "listItem"; + /** + * Whether the item is a tasklist item (when `boolean`). + * + * When `true`, the item is complete. + * When `false`, the item is incomplete. + */ + checked?: boolean | null | undefined; + /** + * Whether one or more of the children are separated with a blank line from + * its siblings (when `true`), or not (when `false` or not present). + */ + spread?: boolean | null | undefined; + /** + * Children of list item. + */ + children: Array; + /** + * Data associated with the mdast list item. + */ + data?: ListItemData | undefined; +} + +/** + * Info associated with mdast list item nodes by the ecosystem. + */ +export interface ListItemData extends Data {} + +/** + * Markdown paragraph. + */ +export interface Paragraph extends Parent { + /** + * Node type of mdast paragraph. + */ + type: "paragraph"; + /** + * Children of paragraph. + */ + children: PhrasingContent[]; + /** + * Data associated with the mdast paragraph. + */ + data?: ParagraphData | undefined; +} + +/** + * Info associated with mdast paragraph nodes by the ecosystem. + */ +export interface ParagraphData extends Data {} + +/** + * Document fragment or a whole document. + * + * Should be used as the root of a tree and must not be used as a child. + */ +export interface Root extends Parent { + /** + * Node type of mdast root. + */ + type: "root"; + /** + * Data associated with the mdast root. + */ + data?: RootData | undefined; +} + +/** + * Info associated with mdast root nodes by the ecosystem. + */ +export interface RootData extends Data {} + +/** + * Markdown strong. + */ +export interface Strong extends Parent { + /** + * Node type of mdast strong. + */ + type: "strong"; + /** + * Children of strong. + */ + children: PhrasingContent[]; + /** + * Data associated with the mdast strong. + */ + data?: StrongData | undefined; +} + +/** + * Info associated with mdast strong nodes by the ecosystem. + */ +export interface StrongData extends Data {} + +/** + * Markdown GFM table. + */ +export interface Table extends Parent { + /** + * Node type of mdast GFM table. + */ + type: "table"; + /** + * How cells in columns are aligned. + */ + align?: AlignType[] | null | undefined; + /** + * Children of GFM table. + */ + children: TableContent[]; + /** + * Data associated with the mdast GFM table. + */ + data?: TableData | undefined; +} + +/** + * Info associated with mdast GFM table nodes by the ecosystem. + */ +export interface TableData extends Data {} + +/** + * Markdown GFM table row. + */ +export interface TableRow extends Parent { + /** + * Node type of mdast GFM table row. + */ + type: "tableRow"; + /** + * Children of GFM table row. + */ + children: RowContent[]; + /** + * Data associated with the mdast GFM table row. + */ + data?: TableRowData | undefined; +} + +/** + * Info associated with mdast GFM table row nodes by the ecosystem. + */ +export interface TableRowData extends Data {} + +/** + * Markdown GFM table cell. + */ +export interface TableCell extends Parent { + /** + * Node type of mdast GFM table cell. + */ + type: "tableCell"; + /** + * Children of GFM table cell. + */ + children: PhrasingContent[]; + /** + * Data associated with the mdast GFM table cell. + */ + data?: TableCellData | undefined; +} + +/** + * Info associated with mdast GFM table cell nodes by the ecosystem. + */ +export interface TableCellData extends Data {} + +/** + * Markdown text. + */ +export interface Text extends Literal { + /** + * Node type of mdast text. + */ + type: "text"; + /** + * Data associated with the mdast text. + */ + data?: TextData | undefined; +} + +/** + * Info associated with mdast text nodes by the ecosystem. + */ +export interface TextData extends Data {} + +/** + * Markdown thematic break (horizontal rule). + */ +export interface ThematicBreak extends Node { + /** + * Node type of mdast thematic break. + */ + type: "thematicBreak"; + /** + * Data associated with the mdast thematic break. + */ + data?: ThematicBreakData | undefined; +} + +/** + * Info associated with mdast thematic break nodes by the ecosystem. + */ +export interface ThematicBreakData extends Data {} + +/** + * Markdown YAML. + */ +export interface Yaml extends Literal { + /** + * Node type of mdast YAML. + */ + type: "yaml"; + /** + * Data associated with the mdast YAML. + */ + data?: YamlData | undefined; +} + +/** + * Info associated with mdast YAML nodes by the ecosystem. + */ +export interface YamlData extends Data {} + +/** + * Old name of `Yaml` node. + * + * @deprecated + * Please use `Yaml` instead. + */ +export type YAML = Yaml; diff --git a/tools/ui/node_modules/@types/mdast/package.json b/tools/ui/node_modules/@types/mdast/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d37b05a6e9eda2ed01db1cd0aa09bd9e578b5131 --- /dev/null +++ b/tools/ui/node_modules/@types/mdast/package.json @@ -0,0 +1,47 @@ +{ + "name": "@types/mdast", + "version": "4.0.4", + "description": "TypeScript definitions for mdast", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mdast", + "license": "MIT", + "contributors": [ + { + "name": "Christian Murphy", + "githubUsername": "ChristianMurphy", + "url": "https://github.com/ChristianMurphy" + }, + { + "name": "Jun Lu", + "githubUsername": "lujun2", + "url": "https://github.com/lujun2" + }, + { + "name": "Remco Haszing", + "githubUsername": "remcohaszing", + "url": "https://github.com/remcohaszing" + }, + { + "name": "Titus Wormer", + "githubUsername": "wooorm", + "url": "https://github.com/wooorm" + }, + { + "name": "Remco Haszing", + "githubUsername": "remcohaszing", + "url": "https://github.com/remcohaszing" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/mdast" + }, + "scripts": {}, + "dependencies": { + "@types/unist": "*" + }, + "typesPublisherContentHash": "1599d3ca45533e9d9248231c90843306b49c07fe13ad94ebf7345da44d8fd4bd", + "typeScriptVersion": "4.7" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/mdx/LICENSE b/tools/ui/node_modules/@types/mdx/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/mdx/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/mdx/README.md b/tools/ui/node_modules/@types/mdx/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e118967a73ed43a1a2f9663a36c5a61d370068bd --- /dev/null +++ b/tools/ui/node_modules/@types/mdx/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/mdx` + +# Summary +This package contains type definitions for mdx (https://github.com/mdx-js/mdx). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mdx. + +### Additional Details + * Last updated: Thu, 11 Apr 2024 15:07:22 GMT + * Dependencies: none + +# Credits +These definitions were written by [Christian Murphy](https://github.com/ChristianMurphy), [Remco Haszing](https://github.com/remcohaszing), and [Titus Wormer](https://github.com/wooorm). diff --git a/tools/ui/node_modules/@types/mdx/index.d.ts b/tools/ui/node_modules/@types/mdx/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..113a0201475d50d0823aad883a36003c4a54ac0a --- /dev/null +++ b/tools/ui/node_modules/@types/mdx/index.d.ts @@ -0,0 +1,117 @@ +/** + * An MDX file which exports a JSX component. + * + * The default export of MDX files is a function which takes props and returns a JSX element. + * MDX files can export other identifiers from within the MDX file as well, either authored manually + * or automatically through plugins + * + * It’s currently not possible for the other exports to be typed automatically. + * You can type them yourself with a TypeScript + * [script](https://www.typescriptlang.org/docs/handbook/2/modules.html#non-modules) + * which augments `*.mdx` modules. + * A script file is a file which doesn’t use top-level ESM syntax, but ESM syntax + * is allowed inside the declared module. + * + * This is typically useful for exports created by plugins. For example: + * + * ```ts + * // mdx-custom.d.ts + * declare module '*.mdx' { + * import { Frontmatter } from 'my-frontmatter-types'; + * + * export const frontmatter: Frontmatter; + * export const title: string; + * } + * ``` + * + * The previous example added types to *all* `.mdx` files. + * To define types for a specific MDX file, create a file with the same name but postfixed with + * `.d.ts` next to the MDX file. + * + * For example, given the following MDX file `my-component.mdx`: + * + * ```mdx + * export const message = 'world'; + * + * # Hello {message} + * ``` + * + * Create the following file named `my-component.mdx.d.ts` in the same directory: + * + * ```ts + * export { default } from '*.mdx'; + * + * export const message: string; + * ``` + * + * Note that this overwrites the `declare module '*.mdx' { … }` types from earlier, which is why you + * also need to define the default export. You can also define your own default export type to narrow + * the accepted prop types of this specific file. + * + * It should now be possible to import both the MDX component and the exported constant `message`. + */ +declare module "*.mdx" { + // eslint-disable-next-line @definitelytyped/no-self-import + import { Element, MDXProps } from "mdx/types"; + + /** + * An function component which renders the MDX content using JSX. + * + * @param props This value is be available as the named variable `props` inside the MDX component. + * @returns A JSX element. The meaning of this may depend on the project configuration. I.e. it + * could be a React, Preact, or Vuex element. + */ + export default function MDXContent(props: MDXProps): Element; +} + +// Support markdown extensions from +// https://github.com/sindresorhus/markdown-extensions/blob/v1.1.1/markdown-extensions.json + +/** + * A markdown file which exports a JSX component. + */ +declare module "*.md" { + export { default } from "*.mdx"; +} + +/** + * A markdown file which exports a JSX component. + */ +declare module "*.markdown" { + export { default } from "*.mdx"; +} + +/** + * A markdown file which exports a JSX component. + */ +declare module "*.mdown" { + export { default } from "*.mdx"; +} + +/** + * A markdown file which exports a JSX component. + */ +declare module "*.mkdn" { + export { default } from "*.mdx"; +} + +/** + * A markdown file which exports a JSX component. + */ +declare module "*.mkd" { + export { default } from "*.mdx"; +} + +/** + * A markdown file which exports a JSX component. + */ +declare module "*.mkdown" { + export { default } from "*.mdx"; +} + +/** + * A markdown file which exports a JSX component. + */ +declare module "*.ron" { + export { default } from "*.mdx"; +} diff --git a/tools/ui/node_modules/@types/mdx/package.json b/tools/ui/node_modules/@types/mdx/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e434d963c042cdd9ef380076d97f94e7609acc48 --- /dev/null +++ b/tools/ui/node_modules/@types/mdx/package.json @@ -0,0 +1,35 @@ +{ + "name": "@types/mdx", + "version": "2.0.13", + "description": "TypeScript definitions for mdx", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mdx", + "license": "MIT", + "contributors": [ + { + "name": "Christian Murphy", + "githubUsername": "ChristianMurphy", + "url": "https://github.com/ChristianMurphy" + }, + { + "name": "Remco Haszing", + "githubUsername": "remcohaszing", + "url": "https://github.com/remcohaszing" + }, + { + "name": "Titus Wormer", + "githubUsername": "wooorm", + "url": "https://github.com/wooorm" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/mdx" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "e9930b09508f8573e534a6a2fb0c41a3f791f073d8596be495dc6e47b788c530", + "typeScriptVersion": "4.7" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/mdx/types.d.ts b/tools/ui/node_modules/@types/mdx/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..498bb694de2e6a62f14d3fe998dc538aff920fc6 --- /dev/null +++ b/tools/ui/node_modules/@types/mdx/types.d.ts @@ -0,0 +1,119 @@ +// Internal helper types + +/** + * This is the global JSX.ElementType if it’s defined, otherwise never. + */ +// @ts-ignore JSX runtimes may optionally define JSX.ElementType. The MDX types need to work regardless whether this is +// defined or not. +type ElementType = any extends JSX.ElementType ? never : JSX.ElementType; + +/** + * This matches any function component types that ar part of `ElementType`. + */ +type FunctionElementType = Extract) => any>; + +/** + * This matches any class component types that ar part of `ElementType`. + */ +type ClassElementType = Extract) => any>; + +/** + * A valid JSX string component. + */ +type StringComponent = Extract; + +/** + * A JSX element returned by MDX content. + */ +export type Element = JSX.Element; + +/** + * A valid JSX function component. + */ +type FunctionComponent = ElementType extends never + // If JSX.ElementType isn’t defined, the valid return type is JSX.Element + ? (props: Props) => Element | null + : FunctionElementType extends never + // If JSX.ElementType is defined, but doesn’t allow function components, function components are disallowed. + ? never + // If JSX.ElementType allows function components, its return value determines what is a valid. + : (props: Props) => ReturnType; + +/** + * A valid JSX class component. + */ +type ClassComponent = ElementType extends never + // If JSX.ElementType isn’t defined, the valid return type is a constructor that returns JSX.ElementClass + ? new(props: Props) => JSX.ElementClass + : ClassElementType extends never + // If JSX.ElementType is defined, but doesn’t allow constructors, function components are disallowed. + ? never + // If JSX.ElementType allows class components, its return value determines what is a valid. + : new(props: Props) => InstanceType; + +/** + * Any allowed JSX component. + */ +type Component = FunctionComponent | ClassComponent | StringComponent; + +interface NestedMDXComponents { + [key: string]: NestedMDXComponents | Component; +} + +// Public MDX helper types + +/** + * MDX components may be passed as the `components`. + * + * The key is the name of the element to override. The value is the component to render instead. + */ +export type MDXComponents = + & NestedMDXComponents + & { + [Key in StringComponent]?: Component; + } + & { + /** + * If a wrapper component is defined, the MDX content will be wrapped inside of it. + */ + wrapper?: Component; + }; + +/** + * The props that may be passed to an MDX component. + */ +export interface MDXProps { + /** + * Which props exactly may be passed into the component depends on the contents of the MDX + * file. + */ + [key: string]: unknown; + + /** + * This prop may be used to customize how certain components are rendered. + */ + components?: MDXComponents; +} + +/** + * The type of the default export of an MDX module. + */ +export type MDXContent = (props: MDXProps) => Element; + +/** + * A generic MDX module type. + */ +export interface MDXModule { + /** + * This could be any value that is exported from the MDX file. + */ + [key: string]: unknown; + + /** + * A functional JSX component which renders the content of the MDX file. + */ + default: MDXContent; +} + +// This marks the file as a module, meaning not all types are implicitly exported. +export {}; diff --git a/tools/ui/node_modules/@types/ms/LICENSE b/tools/ui/node_modules/@types/ms/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/ms/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/ms/README.md b/tools/ui/node_modules/@types/ms/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1152869e50f686578f1c0b13d36502a0c29118fd --- /dev/null +++ b/tools/ui/node_modules/@types/ms/README.md @@ -0,0 +1,82 @@ +# Installation +> `npm install --save @types/ms` + +# Summary +This package contains type definitions for ms (https://github.com/vercel/ms). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/ms. +## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/ms/index.d.ts) +````ts +/** + * Short/Long format for `value`. + * + * @param {Number} value + * @param {{long: boolean}} options + * @return {String} + */ +declare function ms(value: number, options?: { long: boolean }): string; + +/** + * Parse the given `value` and return milliseconds. + * + * @param {ms.StringValue} value + * @return {Number} + */ +declare function ms(value: ms.StringValue): number; + +declare namespace ms { + // Unit, UnitAnyCase, and StringValue are backported from ms@3 + // https://github.com/vercel/ms/blob/8b5923d1d86c84a9f6aba8022d416dcf2361aa8d/src/index.ts + + type Unit = + | "Years" + | "Year" + | "Yrs" + | "Yr" + | "Y" + | "Weeks" + | "Week" + | "W" + | "Days" + | "Day" + | "D" + | "Hours" + | "Hour" + | "Hrs" + | "Hr" + | "H" + | "Minutes" + | "Minute" + | "Mins" + | "Min" + | "M" + | "Seconds" + | "Second" + | "Secs" + | "Sec" + | "s" + | "Milliseconds" + | "Millisecond" + | "Msecs" + | "Msec" + | "Ms"; + + type UnitAnyCase = Unit | Uppercase | Lowercase; + + type StringValue = + | `${number}` + | `${number}${UnitAnyCase}` + | `${number} ${UnitAnyCase}`; +} + +export = ms; + +```` + +### Additional Details + * Last updated: Thu, 16 Jan 2025 21:02:45 GMT + * Dependencies: none + +# Credits +These definitions were written by [Zhiyuan Wang](https://github.com/danny8002). diff --git a/tools/ui/node_modules/@types/ms/index.d.ts b/tools/ui/node_modules/@types/ms/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b1b1f5159ae710182edb36ebcf4e032f23ffe681 --- /dev/null +++ b/tools/ui/node_modules/@types/ms/index.d.ts @@ -0,0 +1,63 @@ +/** + * Short/Long format for `value`. + * + * @param {Number} value + * @param {{long: boolean}} options + * @return {String} + */ +declare function ms(value: number, options?: { long: boolean }): string; + +/** + * Parse the given `value` and return milliseconds. + * + * @param {ms.StringValue} value + * @return {Number} + */ +declare function ms(value: ms.StringValue): number; + +declare namespace ms { + // Unit, UnitAnyCase, and StringValue are backported from ms@3 + // https://github.com/vercel/ms/blob/8b5923d1d86c84a9f6aba8022d416dcf2361aa8d/src/index.ts + + type Unit = + | "Years" + | "Year" + | "Yrs" + | "Yr" + | "Y" + | "Weeks" + | "Week" + | "W" + | "Days" + | "Day" + | "D" + | "Hours" + | "Hour" + | "Hrs" + | "Hr" + | "H" + | "Minutes" + | "Minute" + | "Mins" + | "Min" + | "M" + | "Seconds" + | "Second" + | "Secs" + | "Sec" + | "s" + | "Milliseconds" + | "Millisecond" + | "Msecs" + | "Msec" + | "Ms"; + + type UnitAnyCase = Unit | Uppercase | Lowercase; + + type StringValue = + | `${number}` + | `${number}${UnitAnyCase}` + | `${number} ${UnitAnyCase}`; +} + +export = ms; diff --git a/tools/ui/node_modules/@types/ms/package.json b/tools/ui/node_modules/@types/ms/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0f547d02ca9104713c050bd9d4332520089be0a2 --- /dev/null +++ b/tools/ui/node_modules/@types/ms/package.json @@ -0,0 +1,26 @@ +{ + "name": "@types/ms", + "version": "2.1.0", + "description": "TypeScript definitions for ms", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/ms", + "license": "MIT", + "contributors": [ + { + "name": "Zhiyuan Wang", + "githubUsername": "danny8002", + "url": "https://github.com/danny8002" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/ms" + }, + "scripts": {}, + "dependencies": {}, + "peerDependencies": {}, + "typesPublisherContentHash": "2c8651ce1714fdc6bcbc0f262c93a790f1d127fb1c2dc8edbb583decef56fd39", + "typeScriptVersion": "5.0" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/node/LICENSE b/tools/ui/node_modules/@types/node/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/tools/ui/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/tools/ui/node_modules/@types/node/README.md b/tools/ui/node_modules/@types/node/README.md new file mode 100644 index 0000000000000000000000000000000000000000..985f3ac41107bbe70d84b44a0c70f8e41d02ff98 --- /dev/null +++ b/tools/ui/node_modules/@types/node/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for node (https://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node/v24. + +### Additional Details + * Last updated: Thu, 04 Jun 2026 07:01:48 GMT + * Dependencies: [undici-types](https://npmjs.com/package/undici-types) + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [David Junger](https://github.com/touffy), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Sebastian Silbermann](https://github.com/eps1lon), [Wilco Bakker](https://github.com/WilcoBakker), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), [Dmitry Semigradsky](https://github.com/Semigradsky), [René](https://github.com/Renegade334), and [Yagiz Nizipli](https://github.com/anonrig). diff --git a/tools/ui/node_modules/@types/node/assert.d.ts b/tools/ui/node_modules/@types/node/assert.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cd6d6df9ff33d4291585ffedd0a8619c9e98afdb --- /dev/null +++ b/tools/ui/node_modules/@types/node/assert.d.ts @@ -0,0 +1,1115 @@ +/** + * The `node:assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/assert.js) + */ +declare module "assert" { + import strict = require("assert/strict"); + /** + * An alias of {@link assert.ok}. + * @since v0.5.9 + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + const kOptions: unique symbol; + namespace assert { + type AssertMethodNames = + | "deepEqual" + | "deepStrictEqual" + | "doesNotMatch" + | "doesNotReject" + | "doesNotThrow" + | "equal" + | "fail" + | "ifError" + | "match" + | "notDeepEqual" + | "notDeepStrictEqual" + | "notEqual" + | "notStrictEqual" + | "ok" + | "partialDeepStrictEqual" + | "rejects" + | "strictEqual" + | "throws"; + interface AssertOptions { + /** + * If set to `'full'`, shows the full diff in assertion errors. + * @default 'simple' + */ + diff?: "simple" | "full" | undefined; + /** + * If set to `true`, non-strict methods behave like their + * corresponding strict methods. + * @default true + */ + strict?: boolean | undefined; + /** + * If set to `true`, skips prototype and constructor + * comparison in deep equality checks. + * @since v24.9.0 + * @default false + */ + skipPrototype?: boolean | undefined; + } + interface Assert extends Pick { + readonly [kOptions]: AssertOptions & { strict: false }; + } + interface AssertStrict extends Pick { + readonly [kOptions]: AssertOptions & { strict: true }; + } + /** + * The `Assert` class allows creating independent assertion instances with custom options. + * @since v24.6.0 + */ + var Assert: { + /** + * Creates a new assertion instance. The `diff` option controls the verbosity of diffs in assertion error messages. + * + * ```js + * const { Assert } = require('node:assert'); + * const assertInstance = new Assert({ diff: 'full' }); + * assertInstance.deepStrictEqual({ a: 1 }, { a: 2 }); + * // Shows a full diff in the error message. + * ``` + * + * **Important**: When destructuring assertion methods from an `Assert` instance, + * the methods lose their connection to the instance's configuration options (such + * as `diff`, `strict`, and `skipPrototype` settings). + * The destructured methods will fall back to default behavior instead. + * + * ```js + * const myAssert = new Assert({ diff: 'full' }); + * + * // This works as expected - uses 'full' diff + * myAssert.strictEqual({ a: 1 }, { b: { c: 1 } }); + * + * // This loses the 'full' diff setting - falls back to default 'simple' diff + * const { strictEqual } = myAssert; + * strictEqual({ a: 1 }, { b: { c: 1 } }); + * ``` + * + * The `skipPrototype` option affects all deep equality methods: + * + * ```js + * class Foo { + * constructor(a) { + * this.a = a; + * } + * } + * + * class Bar { + * constructor(a) { + * this.a = a; + * } + * } + * + * const foo = new Foo(1); + * const bar = new Bar(1); + * + * // Default behavior - fails due to different constructors + * const assert1 = new Assert(); + * assert1.deepStrictEqual(foo, bar); // AssertionError + * + * // Skip prototype comparison - passes if properties are equal + * const assert2 = new Assert({ skipPrototype: true }); + * assert2.deepStrictEqual(foo, bar); // OK + * ``` + * + * When destructured, methods lose access to the instance's `this` context and revert to default assertion behavior + * (diff: 'simple', non-strict mode). + * To maintain custom options when using destructured methods, avoid + * destructuring and call methods directly on the instance. + * @since v24.6.0 + */ + new( + options?: AssertOptions & { strict?: true | undefined }, + ): AssertStrict; + new( + options: AssertOptions, + ): Assert; + }; + interface AssertionErrorOptions { + /** + * If provided, the error message is set to this value. + */ + message?: string | undefined; + /** + * The `actual` property on the error instance. + */ + actual?: unknown; + /** + * The `expected` property on the error instance. + */ + expected?: unknown; + /** + * The `operator` property on the error instance. + */ + operator?: string | undefined; + /** + * If provided, the generated stack trace omits frames before this function. + */ + stackStartFn?: Function | undefined; + /** + * If set to `'full'`, shows the full diff in assertion errors. + * @default 'simple' + */ + diff?: "simple" | "full" | undefined; + } + /** + * Indicates the failure of an assertion. All errors thrown by the `node:assert` module will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + constructor(options: AssertionErrorOptions); + /** + * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. + */ + actual: unknown; + /** + * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. + */ + expected: unknown; + /** + * Indicates if the message was auto-generated (`true`) or not. + */ + generatedMessage: boolean; + /** + * Value is always `ERR_ASSERTION` to show that the error is an assertion error. + */ + code: "ERR_ASSERTION"; + /** + * Set to the passed in operator value. + */ + operator: string; + } + /** + * This feature is deprecated and will be removed in a future version. + * Please consider using alternatives such as the `mock` helper function. + * @since v14.2.0, v12.19.0 + * @deprecated Deprecated + */ + class CallTracker { + /** + * The wrapper function is expected to be called exactly `exact` times. If the + * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an + * error. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func); + * ``` + * @since v14.2.0, v12.19.0 + * @param [fn='A no-op function'] + * @param [exact=1] + * @return A function that wraps `fn`. + */ + calls(exact?: number): () => void; + calls(fn: undefined, exact?: number): () => void; + calls any>(fn: Func, exact?: number): Func; + calls any>(fn?: Func, exact?: number): Func | (() => void); + /** + * Example: + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * callsfunc(1, 2, 3); + * + * assert.deepStrictEqual(tracker.getCalls(callsfunc), + * [{ thisArg: undefined, arguments: [1, 2, 3] }]); + * ``` + * @since v18.8.0, v16.18.0 + * @return An array with all the calls to a tracked function. + */ + getCalls(fn: Function): CallTrackerCall[]; + /** + * The arrays contains information about the expected and actual number of calls of + * the functions that have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * // Returns an array containing information on callsfunc() + * console.log(tracker.report()); + * // [ + * // { + * // message: 'Expected the func function to be executed 2 time(s) but was + * // executed 0 time(s).', + * // actual: 0, + * // expected: 2, + * // operator: 'func', + * // stack: stack trace + * // } + * // ] + * ``` + * @since v14.2.0, v12.19.0 + * @return An array of objects containing information about the wrapper functions returned by {@link tracker.calls()}. + */ + report(): CallTrackerReportInformation[]; + /** + * Reset calls of the call tracker. If a tracked function is passed as an argument, the calls will be reset for it. + * If no arguments are passed, all tracked functions will be reset. + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * + * callsfunc(); + * // Tracker was called once + * assert.strictEqual(tracker.getCalls(callsfunc).length, 1); + * + * tracker.reset(callsfunc); + * assert.strictEqual(tracker.getCalls(callsfunc).length, 0); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn a tracked function to reset. + */ + reset(fn?: Function): void; + /** + * Iterates through the list of functions passed to {@link tracker.calls()} and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * callsfunc(); + * + * // Will throw an error since callsfunc() was only called once. + * tracker.verify(); + * ``` + * @since v14.2.0, v12.19.0 + */ + verify(): void; + } + interface CallTrackerCall { + thisArg: object; + arguments: unknown[]; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + type AssertPredicate = RegExp | (new() => object) | ((thrown: unknown) => boolean) | object | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * + * Using `assert.fail()` with more than two arguments is possible but deprecated. + * See below for further details. + * @since v0.1.21 + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: unknown, + expected: unknown, + message?: string | Error, + operator?: string, + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + stackStartFn?: Function, + ): never; + /** + * Tests if `value` is truthy. It is equivalent to `assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is `undefined`, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * // Using `assert()` works the same: + * assert(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(0) + * ``` + * @since v0.1.21 + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled + * and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is + * specially handled and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default error + * message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + * @since v0.1.21 + */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'node:assert'; + * + * const obj1 = { + * a: { + * b: 1, + * }, + * }; + * const obj2 = { + * a: { + * b: 2, + * }, + * }; + * const obj3 = { + * a: { + * b: 1, + * }, + * }; + * const obj4 = { __proto__: obj1 }; + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + * @since v1.2.0 + */ + function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v1.2.0 + */ + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the `AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'node:assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text', + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text', + * }, + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * }, + * ); + * + * // Using regular expressions to validate error properties: + * assert.throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text', + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i, + * }, + * ); + * + * // Fails due to the different `message` and `name` properties: + * assert.throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err, + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error, + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/, + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error', + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an `ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'node:assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + * @since v0.1.21 + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn` function. + * + * If an error is thrown and it is the same type as that specified by the `error` parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError, + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message` parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops', + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + * @since v0.1.21 + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for `ifError()` itself. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + * @since v0.1.97 + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v24.x/api/errors.html#err_invalid_return_value) + * error. In both cases the error handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and `name` properties. + * + * If specified, `message` will be the message provided by the `{@link AssertionError}` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error, + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second argument, then `error` is assumed to + * be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second argument gets considered. + * @since v10.0.0 + */ + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v24.x/api/errors.html#err_invalid_return_value) error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject( + block: (() => Promise) | Promise, + message?: string | Error, + ): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function match(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Tests for partial deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. "Partial" equality means + * that only properties that exist on the `expected` parameter are going to be + * compared. + * + * This method always passes the same test cases as `assert.deepStrictEqual()`, + * behaving as a super set of it. + * @since v22.13.0 + */ + function partialDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + } + namespace assert { + export { strict }; + } + export = assert; +} +declare module "node:assert" { + import assert = require("assert"); + export = assert; +} diff --git a/tools/ui/node_modules/@types/node/assert/strict.d.ts b/tools/ui/node_modules/@types/node/assert/strict.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ed7395a6bc76a40bdf26f2905a217bdd464fac4 --- /dev/null +++ b/tools/ui/node_modules/@types/node/assert/strict.d.ts @@ -0,0 +1,111 @@ +/** + * In strict assertion mode, non-strict methods behave like their corresponding + * strict methods. For example, `assert.deepEqual()` will behave like + * `assert.deepStrictEqual()`. + * + * In strict assertion mode, error messages for objects display a diff. In legacy + * assertion mode, error messages for objects display the objects, often truncated. + * + * To use strict assertion mode: + * + * ```js + * import { strict as assert } from 'node:assert'; + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * ``` + * + * Example error diff: + * + * ```js + * import { strict as assert } from 'node:assert'; + * + * assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); + * // AssertionError: Expected inputs to be strictly deep-equal: + * // + actual - expected ... Lines skipped + * // + * // [ + * // [ + * // ... + * // 2, + * // + 3 + * // - '3' + * // ], + * // ... + * // 5 + * // ] + * ``` + * + * To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS` + * environment variables. This will also deactivate the colors in the REPL. For + * more on color support in terminal environments, read the tty + * [`getColorDepth()`](https://nodejs.org/docs/latest-v24.x/api/tty.html#writestreamgetcolordepthenv) documentation. + * @since v15.0.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/assert/strict.js) + */ +declare module "assert/strict" { + import { + Assert, + AssertionError, + AssertionErrorOptions, + AssertOptions, + AssertPredicate, + AssertStrict, + CallTracker, + CallTrackerCall, + CallTrackerReportInformation, + deepStrictEqual, + doesNotMatch, + doesNotReject, + doesNotThrow, + fail, + ifError, + match, + notDeepStrictEqual, + notStrictEqual, + ok, + partialDeepStrictEqual, + rejects, + strictEqual, + throws, + } from "node:assert"; + function strict(value: unknown, message?: string | Error): asserts value; + namespace strict { + export { + Assert, + AssertionError, + AssertionErrorOptions, + AssertOptions, + AssertPredicate, + AssertStrict, + CallTracker, + CallTrackerCall, + CallTrackerReportInformation, + deepStrictEqual, + deepStrictEqual as deepEqual, + doesNotMatch, + doesNotReject, + doesNotThrow, + fail, + ifError, + match, + notDeepStrictEqual, + notDeepStrictEqual as notDeepEqual, + notStrictEqual, + notStrictEqual as notEqual, + ok, + partialDeepStrictEqual, + rejects, + strict, + strictEqual, + strictEqual as equal, + throws, + }; + } + export = strict; +} +declare module "node:assert/strict" { + import strict = require("assert/strict"); + export = strict; +} diff --git a/tools/ui/node_modules/@types/node/async_hooks.d.ts b/tools/ui/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2377689f865bf238b24201284c843f21ccc321cf --- /dev/null +++ b/tools/ui/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,623 @@ +/** + * We strongly discourage the use of the `async_hooks` API. + * Other APIs that can cover most of its use cases include: + * + * * [`AsyncLocalStorage`](https://nodejs.org/docs/latest-v24.x/api/async_context.html#class-asynclocalstorage) tracks async context + * * [`process.getActiveResourcesInfo()`](https://nodejs.org/docs/latest-v24.x/api/process.html#processgetactiveresourcesinfo) tracks active resources + * + * The `node:async_hooks` module provides an API to track asynchronous resources. + * It can be accessed using: + * + * ```js + * import async_hooks from 'node:async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/async_hooks.js) + */ +declare module "async_hooks" { + /** + * ```js + * import { executionAsyncId } from 'node:async_hooks'; + * import fs from 'node:fs'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * const path = '.'; + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on [promise execution tracking](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#promise-execution-tracking). + * @since v8.1.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'node:fs'; + * import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'node:http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook, + * } from 'node:async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * }, + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v13.9.0, v12.17.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on [promise execution tracking](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#promise-execution-tracking). + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId A unique ID for the async resource + * @param type The type of the async resource + * @param triggerAsyncId The unique ID of the async resource in whose execution context this async resource was created + * @param resource Reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + /** + * Called immediately after the callback specified in `before` is completed. + * + * If an uncaught exception occurs during execution of the callback, then `after` will run after the `'uncaughtException'` event is emitted or a `domain`'s handler runs. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * + * ```js + * import { createHook } from 'node:async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { }, + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * @since v8.1.0 + * @param callbacks The `Hook Callbacks` to register + * @return Instance used for disabling and enabling hooks + */ + function createHook(callbacks: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'node:async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since v9.3.0) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg, + ): Func; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>(fn: Func): Func; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v9.6.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope( + fn: (this: This, ...args: any[]) => Result, + thisArg?: This, + ...args: any[] + ): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + interface AsyncLocalStorageOptions { + /** + * The default value to be used when no store is provided. + */ + defaultValue?: any; + /** + * A name for the `AsyncLocalStorage` value. + */ + name?: string | undefined; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `node:async_hooks` module, `AsyncLocalStorage` should be preferred as it is a performant and memory + * safe implementation that involves significant optimizations that are non-obvious + * to implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'node:http'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 0: finish + * // 1: start + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other's data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * Creates a new instance of `AsyncLocalStorage`. Store is only provided within a + * `run()` call or after an `enterWith()` call. + */ + constructor(options?: AsyncLocalStorageOptions); + /** + * Binds the given function to the current execution context. + * @since v19.8.0 + * @param fn The function to bind to the current execution context. + * @return A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func; + /** + * Captures the current execution context and returns a function that accepts a + * function as an argument. Whenever the returned function is called, it + * calls the function passed to it within the captured context. + * + * ```js + * const asyncLocalStorage = new AsyncLocalStorage(); + * const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); + * const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); + * console.log(result); // returns 123 + * ``` + * + * AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple + * async context tracking purposes, for example: + * + * ```js + * class Foo { + * #runInAsyncScope = AsyncLocalStorage.snapshot(); + * + * get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } + * } + * + * const foo = asyncLocalStorage.run(123, () => new Foo()); + * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 + * ``` + * @since v19.8.0 + * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. + */ + static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R; + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the `asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v13.10.0, v12.17.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v13.10.0, v12.17.0 + */ + getStore(): T | undefined; + /** + * The name of the `AsyncLocalStorage` instance if provided. + * @since v24.0.0 + */ + readonly name: string; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function. + * The store is accessible to any asynchronous operations created within the + * callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * setTimeout(() => { + * asyncLocalStorage.getStore(); // Returns the store object + * }, 200); + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + */ + run(store: T, callback: () => R): R; + run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()` call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + * @experimental + */ + exit(callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why `run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v13.11.0, v12.17.0 + * @experimental + */ + enterWith(store: T): void; + } + /** + * @since v17.2.0, v16.14.0 + * @return A map of provider types to the corresponding numeric id. + * This map contains all the event types that might be emitted by the `async_hooks.init()` event. + */ + namespace asyncWrapProviders { + const NONE: number; + const DIRHANDLE: number; + const DNSCHANNEL: number; + const ELDHISTOGRAM: number; + const FILEHANDLE: number; + const FILEHANDLECLOSEREQ: number; + const FIXEDSIZEBLOBCOPY: number; + const FSEVENTWRAP: number; + const FSREQCALLBACK: number; + const FSREQPROMISE: number; + const GETADDRINFOREQWRAP: number; + const GETNAMEINFOREQWRAP: number; + const HEAPSNAPSHOT: number; + const HTTP2SESSION: number; + const HTTP2STREAM: number; + const HTTP2PING: number; + const HTTP2SETTINGS: number; + const HTTPINCOMINGMESSAGE: number; + const HTTPCLIENTREQUEST: number; + const JSSTREAM: number; + const JSUDPWRAP: number; + const MESSAGEPORT: number; + const PIPECONNECTWRAP: number; + const PIPESERVERWRAP: number; + const PIPEWRAP: number; + const PROCESSWRAP: number; + const PROMISE: number; + const QUERYWRAP: number; + const SHUTDOWNWRAP: number; + const SIGNALWRAP: number; + const STATWATCHER: number; + const STREAMPIPE: number; + const TCPCONNECTWRAP: number; + const TCPSERVERWRAP: number; + const TCPWRAP: number; + const TTYWRAP: number; + const UDPSENDWRAP: number; + const UDPWRAP: number; + const SIGINTWATCHDOG: number; + const WORKER: number; + const WORKERHEAPSNAPSHOT: number; + const WRITEWRAP: number; + const ZLIB: number; + const CHECKPRIMEREQUEST: number; + const PBKDF2REQUEST: number; + const KEYPAIRGENREQUEST: number; + const KEYGENREQUEST: number; + const KEYEXPORTREQUEST: number; + const CIPHERREQUEST: number; + const DERIVEBITSREQUEST: number; + const HASHREQUEST: number; + const RANDOMBYTESREQUEST: number; + const RANDOMPRIMEREQUEST: number; + const SCRYPTREQUEST: number; + const SIGNREQUEST: number; + const TLSWRAP: number; + const VERIFYREQUEST: number; + } +} +declare module "node:async_hooks" { + export * from "async_hooks"; +} diff --git a/tools/ui/node_modules/@types/node/buffer.buffer.d.ts b/tools/ui/node_modules/@types/node/buffer.buffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8823deeb4b67547f4694a5055f399ef045909246 --- /dev/null +++ b/tools/ui/node_modules/@types/node/buffer.buffer.d.ts @@ -0,0 +1,472 @@ +declare module "buffer" { + type ImplicitArrayBuffer> = T extends + { valueOf(): infer V extends ArrayBufferLike } ? V : T; + global { + interface BufferConstructor { + // see buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: ArrayLike): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: TArrayBuffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an + * `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use + * `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal + * `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(array: WithImplicitCoercion>): Buffer; + /** + * This creates a view of the `ArrayBuffer` without copying the underlying + * memory. For example, when passed a reference to the `.buffer` property of a + * `TypedArray` instance, the newly created `Buffer` will share the same + * allocated memory as the `TypedArray`'s underlying `ArrayBuffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arr = new Uint16Array(2); + * + * arr[0] = 5000; + * arr[1] = 4000; + * + * // Shares memory with `arr`. + * const buf = Buffer.from(arr.buffer); + * + * console.log(buf); + * // Prints: + * + * // Changing the original Uint16Array changes the Buffer also. + * arr[1] = 6000; + * + * console.log(buf); + * // Prints: + * ``` + * + * The optional `byteOffset` and `length` arguments specify a memory range within + * the `arrayBuffer` that will be shared by the `Buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const ab = new ArrayBuffer(10); + * const buf = Buffer.from(ab, 0, 2); + * + * console.log(buf.length); + * // Prints: 2 + * ``` + * + * A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a + * `SharedArrayBuffer` or another type appropriate for `Buffer.from()` + * variants. + * + * It is important to remember that a backing `ArrayBuffer` can cover a range + * of memory that extends beyond the bounds of a `TypedArray` view. A new + * `Buffer` created using the `buffer` property of a `TypedArray` may extend + * beyond the range of the `TypedArray`: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements + * const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements + * console.log(arrA.buffer === arrB.buffer); // true + * + * const buf = Buffer.from(arrB.buffer); + * console.log(buf); + * // Prints: + * ``` + * @since v5.10.0 + * @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the + * `.buffer` property of a `TypedArray`. + * @param byteOffset Index of first byte to expose. **Default:** `0`. + * @param length Number of bytes to expose. **Default:** + * `arrayBuffer.byteLength - byteOffset`. + */ + from>( + arrayBuffer: TArrayBuffer, + byteOffset?: number, + length?: number, + ): Buffer>; + /** + * Creates a new `Buffer` containing `string`. The `encoding` parameter identifies + * the character encoding to be used when converting `string` into bytes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('this is a tést'); + * const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); + * + * console.log(buf1.toString()); + * // Prints: this is a tést + * console.log(buf2.toString()); + * // Prints: this is a tést + * console.log(buf1.toString('latin1')); + * // Prints: this is a tést + * ``` + * + * A `TypeError` will be thrown if `string` is not a string or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(string)` may also use the internal `Buffer` pool like + * `Buffer.allocUnsafe()` does. + * @since v5.10.0 + * @param string A string to encode. + * @param encoding The encoding of `string`. **Default:** `'utf8'`. + */ + from(string: WithImplicitCoercion, encoding?: BufferEncoding): Buffer; + from(arrayOrString: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. If the combined length of the `Buffer`s in `list` is + * less than `totalLength`, the remaining space is filled with zeros. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=0] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + } + interface Buffer extends Uint8Array { + // see buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + } + // TODO: remove globals in future version + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedBuffer = Buffer; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type AllowSharedBuffer = Buffer; + } + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + var SlowBuffer: { + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + new(size: number): Buffer; + prototype: Buffer; + }; +} diff --git a/tools/ui/node_modules/@types/node/buffer.d.ts b/tools/ui/node_modules/@types/node/buffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9a62ccf97737d66a8e78a83d09fc08ee27de5337 --- /dev/null +++ b/tools/ui/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,1934 @@ +// If lib.dom.d.ts or lib.webworker.d.ts is loaded, then use the global types. +// Otherwise, use the types from node. +type _Blob = typeof globalThis extends { onmessage: any; Blob: any } ? {} : import("buffer").Blob; +type _File = typeof globalThis extends { onmessage: any; File: any } ? {} : import("buffer").File; + +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/buffer.js) + */ +declare module "buffer" { + import { BinaryLike } from "node:crypto"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + /** + * This function returns `true` if `input` contains only valid UTF-8-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.4.0, v18.14.0 + * @param input The input to validate. + */ + export function isUtf8(input: ArrayBuffer | NodeJS.TypedArray): boolean; + /** + * This function returns `true` if `input` contains only valid ASCII-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.6.0, v18.15.0 + * @param input The input to validate. + */ + export function isAscii(input: ArrayBuffer | NodeJS.TypedArray): boolean; + export let INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + export type TranscodeEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "latin1" + | "binary"; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`, `'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'node:buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ + export function transcode( + source: Uint8Array, + fromEnc: TranscodeEncoding, + toEnc: TranscodeEncoding, + ): NonSharedBuffer; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { type AllowSharedBuffer, Buffer, type NonSharedBuffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts + * will be converted to the platform native line-ending as specified by `import { EOL } from 'node:os'`. + */ + endings?: "transparent" | "native"; + /** + * The Blob content-type. The intent is for `type` to convey + * the MIME media type of the data, however no validation of the type format + * is performed. + */ + type?: string | undefined; + } + /** + * A `Blob` encapsulates immutable, raw data that can be safely shared across + * multiple worker threads. + * @since v15.7.0, v14.18.0 + */ + export class Blob { + /** + * The total size of the `Blob` in bytes. + * @since v15.7.0, v14.18.0 + */ + readonly size: number; + /** + * The content-type of the `Blob`. + * @since v15.7.0, v14.18.0 + */ + readonly type: string; + /** + * Creates a new `Blob` object containing a concatenation of the given sources. + * + * {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into + * the 'Blob' and can therefore be safely modified after the 'Blob' is created. + * + * String sources are also copied into the `Blob`. + */ + constructor(sources: Array, options?: BlobOptions); + /** + * Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of + * the `Blob` data. + * @since v15.7.0, v14.18.0 + */ + arrayBuffer(): Promise; + /** + * The `blob.bytes()` method returns the byte of the `Blob` object as a `Promise`. + * + * ```js + * const blob = new Blob(['hello']); + * blob.bytes().then((bytes) => { + * console.log(bytes); // Outputs: Uint8Array(5) [ 104, 101, 108, 108, 111 ] + * }); + * ``` + */ + bytes(): Promise; + /** + * Creates and returns a new `Blob` containing a subset of this `Blob` objects + * data. The original `Blob` is not altered. + * @since v15.7.0, v14.18.0 + * @param start The starting index. + * @param end The ending index. + * @param type The content-type for the new `Blob` + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * Returns a promise that fulfills with the contents of the `Blob` decoded as a + * UTF-8 string. + * @since v15.7.0, v14.18.0 + */ + text(): Promise; + /** + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): WebReadableStream; + } + export interface FileOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be + * converted to the platform native line-ending as specified by `import { EOL } from 'node:os'`. + */ + endings?: "native" | "transparent"; + /** The File content-type. */ + type?: string; + /** The last modified date of the file. `Default`: Date.now(). */ + lastModified?: number; + } + /** + * A [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) provides information about files. + * @since v19.2.0, v18.13.0 + */ + export class File extends Blob { + constructor(sources: Array, fileName: string, options?: FileOptions); + /** + * The name of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly name: string; + /** + * The last modified date of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly lastModified: number; + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + export type WithImplicitCoercion = + | T + | { valueOf(): T } + | (T extends string ? { [Symbol.toPrimitive](hint: "string"): T } : never); + global { + namespace NodeJS { + export { BufferEncoding }; + } + // Buffer class + type BufferEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + // see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later + // see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier + + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * Buffer.isBuffer(Buffer.alloc(10)); // true + * Buffer.isBuffer(Buffer.from('foo')); // true + * Buffer.isBuffer('a string'); // false + * Buffer.isBuffer([]); // false + * Buffer.isBuffer(new Uint8Array(1024)); // false + * ``` + * @since v0.1.101 + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` is the name of a supported character encoding, + * or `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * console.log(Buffer.isEncoding('utf8')); + * // Prints: true + * + * console.log(Buffer.isEncoding('hex')); + * // Prints: true + * + * console.log(Buffer.isEncoding('utf/8')); + * // Prints: false + * + * console.log(Buffer.isEncoding('')); + * // Prints: false + * ``` + * @since v0.9.1 + * @param encoding A character encoding name to check. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Returns the byte length of a string when encoded using `encoding`. + * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account + * for the encoding that is used to convert the string into bytes. + * + * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. + * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the + * return value might be greater than the length of a `Buffer` created from the + * string. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const str = '\u00bd + \u00bc = \u00be'; + * + * console.log(`${str}: ${str.length} characters, ` + + * `${Buffer.byteLength(str, 'utf8')} bytes`); + * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes + * ``` + * + * When `string` is a + * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- + * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- + * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + * @since v0.1.90 + * @param string A value to calculate the length of. + * @param [encoding='utf8'] If `string` is a string, this is its encoding. + * @return The number of bytes contained within `string`. + */ + byteLength( + string: string | NodeJS.ArrayBufferView | ArrayBufferLike, + encoding?: BufferEncoding, + ): number; + /** + * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of `Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('1234'); + * const buf2 = Buffer.from('0123'); + * const arr = [buf1, buf2]; + * + * console.log(arr.sort(Buffer.compare)); + * // Prints: [ , ] + * // (This result is equal to: [buf2, buf1].) + * ``` + * @since v0.11.13 + * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. + */ + compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; + /** + * This is the size (in bytes) of pre-allocated internal `Buffer` instances used + * for pooling. This value may be modified. + * @since v0.11.3 + */ + poolSize: number; + } + interface Buffer { + // see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later + // see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier + + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: "Buffer"; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd` arguments can be used to limit the comparison to specific ranges within `target` and `buf` respectively. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`, `targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare( + target: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number, + ): -1 | 0 | 1; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntLE + * @since v14.9.0, v12.19.0 + */ + writeUintLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntBE + * @since v14.9.0, v12.19.0 + */ + writeUintBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + readBigUint64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + readBigUint64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntLE + * @since v14.9.0, v12.19.0 + */ + readUintLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntBE + * @since v14.9.0, v12.19.0 + */ + readUintBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * @alias Buffer.readUInt8 + * @since v14.9.0, v12.19.0 + */ + readUint8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * @alias Buffer.readUInt16LE + * @since v14.9.0, v12.19.0 + */ + readUint16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * @alias Buffer.readUInt16BE + * @since v14.9.0, v12.19.0 + */ + readUint16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * @alias Buffer.readUInt32LE + * @since v14.9.0, v12.19.0 + */ + readUint32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * @alias Buffer.readUInt32BE + * @since v14.9.0, v12.19.0 + */ + readUint32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): this; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): this; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): this; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt8 + * @since v14.9.0, v12.19.0 + */ + writeUint8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16LE + * @since v14.9.0, v12.19.0 + */ + writeUint16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16BE + * @since v14.9.0, v12.19.0 + */ + writeUint16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32LE + * @since v14.9.0, v12.19.0 + */ + writeUint32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32BE + * @since v14.9.0, v12.19.0 + */ + writeUint32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * + * // Fill a buffer with empty string + * const c = Buffer.allocUnsafe(5).fill(''); + * + * console.log(c.fill('')); + * // Prints: + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + fill(value: string | Uint8Array | number, offset: number, encoding: BufferEncoding): this; + fill(value: string | Uint8Array | number, encoding: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in `encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.subarray`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + indexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + lastIndexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + includes(value: string | number | Buffer, encoding: BufferEncoding): boolean; + } + var Buffer: BufferConstructor; + /** + * Decodes a string of Base64-encoded data into bytes, and encodes those bytes + * into a string using Latin-1 (ISO-8859-1). + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `Buffer.from(data, 'base64')` instead. + * @param data The Base64-encoded input string. + */ + function atob(data: string): string; + /** + * Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes + * into a string using Base64. + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `buf.toString('base64')` instead. + * @param data An ASCII (Latin1) string. + */ + function btoa(data: string): string; + interface Blob extends _Blob {} + /** + * `Blob` class is a global reference for `import { Blob } from 'node:buffer'` + * https://nodejs.org/api/buffer.html#class-blob + * @since v18.0.0 + */ + var Blob: typeof globalThis extends { onmessage: any; Blob: infer T } ? T + : typeof import("buffer").Blob; + interface File extends _File {} + /** + * `File` class is a global reference for `import { File } from 'node:buffer'` + * https://nodejs.org/api/buffer.html#class-file + * @since v20.0.0 + */ + var File: typeof globalThis extends { onmessage: any; File: infer T } ? T + : typeof import("buffer").File; + } +} +declare module "node:buffer" { + export * from "buffer"; +} diff --git a/tools/ui/node_modules/@types/node/child_process.d.ts b/tools/ui/node_modules/@types/node/child_process.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e680bf29dd33de2f7a937eb8bfb91c30c61340ac --- /dev/null +++ b/tools/ui/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1476 @@ +/** + * The `node:child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * import { spawn } from 'node:child_process'; + * import { once } from 'node:events'; + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * const [code] = await once(ls, 'close'); + * console.log(`child process exited with code ${code}`); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks, waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }` option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is + * used. If `options.env` is set without `PATH`, lookup on Unix is performed + * on a default search path search of `/usr/bin:/bin` (see your operating system's + * manual for execvpe/execvp), on Windows the current processes environment + * variable `PATH` is used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as `PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `node:child_process` module provides a handful of + * synchronous and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/child_process.js) + */ +declare module "child_process" { + import { NonSharedBuffer } from "node:buffer"; + import { Abortable, EventEmitter } from "node:events"; + import * as dgram from "node:dgram"; + import * as net from "node:net"; + import { Readable, Stream, Writable } from "node:stream"; + import { URL } from "node:url"; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server | dgram.Socket | undefined; + /** + * Instances of the `ChildProcess` represent spawned child processes. + * + * Instances of `ChildProcess` are not intended to be created directly. Rather, + * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create + * instances of `ChildProcess`. + * @since v2.2.0 + */ + class ChildProcess extends EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Control | null; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and `subprocess.stdio[2]` are also available as `subprocess.stdin`, `subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * import assert from 'node:assert'; + * import fs from 'node:fs'; + * import child_process from 'node:child_process'; + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ], + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined, // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * import { spawn } from 'node:child_process'; + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is `false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * import { spawn } from 'node:child_process'; + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to `'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'], + * }, + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * Calls {@link ChildProcess.kill} with `'SIGTERM'`. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * import cp from 'node:child_process'; + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the `'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for `'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received and buffered in + * the socket will not be sent to the child. Sending IPC sockets is not supported on Windows. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an `'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * import { createServer } from 'node:net'; + * import { fork } from 'node:child_process'; + * const subprocess = fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `node:net` module, `node:dgram` module servers use exactly the same workflow with the exceptions of + * listening on a `'message'` event instead of `'connection'` and using `server.bind()` instead of `server.listen()`. This is, however, only + * supported on Unix platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * import { createServer } from 'node:net'; + * import { fork } from 'node:child_process'; + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param sendHandle `undefined`, or a [`net.Socket`](https://nodejs.org/docs/latest-v24.x/api/net.html#class-netsocket), [`net.Server`](https://nodejs.org/docs/latest-v24.x/api/net.html#class-netserver), or [`dgram.Socket`](https://nodejs.org/docs/latest-v24.x/api/dgram.html#class-dgramsocket) object. + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send( + message: Serializable, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the `subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + * 6. spawn + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + addListener(event: "spawn", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "message", message: Serializable, sendHandle: SendHandle): boolean; + emit(event: "spawn", listener: () => void): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + on(event: "spawn", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + once(event: "spawn", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependListener(event: "spawn", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "close", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "exit", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: "spawn", listener: () => void): this; + } + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio + extends ChildProcess + { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + interface Control extends EventEmitter { + ref(): void; + unref(): void; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = "overlapped" | "pipe" | "ignore" | "inherit"; + type StdioOptions = IOType | Array; + type SerializationType = "json" | "advanced"; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default false + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = "inherit" | "ignore" | Stream; + type StdioPipeNamed = "pipe" | "overlapped"; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple< + Stdin extends StdioNull | StdioPipe, + Stdout extends StdioNull | StdioPipe, + Stderr extends StdioNull | StdioPipe, + > extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given `command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env, + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * import { spawn } from 'node:child_process'; + * import { once } from 'node:events'; + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * const [code] = await once(ls, 'close'); + * console.log(`child process exited with code ${code}`); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * import { spawn } from 'node:child_process'; + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * import { spawn } from 'node:child_process'; + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js overwrites `argv[0]` with `process.execPath` on startup, so `process.argv[0]` in a Node.js child process will not match the `argv0` parameter passed to `spawn` from the parent. Retrieve + * it with the `process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { spawn } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn( + command: string, + args?: readonly string[], + options?: SpawnOptionsWithoutStdio, + ): ChildProcessWithoutNullStreams; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, args: readonly string[], options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + signal?: AbortSignal | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + encoding?: string | null | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding?: BufferEncoding | undefined; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: "buffer" | null; // specify `null`. + } + // TODO: Just Plain Wrong™ (see also nodejs/node#57392) + interface ExecException extends Error { + cmd?: string; + killed?: boolean; + code?: number; + signal?: NodeJS.Signals; + stdout?: string; + stderr?: string; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * import { exec } from 'node:child_process'; + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments `(error, stdout, stderr)`. On success, `error` will be `null`. On error, `error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0` indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * import { exec } from 'node:child_process'; + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * import util from 'node:util'; + * import child_process from 'node:child_process'; + * const exec = util.promisify(child_process.exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { exec } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec( + command: string, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: ExecOptionsWithBufferEncoding, + callback?: (error: ExecException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void, + ): ChildProcess; + // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: ExecOptionsWithStringEncoding, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: ExecOptions | undefined | null, + callback?: ( + error: ExecException | null, + stdout: string | NonSharedBuffer, + stderr: string | NonSharedBuffer, + ) => void, + ): ChildProcess; + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: NonSharedBuffer; + stderr: NonSharedBuffer; + }>; + function __promisify__( + command: string, + options: ExecOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | NonSharedBuffer; + stderr: string | NonSharedBuffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + encoding?: string | null | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding?: BufferEncoding | undefined; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: "buffer" | null; + } + /** @deprecated Use `ExecFileOptions` instead. */ + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions {} + // TODO: execFile exceptions can take many forms... this accurately describes none of them + type ExecFileException = + & Omit + & Omit + & { code?: string | number | null }; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * import { execFile } from 'node:child_process'; + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * import util from 'node:util'; + * import child_process from 'node:child_process'; + * const execFile = util.promisify(child_process.execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { execFile } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + // no `options` definitely means stdout/stderr are `string`. + function execFile( + file: string, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile( + file: string, + options: ExecFileOptionsWithBufferEncoding, + callback?: (error: ExecFileException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback?: (error: ExecFileException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void, + ): ChildProcess; + // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptionsWithStringEncoding, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: ExecFileOptions | undefined | null, + callback: + | (( + error: ExecFileException | null, + stdout: string | NonSharedBuffer, + stderr: string | NonSharedBuffer, + ) => void) + | undefined + | null, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions | undefined | null, + callback: + | (( + error: ExecFileException | null, + stdout: string | NonSharedBuffer, + stderr: string | NonSharedBuffer, + ) => void) + | undefined + | null, + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: NonSharedBuffer; + stderr: NonSharedBuffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: NonSharedBuffer; + stderr: NonSharedBuffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | NonSharedBuffer; + stderr: string | NonSharedBuffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | NonSharedBuffer; + stderr: string | NonSharedBuffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the `options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by `child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * import { fork } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string | URL, options?: ForkOptions): ChildProcess; + function fork(modulePath: string | URL, args?: readonly string[], options?: ForkOptions): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: "buffer" | null | undefined; + } + interface SpawnSyncReturns { + pid: number; + output: Array; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args: readonly string[]): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithStringEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithBufferEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args?: readonly string[], + options?: SpawnSyncOptions, + ): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + /** + * Can be set to 'pipe', 'inherit, or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: "buffer" | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM` signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): NonSharedBuffer; + function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): NonSharedBuffer; + function execSync(command: string, options?: ExecSyncOptions): string | NonSharedBuffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding?: "buffer" | null | undefined; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): NonSharedBuffer; + function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): NonSharedBuffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): string | NonSharedBuffer; + function execFileSync(file: string, args: readonly string[]): NonSharedBuffer; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithStringEncoding, + ): string; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithBufferEncoding, + ): NonSharedBuffer; + function execFileSync( + file: string, + args?: readonly string[], + options?: ExecFileSyncOptions, + ): string | NonSharedBuffer; +} +declare module "node:child_process" { + export * from "child_process"; +} diff --git a/tools/ui/node_modules/@types/node/cluster.d.ts b/tools/ui/node_modules/@types/node/cluster.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cdbc21902c2b77f19708e22cb66c7f0660887e62 --- /dev/null +++ b/tools/ui/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,578 @@ +/** + * Clusters of Node.js processes can be used to run multiple instances of Node.js + * that can distribute workloads among their application threads. When process isolation + * is not needed, use the [`worker_threads`](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html) + * module instead, which allows running multiple application threads within a single Node.js instance. + * + * The cluster module allows easy creation of child processes that all share + * server ports. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('exit', (worker, code, signal) => { + * console.log(`worker ${worker.process.pid} died`); + * }); + * } else { + * // Workers can share any TCP connection + * // In this case it is an HTTP server + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * + * console.log(`Worker ${process.pid} started`); + * } + * ``` + * + * Running Node.js will now share port 8000 between the workers: + * + * ```console + * $ node server.js + * Primary 3596 is running + * Worker 4324 started + * Worker 4520 started + * Worker 6056 started + * Worker 5644 started + * ``` + * + * On Windows, it is not yet possible to set up a named pipe server in a worker. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/cluster.js) + */ +declare module "cluster" { + import * as child from "node:child_process"; + import EventEmitter = require("node:events"); + import * as net from "node:net"; + type SerializationType = "json" | "advanced"; + export interface ClusterSettings { + /** + * List of string arguments passed to the Node.js executable. + * @default process.execArgv + */ + execArgv?: string[] | undefined; + /** + * File path to worker file. + * @default process.argv[1] + */ + exec?: string | undefined; + /** + * String arguments passed to worker. + * @default process.argv.slice(2) + */ + args?: readonly string[] | undefined; + /** + * Whether or not to send output to parent's stdio. + * @default false + */ + silent?: boolean | undefined; + /** + * Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must + * contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See [`child_prcess.spawn()`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#child_processspawncommand-args-options)'s + * [`stdio`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#optionsstdio). + */ + stdio?: any[] | undefined; + /** + * Sets the user identity of the process. (See [`setuid(2)`](https://man7.org/linux/man-pages/man2/setuid.2.html).) + */ + uid?: number | undefined; + /** + * Sets the group identity of the process. (See [`setgid(2)`](https://man7.org/linux/man-pages/man2/setgid.2.html).) + */ + gid?: number | undefined; + /** + * Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. + * By default each worker gets its own port, incremented from the primary's `process.debugPort`. + */ + inspectPort?: number | (() => number) | undefined; + /** + * Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. + * See [Advanced serialization for `child_process`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#advanced-serialization) for more details. + * @default false + */ + serialization?: SerializationType | undefined; + /** + * Current working directory of the worker process. + * @default undefined (inherits from parent process) + */ + cwd?: string | undefined; + /** + * Hide the forked processes console window that would normally be created on Windows systems. + * @default false + */ + windowsHide?: boolean | undefined; + } + export interface Address { + address: string; + port: number; + /** + * The `addressType` is one of: + * + * * `4` (TCPv4) + * * `6` (TCPv6) + * * `-1` (Unix domain socket) + * * `'udp4'` or `'udp6'` (UDPv4 or UDPv6) + */ + addressType: 4 | 6 | -1 | "udp4" | "udp6"; + } + /** + * A `Worker` object contains all public information and method about a worker. + * In the primary it can be obtained using `cluster.workers`. In a worker + * it can be obtained using `cluster.worker`. + * @since v0.7.0 + */ + export class Worker extends EventEmitter { + /** + * Each new worker is given its own unique id, this id is stored in the `id`. + * + * While a worker is alive, this is the key that indexes it in `cluster.workers`. + * @since v0.8.0 + */ + id: number; + /** + * All workers are created using [`child_process.fork()`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#child_processforkmodulepath-args-options), the returned object + * from this function is stored as `.process`. In a worker, the global `process` is stored. + * + * See: [Child Process module](https://nodejs.org/docs/latest-v24.x/api/child_process.html#child_processforkmodulepath-args-options). + * + * Workers will call `process.exit(0)` if the `'disconnect'` event occurs + * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against + * accidental disconnection. + * @since v0.7.0 + */ + process: child.ChildProcess; + /** + * Send a message to a worker or primary, optionally with a handle. + * + * In the primary, this sends a message to a specific worker. It is identical to [`ChildProcess.send()`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#subprocesssendmessage-sendhandle-options-callback). + * + * In a worker, this sends a message to the primary. It is identical to `process.send()`. + * + * This example will echo back all messages from the primary: + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * worker.send('hi there'); + * + * } else if (cluster.isWorker) { + * process.on('message', (msg) => { + * process.send(msg); + * }); + * } + * ``` + * @since v0.7.0 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. + */ + send(message: child.Serializable, callback?: (error: Error | null) => void): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + callback?: (error: Error | null) => void, + ): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + options?: child.MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * This function will kill the worker. In the primary worker, it does this by + * disconnecting the `worker.process`, and once disconnected, killing with `signal`. In the worker, it does it by killing the process with `signal`. + * + * The `kill()` function kills the worker process without waiting for a graceful + * disconnect, it has the same behavior as `worker.process.kill()`. + * + * This method is aliased as `worker.destroy()` for backwards compatibility. + * + * In a worker, `process.kill()` exists, but it is not this function; + * it is [`kill()`](https://nodejs.org/docs/latest-v24.x/api/process.html#processkillpid-signal). + * @since v0.9.12 + * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. + */ + kill(signal?: string): void; + destroy(signal?: string): void; + /** + * In a worker, this function will close all servers, wait for the `'close'` event + * on those servers, and then disconnect the IPC channel. + * + * In the primary, an internal message is sent to the worker causing it to call `.disconnect()` on itself. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * After a server is closed, it will no longer accept new connections, + * but connections may be accepted by any other listening worker. Existing + * connections will be allowed to close as usual. When no more connections exist, + * see `server.close()`, the IPC channel to the worker will close allowing it + * to die gracefully. + * + * The above applies _only_ to server connections, client connections are not + * automatically closed by workers, and disconnect does not wait for them to close + * before exiting. + * + * In a worker, `process.disconnect` exists, but it is not this function; + * it is `disconnect()`. + * + * Because long living server connections may block workers from disconnecting, it + * may be useful to send a message, so application specific actions may be taken to + * close them. It also may be useful to implement a timeout, killing a worker if + * the `'disconnect'` event has not been emitted after some time. + * + * ```js + * import net from 'node:net'; + * + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * let timeout; + * + * worker.on('listening', (address) => { + * worker.send('shutdown'); + * worker.disconnect(); + * timeout = setTimeout(() => { + * worker.kill(); + * }, 2000); + * }); + * + * worker.on('disconnect', () => { + * clearTimeout(timeout); + * }); + * + * } else if (cluster.isWorker) { + * const server = net.createServer((socket) => { + * // Connections never end + * }); + * + * server.listen(8000); + * + * process.on('message', (msg) => { + * if (msg === 'shutdown') { + * // Initiate graceful close of any connections to server + * } + * }); + * } + * ``` + * @since v0.7.7 + * @return A reference to `worker`. + */ + disconnect(): this; + /** + * This function returns `true` if the worker is connected to its primary via its + * IPC channel, `false` otherwise. A worker is connected to its primary after it + * has been created. It is disconnected after the `'disconnect'` event is emitted. + * @since v0.11.14 + */ + isConnected(): boolean; + /** + * This function returns `true` if the worker's process has terminated (either + * because of exiting or being signaled). Otherwise, it returns `false`. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('fork', (worker) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * + * cluster.on('exit', (worker, code, signal) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * } else { + * // Workers can share any TCP connection. In this case, it is an HTTP server. + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end(`Current process\n ${process.pid}`); + * process.kill(process.pid); + * }).listen(8000); + * } + * ``` + * @since v0.11.14 + */ + isDead(): boolean; + /** + * This property is `true` if the worker exited due to `.disconnect()`. + * If the worker exited any other way, it is `false`. If the + * worker has not exited, it is `undefined`. + * + * The boolean `worker.exitedAfterDisconnect` allows distinguishing between + * voluntary and accidental exit, the primary may choose not to respawn a worker + * based on this value. + * + * ```js + * cluster.on('exit', (worker, code, signal) => { + * if (worker.exitedAfterDisconnect === true) { + * console.log('Oh, it was just voluntary – no need to worry'); + * } + * }); + * + * // kill worker + * worker.kill(); + * ``` + * @since v6.0.0 + */ + exitedAfterDisconnect: boolean; + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "listening", address: Address): boolean; + emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + export interface Cluster extends EventEmitter { + disconnect(callback?: () => void): void; + /** + * Spawn a new worker process. + * + * This can only be called from the primary process. + * @param env Key/value pairs to add to worker process environment. + * @since v0.6.0 + */ + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + /** + * True if the process is a primary. This is determined by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` + * is undefined, then `isPrimary` is `true`. + * @since v16.0.0 + */ + readonly isPrimary: boolean; + /** + * True if the process is not a primary (it is the negation of `cluster.isPrimary`). + * @since v0.6.0 + */ + readonly isWorker: boolean; + /** + * The scheduling policy, either `cluster.SCHED_RR` for round-robin or `cluster.SCHED_NONE` to leave it to the operating system. This is a + * global setting and effectively frozen once either the first worker is spawned, or [`.setupPrimary()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clustersetupprimarysettings) + * is called, whichever comes first. + * + * `SCHED_RR` is the default on all operating systems except Windows. Windows will change to `SCHED_RR` once libuv is able to effectively distribute + * IOCP handles without incurring a large performance hit. + * + * `cluster.schedulingPolicy` can also be set through the `NODE_CLUSTER_SCHED_POLICY` environment variable. Valid values are `'rr'` and `'none'`. + * @since v0.11.2 + */ + schedulingPolicy: number; + /** + * After calling [`.setupPrimary()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clustersetupprimarysettings) + * (or [`.fork()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clusterforkenv)) this settings object will contain + * the settings, including the default values. + * + * This object is not intended to be changed or set manually. + * @since v0.7.1 + */ + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use [`.setupPrimary()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clustersetupprimarysettings) instead. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`. + * + * Any settings changes only affect future calls to [`.fork()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clusterforkenv) + * and have no effect on workers that are already running. + * + * The only attribute of a worker that cannot be set via `.setupPrimary()` is the `env` passed to + * [`.fork()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clusterforkenv). + * + * The defaults above apply to the first call only; the defaults for later calls are the current values at the time of + * `cluster.setupPrimary()` is called. + * + * ```js + * import cluster from 'node:cluster'; + * + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'https'], + * silent: true, + * }); + * cluster.fork(); // https worker + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'http'], + * }); + * cluster.fork(); // http worker + * ``` + * + * This can only be called from the primary process. + * @since v16.0.0 + */ + setupPrimary(settings?: ClusterSettings): void; + /** + * A reference to the current worker object. Not available in the primary process. + * + * ```js + * import cluster from 'node:cluster'; + * + * if (cluster.isPrimary) { + * console.log('I am primary'); + * cluster.fork(); + * cluster.fork(); + * } else if (cluster.isWorker) { + * console.log(`I am worker #${cluster.worker.id}`); + * } + * ``` + * @since v0.7.0 + */ + readonly worker?: Worker; + /** + * A hash that stores the active worker objects, keyed by `id` field. This makes it easy to loop through all the workers. It is only available in the primary process. + * + * A worker is removed from `cluster.workers` after the worker has disconnected _and_ exited. The order between these two events cannot be determined in advance. However, it + * is guaranteed that the removal from the `cluster.workers` list happens before the last `'disconnect'` or `'exit'` event is emitted. + * + * ```js + * import cluster from 'node:cluster'; + * + * for (const worker of Object.values(cluster.workers)) { + * worker.send('big announcement to all workers'); + * } + * ``` + * @since v0.7.0 + */ + readonly workers?: NodeJS.Dict; + readonly SCHED_NONE: number; + readonly SCHED_RR: number; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect", worker: Worker): boolean; + emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + emit(event: "fork", worker: Worker): boolean; + emit(event: "listening", worker: Worker, address: Address): boolean; + emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online", worker: Worker): boolean; + emit(event: "setup", settings: ClusterSettings): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: ClusterSettings) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + } + const cluster: Cluster; + export default cluster; +} +declare module "node:cluster" { + export * from "cluster"; + export { default as default } from "cluster"; +} diff --git a/tools/ui/node_modules/@types/node/compatibility/iterators.d.ts b/tools/ui/node_modules/@types/node/compatibility/iterators.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..156e7856360bf532de1d82080e425573e9b2d749 --- /dev/null +++ b/tools/ui/node_modules/@types/node/compatibility/iterators.d.ts @@ -0,0 +1,21 @@ +// Backwards-compatible iterator interfaces, augmented with iterator helper methods by lib.esnext.iterator in TypeScript 5.6. +// The IterableIterator interface does not contain these methods, which creates assignability issues in places where IteratorObjects +// are expected (eg. DOM-compatible APIs) if lib.esnext.iterator is loaded. +// Also ensures that iterators returned by the Node API, which inherit from Iterator.prototype, correctly expose the iterator helper methods +// if lib.esnext.iterator is loaded. +// TODO: remove once this package no longer supports TS 5.5, and replace NodeJS.BuiltinIteratorReturn with BuiltinIteratorReturn. + +// Placeholders for TS <5.6 +interface IteratorObject {} +interface AsyncIteratorObject {} + +declare namespace NodeJS { + // Populate iterator methods for TS <5.6 + interface Iterator extends globalThis.Iterator {} + interface AsyncIterator extends globalThis.AsyncIterator {} + + // Polyfill for TS 5.6's instrinsic BuiltinIteratorReturn type, required for DOM-compatible iterators + type BuiltinIteratorReturn = ReturnType extends + globalThis.Iterator ? TReturn + : any; +} diff --git a/tools/ui/node_modules/@types/node/console.d.ts b/tools/ui/node_modules/@types/node/console.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c8a6825a0c656d36bf516b90e3b72389a43ea71 --- /dev/null +++ b/tools/ui/node_modules/@types/node/console.d.ts @@ -0,0 +1,453 @@ +/** + * The `node:console` module provides a simple debugging console that is similar to + * the JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()`, and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/console.js) + */ +declare module "console" { + import console = require("node:console"); + export = console; +} +declare module "node:console" { + import { InspectOptions } from "node:util"; + global { + // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build + interface Console { + Console: console.ConsoleConstructor; + /** + * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only + * writes a message and does not otherwise affect execution. The output always + * starts with `"Assertion failed"`. If provided, `message` is formatted using + * [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args). + * + * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. + * + * ```js + * console.assert(true, 'does nothing'); + * + * console.assert(false, 'Whoops %s work', 'didn\'t'); + * // Assertion failed: Whoops didn't work + * + * console.assert(); + * // Assertion failed + * ``` + * @since v0.1.101 + * @param value The value tested for being truthy. + * @param message All arguments besides `value` are used as error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the + * TTY. When `stdout` is not a TTY, this method does nothing. + * + * The specific operation of `console.clear()` can vary across operating systems + * and terminal types. For most Linux operating systems, `console.clear()` operates similarly to the `clear` shell command. On Windows, `console.clear()` will clear only the output in the + * current terminal viewport for the Node.js + * binary. + * @since v8.3.0 + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the + * number of times `console.count()` has been called with the given `label`. + * + * ```js + * > console.count() + * default: 1 + * undefined + * > console.count('default') + * default: 2 + * undefined + * > console.count('abc') + * abc: 1 + * undefined + * > console.count('xyz') + * xyz: 1 + * undefined + * > console.count('abc') + * abc: 2 + * undefined + * > console.count() + * default: 3 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + * + * ```js + * > console.count('abc'); + * abc: 1 + * undefined + * > console.countReset('abc'); + * undefined + * > console.count('abc'); + * abc: 1 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link log}. + * @since v8.0.0 + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + * @since v0.1.101 + */ + dir(obj: any, options?: InspectOptions): void; + /** + * This method calls `console.log()` passing it the arguments received. + * This method does not produce any XML formatting. + * @since v8.0.0 + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). + * + * ```js + * const code = 5; + * console.error('error #%d', code); + * // Prints: error #5, to stderr + * console.error('error', code); + * // Prints: error 5, to stderr + * ``` + * + * If formatting elements (e.g. `%d`) are not found in the first string then + * [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) is called on each argument and the + * resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) + * for more information. + * @since v0.1.100 + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by spaces for `groupIndentation` length. + * + * If one or more `label`s are provided, those are printed first without the + * additional indentation. + * @since v8.5.0 + */ + group(...label: any[]): void; + /** + * An alias for {@link group}. + * @since v8.5.0 + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by spaces for `groupIndentation` length. + * @since v8.5.0 + */ + groupEnd(): void; + /** + * The `console.info()` function is an alias for {@link log}. + * @since v0.1.100 + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). + * + * ```js + * const count = 5; + * console.log('count: %d', count); + * // Prints: count: 5, to stdout + * console.log('count:', count); + * // Prints: count: 5, to stdout + * ``` + * + * See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information. + * @since v0.1.100 + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * Try to construct a table with the columns of the properties of `tabularData` (or use `properties`) and rows of `tabularData` and log it. Falls back to just + * logging the argument if it can't be parsed as tabular. + * + * ```js + * // These can't be parsed as tabular data + * console.table(Symbol()); + * // Symbol() + * + * console.table(undefined); + * // undefined + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); + * // ┌─────────┬─────┬─────┐ + * // │ (index) │ a │ b │ + * // ├─────────┼─────┼─────┤ + * // │ 0 │ 1 │ 'Y' │ + * // │ 1 │ 'Z' │ 2 │ + * // └─────────┴─────┴─────┘ + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); + * // ┌─────────┬─────┐ + * // │ (index) │ a │ + * // ├─────────┼─────┤ + * // │ 0 │ 1 │ + * // │ 1 │ 'Z' │ + * // └─────────┴─────┘ + * ``` + * @since v10.0.0 + * @param properties Alternate properties for constructing the table. + */ + table(tabularData: any, properties?: readonly string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers + * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in + * suitable time units to `stdout`. For example, if the elapsed + * time is 3869ms, `console.timeEnd()` displays "3.869s". + * @since v0.1.104 + * @param [label='default'] + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('bunch-of-stuff'); + * // Do a bunch of stuff. + * console.timeEnd('bunch-of-stuff'); + * // Prints: bunch-of-stuff: 225.438ms + * ``` + * @since v0.1.104 + * @param [label='default'] + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link time}, prints + * the elapsed time and other `data` arguments to `stdout`: + * + * ```js + * console.time('process'); + * const value = expensiveProcess1(); // Returns 42 + * console.timeLog('process', value); + * // Prints "process: 365.227ms 42". + * doExpensiveProcess2(value); + * console.timeEnd('process'); + * ``` + * @since v10.7.0 + * @param [label='default'] + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) + * formatted message and stack trace to the current position in the code. + * + * ```js + * console.trace('Show me'); + * // Prints: (stack trace will vary based on where trace is called) + * // Trace: Show me + * // at repl:2:9 + * // at REPLServer.defaultEval (repl.js:248:27) + * // at bound (domain.js:287:14) + * // at REPLServer.runBound [as eval] (domain.js:300:12) + * // at REPLServer. (repl.js:412:12) + * // at emitOne (events.js:82:20) + * // at REPLServer.emit (events.js:169:7) + * // at REPLServer.Interface._onLine (readline.js:210:10) + * // at REPLServer.Interface._line (readline.js:549:8) + * // at REPLServer.Interface._ttyWrite (readline.js:826:14) + * ``` + * @since v0.1.104 + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The `console.warn()` function is an alias for {@link error}. + * @since v0.1.100 + */ + warn(message?: any, ...optionalParams: any[]): void; + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. The `console.profile()` + * method starts a JavaScript CPU profile with an optional label until {@link profileEnd} + * is called. The profile is then added to the Profile panel of the inspector. + * + * ```js + * console.profile('MyLabel'); + * // Some code + * console.profileEnd('MyLabel'); + * // Adds the profile 'MyLabel' to the Profiles panel of the inspector. + * ``` + * @since v8.0.0 + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. Stops the current + * JavaScript CPU profiling session if one has been started and prints the report to the + * Profiles panel of the inspector. See {@link profile} for an example. + * + * If this method is called without a label, the most recently started profile is stopped. + * @since v8.0.0 + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. The `console.timeStamp()` + * method adds an event with the label `'label'` to the Timeline panel of the inspector. + * @since v8.0.0 + */ + timeStamp(label?: string): void; + } + /** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + /** + * Ignore errors when writing to the underlying streams. + * @default true + */ + ignoreErrors?: boolean | undefined; + /** + * Set color support for this `Console` instance. Setting to true enables coloring while inspecting + * values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color + * support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the + * respective stream. This option can not be used, if `inspectOptions.colors` is set as well. + * @default auto + */ + colorMode?: boolean | "auto" | undefined; + /** + * Specifies options that are passed along to + * `util.inspect()`. Can be an options object or, if different options + * for stdout and stderr are desired, a `Map` from stream objects to options. + */ + inspectOptions?: InspectOptions | ReadonlyMap | undefined; + /** + * Set group indentation. + * @default 2 + */ + groupIndentation?: number | undefined; + } + interface ConsoleConstructor { + prototype: Console; + new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + } + var console: Console; + } + export = globalThis.console; +} diff --git a/tools/ui/node_modules/@types/node/constants.d.ts b/tools/ui/node_modules/@types/node/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5685a9dfe307be102639a9c61a8c02632b542c95 --- /dev/null +++ b/tools/ui/node_modules/@types/node/constants.d.ts @@ -0,0 +1,21 @@ +/** + * @deprecated The `node:constants` module is deprecated. When requiring access to constants + * relevant to specific Node.js builtin modules, developers should instead refer + * to the `constants` property exposed by the relevant module. For instance, + * `require('node:fs').constants` and `require('node:os').constants`. + */ +declare module "constants" { + const constants: + & typeof import("node:os").constants.dlopen + & typeof import("node:os").constants.errno + & typeof import("node:os").constants.priority + & typeof import("node:os").constants.signals + & typeof import("node:fs").constants + & typeof import("node:crypto").constants; + export = constants; +} + +declare module "node:constants" { + import constants = require("constants"); + export = constants; +} diff --git a/tools/ui/node_modules/@types/node/crypto.d.ts b/tools/ui/node_modules/@types/node/crypto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..886379fa442f60693cf563c1ceadaa183d4997da --- /dev/null +++ b/tools/ui/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,5417 @@ +/** + * The `node:crypto` module provides cryptographic functionality that includes a + * set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify + * functions. + * + * ```js + * const { createHmac } = await import('node:crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/crypto.js) + */ +declare module "crypto" { + import { NonSharedBuffer } from "node:buffer"; + import * as stream from "node:stream"; + import { PeerCertificate } from "node:tls"; + /** + * SPKAC is a Certificate Signing Request mechanism originally implemented by + * Netscape and was specified formally as part of HTML5's `keygen` element. + * + * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects + * should not use this element anymore. + * + * The `node:crypto` module provides the `Certificate` class for working with SPKAC + * data. The most common usage is handling output generated by the HTML5 `` element. Node.js uses [OpenSSL's SPKAC + * implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally. + * @since v0.11.8 + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const challenge = Certificate.exportChallenge(spkac); + * console.log(challenge.toString('utf8')); + * // Prints: the challenge as a UTF8 string + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportChallenge(spkac: BinaryLike): NonSharedBuffer; + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const publicKey = Certificate.exportPublicKey(spkac); + * console.log(publicKey); + * // Prints: the public key as + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The public key component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportPublicKey(spkac: BinaryLike, encoding?: string): NonSharedBuffer; + /** + * ```js + * import { Buffer } from 'node:buffer'; + * const { Certificate } = await import('node:crypto'); + * + * const spkac = getSpkacSomehow(); + * console.log(Certificate.verifySpkac(Buffer.from(spkac))); + * // Prints: true or false + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return `true` if the given `spkac` data structure is valid, `false` otherwise. + */ + static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): NonSharedBuffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): NonSharedBuffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + namespace constants { + // https://nodejs.org/dist/latest-v24.x/docs/api/crypto.html#crypto-constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode for TLS v1.3 */ + const SSL_OP_ALLOW_NO_DHE_KEX: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + /** Instructs OpenSSL to disable encrypt-then-MAC. */ + const SSL_OP_NO_ENCRYPT_THEN_MAC: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to disable renegotiation. */ + const SSL_OP_NO_RENEGOTIATION: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + /** Instructs OpenSSL to turn off SSL v2 */ + const SSL_OP_NO_SSLv2: number; + /** Instructs OpenSSL to turn off SSL v3 */ + const SSL_OP_NO_SSLv3: number; + /** Instructs OpenSSL to disable use of RFC4507bis tickets. */ + const SSL_OP_NO_TICKET: number; + /** Instructs OpenSSL to turn off TLS v1 */ + const SSL_OP_NO_TLSv1: number; + /** Instructs OpenSSL to turn off TLS v1.1 */ + const SSL_OP_NO_TLSv1_1: number; + /** Instructs OpenSSL to turn off TLS v1.2 */ + const SSL_OP_NO_TLSv1_2: number; + /** Instructs OpenSSL to turn off TLS v1.3 */ + const SSL_OP_NO_TLSv1_3: number; + /** Instructs OpenSSL server to prioritize ChaCha20-Poly1305 when the client does. This option has no effect if `SSL_OP_CIPHER_SERVER_PREFERENCE` is not enabled. */ + const SSL_OP_PRIORITIZE_CHACHA: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHash, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was + * obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not + * exceed the block size of `algorithm` (e.g., 512 bits for SHA-256). + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = "base64" | "base64url" | "hex" | "binary"; + type CharacterEncoding = "utf8" | "utf-8" | "utf16le" | "utf-16le" | "latin1"; + type LegacyCharacterEncoding = "ascii" | "binary" | "ucs2" | "ucs-2"; + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { createHash } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: HashOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ + digest(): NonSharedBuffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + * @deprecated Since v20.13.0 Calling `Hmac` class directly with `Hmac()` or `new Hmac()` is deprecated due to being internals, not intended for public use. Please use the {@link createHmac} method to create Hmac instances. + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ + digest(): NonSharedBuffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyObjectType = "secret" | "public" | "private"; + interface KeyExportOptions { + type: "pkcs1" | "spki" | "pkcs8" | "sec1"; + format: T; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: "jwk"; + } + interface JsonWebKey { + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + k?: string; + kty?: string; + n?: string; + p?: string; + q?: string; + qi?: string; + x?: string; + y?: string; + [key: string]: unknown; + } + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number; + /** + * Name of the curve (EC). + */ + namedCurve?: string; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ + class KeyObject { + private constructor(); + /** + * Example: Converting a `CryptoKey` instance to a `KeyObject`: + * + * ```js + * const { KeyObject } = await import('node:crypto'); + * const { subtle } = globalThis.crypto; + * + * const key = await subtle.generateKey({ + * name: 'HMAC', + * hash: 'SHA-256', + * length: 256, + * }, true, ['sign', 'verify']); + * + * const keyObject = KeyObject.from(key); + * console.log(keyObject.symmetricKeySize); + * // Prints: 32 (symmetric key size in bytes) + * ``` + * @since v15.0.0 + */ + static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. See the + * supported [asymmetric key types](https://nodejs.org/docs/latest-v24.x/api/crypto.html#asymmetric-key-types). + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ + asymmetricKeyType?: KeyType; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ + export(options: KeyExportOptions<"pem">): string | NonSharedBuffer; + export(options?: KeyExportOptions<"der">): NonSharedBuffer; + export(options?: JwkKeyExportOptions): JsonWebKey; + /** + * Returns `true` or `false` depending on whether the keys have exactly the same + * type, value, and parameters. This method is not [constant time](https://en.wikipedia.org/wiki/Timing_attack). + * @since v17.7.0, v16.15.0 + * @param otherKeyObject A `KeyObject` with which to compare `keyObject`. + */ + equals(otherKeyObject: KeyObject): boolean; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ + symmetricKeySize?: number; + /** + * Converts a `KeyObject` instance to a `CryptoKey`. + * @since 22.10.0 + */ + toCryptoKey( + algorithm: + | webcrypto.AlgorithmIdentifier + | webcrypto.RsaHashedImportParams + | webcrypto.EcKeyImportParams + | webcrypto.HmacImportParams, + extractable: boolean, + keyUsages: readonly webcrypto.KeyUsage[], + ): webcrypto.CryptoKey; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ + type: KeyObjectType; + } + type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm"; + type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; + type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb"; + type CipherChaCha20Poly1305Types = "chacha20-poly1305"; + type BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + interface CipherOCBOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherChaCha20Poly1305Options extends stream.TransformOptions { + /** @default 16 */ + authTagLength?: number | undefined; + } + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): CipherCCM; + function createCipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): CipherOCB; + function createCipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): CipherGCM; + function createCipheriv( + algorithm: CipherChaCha20Poly1305Types, + key: CipherKey, + iv: BinaryLike, + options?: CipherChaCha20Poly1305Options, + ): CipherChaCha20Poly1305; + function createCipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Cipheriv; + /** + * Instances of the `Cipheriv` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipheriv} method is + * used to create `Cipheriv` instances. `Cipheriv` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipheriv` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipheriv` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * + * import { + * pipeline, + * } from 'node:stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ + class Cipheriv extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or `DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): NonSharedBuffer; + update(data: string, inputEncoding: Encoding): NonSharedBuffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipheriv` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): NonSharedBuffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipheriv` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + interface CipherGCM extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + interface CipherOCB extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + interface CipherChaCha20Poly1305 extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): NonSharedBuffer; + } + /** + * Creates and returns a `Decipheriv` object that uses the given `algorithm`, `key` and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the `authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength` option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): DecipherOCB; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv( + algorithm: CipherChaCha20Poly1305Types, + key: CipherKey, + iv: BinaryLike, + options?: CipherChaCha20Poly1305Options, + ): DecipherChaCha20Poly1305; + function createDecipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Decipheriv; + /** + * Instances of the `Decipheriv` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipheriv} method is + * used to create `Decipheriv` instances. `Decipheriv` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipheriv` objects as streams: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * let chunk; + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipheriv` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ + class Decipheriv extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data` argument is a string using the specified encoding. If the `inputEncoding` argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding` is specified, a string using the specified encoding is returned. If no `outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: NodeJS.ArrayBufferView): NonSharedBuffer; + update(data: string, inputEncoding: Encoding): NonSharedBuffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipheriv` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): NonSharedBuffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling `decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface DecipherGCM extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherOCB extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherChaCha20Poly1305 extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "pkcs8" | "sec1" | undefined; + passphrase?: string | Buffer | undefined; + encoding?: string | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "spki" | undefined; + encoding?: string | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey, + * } = await import('node:crypto'); + * + * generateKey('hmac', { length: 512 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: "hmac" | "aes", + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void, + ): void; + /** + * Synchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKeySync, + * } = await import('node:crypto'); + * + * const key = generateKeySync('hmac', { length: 512 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKeySync( + type: "hmac" | "aes", + options: { + length: number; + }, + ): KeyObject; + interface JsonWebKeyInput { + key: JsonWebKey; + format: "jwk"; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key` must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject` with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type `'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + // TODO: signing algorithm type + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; + type DSAEncoding = "der" | "ieee-p1363"; + interface SigningOptions { + /** + * @see crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + context?: ArrayBuffer | NodeJS.ArrayBufferView | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface SignJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1', + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput): NonSharedBuffer; + sign( + privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + outputFormat: BinaryToTextEncoding, + ): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances. `Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if `object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: string, + signature_format?: BinaryToTextEncoding, + ): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If `generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createDiffieHellman, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values unless they have been + * generated or computed already, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * This function is a thin wrapper around [`DH_generate_key()`](https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html). In particular, + * once a private key has been generated or set, calling this function only updates + * the public key but does not generate a new private key. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + generateKeys(): NonSharedBuffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret( + otherPublicKey: NodeJS.ArrayBufferView, + inputEncoding?: null, + outputEncoding?: null, + ): NonSharedBuffer; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding?: null, + ): NonSharedBuffer; + computeSecret( + otherPublicKey: NodeJS.ArrayBufferView, + inputEncoding: null, + outputEncoding: BinaryToTextEncoding, + ): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrime(): NonSharedBuffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getGenerator(): NonSharedBuffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): NonSharedBuffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): NonSharedBuffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided, `publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * + * This function does not automatically compute the associated public key. Either `diffieHellman.setPublicKey()` or `diffieHellman.generateKeys()` can be + * used to manually provide the public key or to automatically derive it. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `node:constants` module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ + verifyError: number; + } + /** + * The `DiffieHellmanGroup` class takes a well-known modp group as its argument. + * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation. + * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods. + * + * ```js + * const { createDiffieHellmanGroup } = await import('node:crypto'); + * const dh = createDiffieHellmanGroup('modp1'); + * ``` + * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt): + * ```bash + * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h + * modp1 # 768 bits + * modp2 # 1024 bits + * modp5 # 1536 bits + * modp14 # 2048 bits + * modp15 # etc. + * modp16 + * modp17 + * modp18 + * ``` + * @since v0.7.5 + */ + const DiffieHellmanGroup: DiffieHellmanGroupConstructor; + interface DiffieHellmanGroupConstructor { + new(name: string): DiffieHellmanGroup; + (name: string): DiffieHellmanGroup; + readonly prototype: DiffieHellmanGroup; + } + type DiffieHellmanGroup = Omit; + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are listed in the documentation for `DiffieHellmanGroup`. + * + * The returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman, + * } = await import('node:crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellmanGroup; + /** + * An alias for {@link getDiffieHellman} + * @since v0.9.3 + */ + function createDiffieHellmanGroup(name: string): DiffieHellmanGroup; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated `derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2, + * } = await import('node:crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync, + * } = await import('node:crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + ): NonSharedBuffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The `buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): NonSharedBuffer; + function randomBytes(size: number, callback: (err: Error | null, buf: NonSharedBuffer) => void): void; + function pseudoRandomBytes(size: number): NonSharedBuffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: NonSharedBuffer) => void): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 2**48. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync(buffer: T, offset?: number, size?: number): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as `buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill( + buffer: T, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + size: number, + callback: (err: Error | null, buf: T) => void, + ): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`. `err` is an exception object when key derivation fails, otherwise `err` is `null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt, + * } = await import('node:crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync, + * } = await import('node:crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ + function scryptSync( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options?: ScryptOptions, + ): NonSharedBuffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: NodeJS.TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ + function publicEncrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ + function publicDecrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt( + privateKey: RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt( + privateKey: RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): NonSharedBuffer; + /** + * ```js + * const { + * getCiphers, + * } = await import('node:crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves, + * } = await import('node:crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. + * Throws an error if FIPS mode is not available. + * @since v10.0.0 + * @param bool `true` to enable FIPS mode. + */ + function setFips(bool: boolean): void; + /** + * ```js + * const { + * getHashes, + * } = await import('node:crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createECDH, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'` format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH, + * } = await import('node:crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: "latin1" | "hex" | "base64" | "base64url", + format?: "uncompressed" | "compressed" | "hybrid", + ): NonSharedBuffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): NonSharedBuffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey` lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): NonSharedBuffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): NonSharedBuffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): NonSharedBuffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(encoding?: null, format?: ECDHKeyFormat): NonSharedBuffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function compares the underlying bytes that represent the given `ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time + * algorithm. + * + * This function does not leak timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. An error is thrown if `a` and `b` have + * different byte lengths. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * **When both of the inputs are `Float32Array`s or `Float64Array`s, this function might return unexpected results due to IEEE 754** + * **encoding of floating-point numbers. In particular, neither `x === y` nor `Object.is(x, y)` implies that the byte representations of two floating-point** + * **numbers `x` and `y` are equal.** + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + type KeyType = + | "dh" + | "dsa" + | "ec" + | "ed25519" + | "ed448" + | "ml-dsa-44" + | "ml-dsa-65" + | "ml-dsa-87" + | "ml-kem-1024" + | "ml-kem-512" + | "ml-kem-768" + | "rsa-pss" + | "rsa" + | "slh-dsa-sha2-128f" + | "slh-dsa-sha2-128s" + | "slh-dsa-sha2-192f" + | "slh-dsa-sha2-192s" + | "slh-dsa-sha2-256f" + | "slh-dsa-sha2-256s" + | "slh-dsa-shake-128f" + | "slh-dsa-shake-128s" + | "slh-dsa-shake-192f" + | "slh-dsa-shake-192s" + | "slh-dsa-shake-256f" + | "slh-dsa-shake-256s" + | "x25519" + | "x448"; + type KeyFormat = "pem" | "der" | "jwk"; + interface BasePrivateKeyEncodingOptions { + format: T; + cipher?: string | undefined; + passphrase?: string | undefined; + } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + interface ED25519KeyPairKeyObjectOptions {} + interface ED448KeyPairKeyObjectOptions {} + interface X25519KeyPairKeyObjectOptions {} + interface X448KeyPairKeyObjectOptions {} + interface MLDSAKeyPairKeyObjectOptions {} + interface MLKEMKeyPairKeyObjectOptions {} + interface SLHDSAKeyPairKeyObjectOptions {} + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use + */ + namedCurve: string; + /** + * Must be `'named'` or `'explicit'`. Default: `'named'`. + */ + paramEncoding?: "explicit" | "named" | undefined; + } + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface RSAPSSKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes + */ + saltLength?: string | undefined; + } + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs1" | "pkcs8"; + }; + } + interface RSAPSSKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes + */ + saltLength?: string | undefined; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ECKeyPairOptions extends ECKeyPairKeyObjectOptions { + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "sec1" | "pkcs8"; + }; + } + interface ED25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ED448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface MLDSAKeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface MLKEMKeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface SLHDSAKeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + /** + * Generates a new asymmetric key pair of the given `type`. + * See the supported [asymmetric key types](https://nodejs.org/docs/latest-v24.x/api/crypto.html#asymmetric-key-types). + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if {@link KeyObject.export `keyObject.export()`} had been called on its result. Otherwise, + * the respective part of the key is returned as a {@link KeyObject `KeyObject`}. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync, + * } = await import('node:crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type The asymmetric key type to generate. See the + * supported [asymmetric key types](https://nodejs.org/docs/latest-v24.x/api/crypto.html#asymmetric-key-types). + */ + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa", options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa-pss", options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "dsa", options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ec", options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed25519", options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed448", options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x25519", options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x448", options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options?: MLDSAKeyPairKeyObjectOptions, + ): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ml-kem-1024" | "ml-kem-512" | "ml-kem-768", + options: MLKEMKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ml-kem-1024" | "ml-kem-512" | "ml-kem-768", + options: MLKEMKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ml-kem-1024" | "ml-kem-512" | "ml-kem-768", + options: MLKEMKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ml-kem-1024" | "ml-kem-512" | "ml-kem-768", + options: MLKEMKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ml-kem-1024" | "ml-kem-512" | "ml-kem-768", + options?: MLKEMKeyPairKeyObjectOptions, + ): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: + | "slh-dsa-sha2-128f" + | "slh-dsa-sha2-128s" + | "slh-dsa-sha2-192f" + | "slh-dsa-sha2-192s" + | "slh-dsa-sha2-256f" + | "slh-dsa-sha2-256s" + | "slh-dsa-shake-128f" + | "slh-dsa-shake-128s" + | "slh-dsa-shake-192f" + | "slh-dsa-shake-192s" + | "slh-dsa-shake-256f" + | "slh-dsa-shake-256s", + options: SLHDSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: + | "slh-dsa-sha2-128f" + | "slh-dsa-sha2-128s" + | "slh-dsa-sha2-192f" + | "slh-dsa-sha2-192s" + | "slh-dsa-sha2-256f" + | "slh-dsa-sha2-256s" + | "slh-dsa-shake-128f" + | "slh-dsa-shake-128s" + | "slh-dsa-shake-192f" + | "slh-dsa-shake-192s" + | "slh-dsa-shake-256f" + | "slh-dsa-shake-256s", + options: SLHDSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: + | "slh-dsa-sha2-128f" + | "slh-dsa-sha2-128s" + | "slh-dsa-sha2-192f" + | "slh-dsa-sha2-192s" + | "slh-dsa-sha2-256f" + | "slh-dsa-sha2-256s" + | "slh-dsa-shake-128f" + | "slh-dsa-shake-128s" + | "slh-dsa-shake-192f" + | "slh-dsa-shake-192s" + | "slh-dsa-shake-256f" + | "slh-dsa-shake-256s", + options: SLHDSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: + | "slh-dsa-sha2-128f" + | "slh-dsa-sha2-128s" + | "slh-dsa-sha2-192f" + | "slh-dsa-sha2-192s" + | "slh-dsa-sha2-256f" + | "slh-dsa-sha2-256s" + | "slh-dsa-shake-128f" + | "slh-dsa-shake-128s" + | "slh-dsa-shake-192f" + | "slh-dsa-shake-192s" + | "slh-dsa-shake-256f" + | "slh-dsa-shake-256s", + options: SLHDSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: + | "slh-dsa-sha2-128f" + | "slh-dsa-sha2-128s" + | "slh-dsa-sha2-192f" + | "slh-dsa-sha2-192s" + | "slh-dsa-sha2-256f" + | "slh-dsa-sha2-256s" + | "slh-dsa-shake-128f" + | "slh-dsa-shake-128s" + | "slh-dsa-shake-192f" + | "slh-dsa-shake-192s" + | "slh-dsa-shake-256f" + | "slh-dsa-shake-256s", + options?: SLHDSAKeyPairKeyObjectOptions, + ): KeyPairKeyObjectResult; + /** + * Generates a new asymmetric key pair of the given `type`. + * See the supported [asymmetric key types](https://nodejs.org/docs/latest-v24.x/api/crypto.html#asymmetric-key-types). + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if {@link KeyObject.export `keyObject.export()`} had been called on its result. Otherwise, + * the respective part of the key is returned as a {@link KeyObject `KeyObject`}. + * + * It is recommended to encode public keys as `'spki'` and private keys as `'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair, + * } = await import('node:crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and `publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type The asymmetric key type to generate. See the + * supported [asymmetric key types](https://nodejs.org/docs/latest-v24.x/api/crypto.html#asymmetric-key-types). + */ + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ml-kem-1024" | "ml-kem-512" | "ml-kem-768", + options: MLKEMKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ml-kem-1024" | "ml-kem-512" | "ml-kem-768", + options: MLKEMKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ml-kem-1024" | "ml-kem-512" | "ml-kem-768", + options: MLKEMKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ml-kem-1024" | "ml-kem-512" | "ml-kem-768", + options: MLKEMKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: NonSharedBuffer, privateKey: NonSharedBuffer) => void, + ): void; + function generateKeyPair( + type: "ml-kem-1024" | "ml-kem-512" | "ml-kem-768", + options: MLKEMKeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: + | "slh-dsa-sha2-128f" + | "slh-dsa-sha2-128s" + | "slh-dsa-sha2-192f" + | "slh-dsa-sha2-192s" + | "slh-dsa-sha2-256f" + | "slh-dsa-sha2-256s" + | "slh-dsa-shake-128f" + | "slh-dsa-shake-128s" + | "slh-dsa-shake-192f" + | "slh-dsa-shake-192s" + | "slh-dsa-shake-256f" + | "slh-dsa-shake-256s", + options: SLHDSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: + | "slh-dsa-sha2-128f" + | "slh-dsa-sha2-128s" + | "slh-dsa-sha2-192f" + | "slh-dsa-sha2-192s" + | "slh-dsa-sha2-256f" + | "slh-dsa-sha2-256s" + | "slh-dsa-shake-128f" + | "slh-dsa-shake-128s" + | "slh-dsa-shake-192f" + | "slh-dsa-shake-192s" + | "slh-dsa-shake-256f" + | "slh-dsa-shake-256s", + options: SLHDSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: + | "slh-dsa-sha2-128f" + | "slh-dsa-sha2-128s" + | "slh-dsa-sha2-192f" + | "slh-dsa-sha2-192s" + | "slh-dsa-sha2-256f" + | "slh-dsa-sha2-256s" + | "slh-dsa-shake-128f" + | "slh-dsa-shake-128s" + | "slh-dsa-shake-192f" + | "slh-dsa-shake-192s" + | "slh-dsa-shake-256f" + | "slh-dsa-shake-256s", + options: SLHDSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: + | "slh-dsa-sha2-128f" + | "slh-dsa-sha2-128s" + | "slh-dsa-sha2-192f" + | "slh-dsa-sha2-192s" + | "slh-dsa-sha2-256f" + | "slh-dsa-sha2-256s" + | "slh-dsa-shake-128f" + | "slh-dsa-shake-128s" + | "slh-dsa-shake-192f" + | "slh-dsa-shake-192s" + | "slh-dsa-shake-256f" + | "slh-dsa-shake-256s", + options: SLHDSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: + | "slh-dsa-sha2-128f" + | "slh-dsa-sha2-128s" + | "slh-dsa-sha2-192f" + | "slh-dsa-sha2-192s" + | "slh-dsa-sha2-256f" + | "slh-dsa-sha2-256s" + | "slh-dsa-shake-128f" + | "slh-dsa-shake-128s" + | "slh-dsa-shake-192f" + | "slh-dsa-shake-192s" + | "slh-dsa-shake-256f" + | "slh-dsa-shake-256s", + options: SLHDSAKeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + namespace generateKeyPair { + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "ed25519", + options?: ED25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__(type: "ed448", options?: ED448KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "x25519", + options?: X25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__(type: "x448", options?: X448KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options?: MLDSAKeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "ml-kem-1024" | "ml-kem-512" | "ml-kem-768", + options: MLKEMKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ml-kem-1024" | "ml-kem-512" | "ml-kem-768", + options: MLKEMKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "ml-kem-1024" | "ml-kem-512" | "ml-kem-768", + options: MLKEMKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: string; + }>; + function __promisify__( + type: "ml-kem-1024" | "ml-kem-512" | "ml-kem-768", + options: MLKEMKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: NonSharedBuffer; + privateKey: NonSharedBuffer; + }>; + function __promisify__( + type: "ml-kem-1024" | "ml-kem-512" | "ml-kem-768", + options?: MLKEMKeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: + | "slh-dsa-sha2-128f" + | "slh-dsa-sha2-128s" + | "slh-dsa-sha2-192f" + | "slh-dsa-sha2-192s" + | "slh-dsa-sha2-256f" + | "slh-dsa-sha2-256s" + | "slh-dsa-shake-128f" + | "slh-dsa-shake-128s" + | "slh-dsa-shake-192f" + | "slh-dsa-shake-192s" + | "slh-dsa-shake-256f" + | "slh-dsa-shake-256s", + options: SLHDSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: + | "slh-dsa-sha2-128f" + | "slh-dsa-sha2-128s" + | "slh-dsa-sha2-192f" + | "slh-dsa-sha2-192s" + | "slh-dsa-sha2-256f" + | "slh-dsa-sha2-256s" + | "slh-dsa-shake-128f" + | "slh-dsa-shake-128s" + | "slh-dsa-shake-192f" + | "slh-dsa-shake-192s" + | "slh-dsa-shake-256f" + | "slh-dsa-shake-256s", + options: SLHDSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: + | "slh-dsa-sha2-128f" + | "slh-dsa-sha2-128s" + | "slh-dsa-sha2-192f" + | "slh-dsa-sha2-192s" + | "slh-dsa-sha2-256f" + | "slh-dsa-sha2-256s" + | "slh-dsa-shake-128f" + | "slh-dsa-shake-128s" + | "slh-dsa-shake-192f" + | "slh-dsa-shake-192s" + | "slh-dsa-shake-256f" + | "slh-dsa-shake-256s", + options: SLHDSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: + | "slh-dsa-sha2-128f" + | "slh-dsa-sha2-128s" + | "slh-dsa-sha2-192f" + | "slh-dsa-sha2-192s" + | "slh-dsa-sha2-256f" + | "slh-dsa-sha2-256s" + | "slh-dsa-shake-128f" + | "slh-dsa-shake-128s" + | "slh-dsa-shake-192f" + | "slh-dsa-shake-192s" + | "slh-dsa-shake-256f" + | "slh-dsa-shake-256s", + options: SLHDSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: + | "slh-dsa-sha2-128f" + | "slh-dsa-sha2-128s" + | "slh-dsa-sha2-192f" + | "slh-dsa-sha2-192s" + | "slh-dsa-sha2-256f" + | "slh-dsa-sha2-256s" + | "slh-dsa-shake-128f" + | "slh-dsa-shake-128s" + | "slh-dsa-shake-192f" + | "slh-dsa-shake-192s" + | "slh-dsa-shake-256f" + | "slh-dsa-shake-256s", + options?: SLHDSAKeyPairKeyObjectOptions, + ): Promise; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type. + * + * `algorithm` is required to be `null` or `undefined` for Ed25519, Ed448, and + * ML-DSA. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + ): NonSharedBuffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + callback: (error: Error | null, data: NonSharedBuffer) => void, + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If + * `algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type. + * + * `algorithm` is required to be `null` or `undefined` for Ed25519, Ed448, and + * ML-DSA. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void, + ): void; + /** + * Key decapsulation using a KEM algorithm with a private key. + * + * Supported key types and their KEM algorithms are: + * + * * `'rsa'` RSA Secret Value Encapsulation + * * `'ec'` DHKEM(P-256, HKDF-SHA256), DHKEM(P-384, HKDF-SHA256), DHKEM(P-521, HKDF-SHA256) + * * `'x25519'` DHKEM(X25519, HKDF-SHA256) + * * `'x448'` DHKEM(X448, HKDF-SHA512) + * * `'ml-kem-512'` ML-KEM + * * `'ml-kem-768'` ML-KEM + * * `'ml-kem-1024'` ML-KEM + * + * If `key` is not a {@link KeyObject}, this function behaves as if `key` had been + * passed to `crypto.createPrivateKey()`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v24.7.0 + */ + function decapsulate( + key: KeyLike | PrivateKeyInput | JsonWebKeyInput, + ciphertext: ArrayBuffer | NodeJS.ArrayBufferView, + ): NonSharedBuffer; + function decapsulate( + key: KeyLike | PrivateKeyInput | JsonWebKeyInput, + ciphertext: ArrayBuffer | NodeJS.ArrayBufferView, + callback: (err: Error, sharedKey: NonSharedBuffer) => void, + ): void; + /** + * Computes the Diffie-Hellman shared secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType` and must support either the DH or + * ECDH operation. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): NonSharedBuffer; + function diffieHellman( + options: { privateKey: KeyObject; publicKey: KeyObject }, + callback: (err: Error | null, secret: NonSharedBuffer) => void, + ): void; + /** + * Key encapsulation using a KEM algorithm with a public key. + * + * Supported key types and their KEM algorithms are: + * + * * `'rsa'` RSA Secret Value Encapsulation + * * `'ec'` DHKEM(P-256, HKDF-SHA256), DHKEM(P-384, HKDF-SHA256), DHKEM(P-521, HKDF-SHA256) + * * `'x25519'` DHKEM(X25519, HKDF-SHA256) + * * `'x448'` DHKEM(X448, HKDF-SHA512) + * * `'ml-kem-512'` ML-KEM + * * `'ml-kem-768'` ML-KEM + * * `'ml-kem-1024'` ML-KEM + * + * If `key` is not a {@link KeyObject}, this function behaves as if `key` had been + * passed to `crypto.createPublicKey()`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v24.7.0 + */ + function encapsulate( + key: KeyLike | PublicKeyInput | JsonWebKeyInput, + ): { sharedKey: NonSharedBuffer; ciphertext: NonSharedBuffer }; + function encapsulate( + key: KeyLike | PublicKeyInput | JsonWebKeyInput, + callback: (err: Error, result: { sharedKey: NonSharedBuffer; ciphertext: NonSharedBuffer }) => void, + ): void; + interface OneShotDigestOptions { + /** + * Encoding used to encode the returned digest. + * @default 'hex' + */ + outputEncoding?: BinaryToTextEncoding | "buffer" | undefined; + /** + * For XOF hash functions such as 'shake256', the outputLength option + * can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + interface OneShotDigestOptionsWithStringEncoding extends OneShotDigestOptions { + outputEncoding?: BinaryToTextEncoding | undefined; + } + interface OneShotDigestOptionsWithBufferEncoding extends OneShotDigestOptions { + outputEncoding: "buffer"; + } + /** + * A utility for creating one-shot hash digests of data. It can be faster than + * the object-based `crypto.createHash()` when hashing a smaller amount of data + * (<= 5MB) that's readily available. If the data can be big or if it is streamed, + * it's still recommended to use `crypto.createHash()` instead. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * If `options` is a string, then it specifies the `outputEncoding`. + * + * Example: + * + * ```js + * import crypto from 'node:crypto'; + * import { Buffer } from 'node:buffer'; + * + * // Hashing a string and return the result as a hex-encoded string. + * const string = 'Node.js'; + * // 10b3493287f831e81a438811a1ffba01f8cec4b7 + * console.log(crypto.hash('sha1', string)); + * + * // Encode a base64-encoded string into a Buffer, hash it and return + * // the result as a buffer. + * const base64 = 'Tm9kZS5qcw=='; + * // + * console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer')); + * ``` + * @since v21.7.0, v20.12.0 + * @param data When `data` is a string, it will be encoded as UTF-8 before being hashed. If a different + * input encoding is desired for a string input, user could encode the string + * into a `TypedArray` using either `TextEncoder` or `Buffer.from()` and passing + * the encoded `TypedArray` into this API instead. + */ + function hash( + algorithm: string, + data: BinaryLike, + options?: OneShotDigestOptionsWithStringEncoding | BinaryToTextEncoding, + ): string; + function hash( + algorithm: string, + data: BinaryLike, + options: OneShotDigestOptionsWithBufferEncoding | "buffer", + ): NonSharedBuffer; + function hash( + algorithm: string, + data: BinaryLike, + options: OneShotDigestOptions | BinaryToTextEncoding | "buffer", + ): string | NonSharedBuffer; + type CipherMode = "cbc" | "ccm" | "cfb" | "ctr" | "ecb" | "gcm" | "ocb" | "ofb" | "stream" | "wrap" | "xts"; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdf, + * } = await import('node:crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf( + digest: string, + irm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: ArrayBuffer) => void, + ): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdfSync, + * } = await import('node:crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync( + digest: string, + ikm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + ): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + type UUID = `${string}-${string}-${string}-${string}-${string}`; + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0, v14.17.0 + */ + function randomUUID(options?: RandomUUIDOptions): UUID; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject?: "always" | "default" | "never" | undefined; + /** + * @default true + */ + wildcards?: boolean | undefined; + /** + * @default true + */ + partialWildcards?: boolean | undefined; + /** + * @default false + */ + multiLabelWildcards?: boolean | undefined; + /** + * @default false + */ + singleLabelSubdomains?: boolean | undefined; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('node:crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (CA) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * + * Because SHA-1 is cryptographically broken and because the security of SHA-1 is + * significantly worse than that of algorithms that are commonly used to sign + * certificates, consider using `x509.fingerprint256` instead. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The SHA-512 fingerprint of this certificate. + * + * Because computing the SHA-256 fingerprint is usually faster and because it is + * only half the size of the SHA-512 fingerprint, `x509.fingerprint256` may be + * a better choice. While SHA-512 presumably provides a higher level of security in + * general, the security of SHA-256 matches that of most algorithms that are + * commonly used to sign certificates. + * @since v17.2.0, v16.14.0 + */ + readonly fingerprint512: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate. + * + * This is a comma-separated list of subject alternative names. Each entry begins + * with a string identifying the kind of the subject alternative name followed by + * a colon and the value associated with the entry. + * + * Earlier versions of Node.js incorrectly assumed that it is safe to split this + * property at the two-character sequence `', '` (see [CVE-2021-44532](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532)). However, + * both malicious and legitimate certificates can contain subject alternative names + * that include this sequence when represented as a string. + * + * After the prefix denoting the type of the entry, the remainder of each entry + * might be enclosed in quotes to indicate that the value is a JSON string literal. + * For backward compatibility, Node.js only uses JSON string literals within this + * property when necessary to avoid ambiguity. Third-party code should be prepared + * to handle both possible entry formats. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * A textual representation of the certificate's authority information access + * extension. + * + * This is a line feed separated list of access descriptions. Each line begins with + * the access method and the kind of the access location, followed by a colon and + * the value associated with the access location. + * + * After the prefix denoting the access method and the kind of the access location, + * the remainder of each line might be enclosed in quotes to indicate that the + * value is a JSON string literal. For backward compatibility, Node.js only uses + * JSON string literals within this property when necessary to avoid ambiguity. + * Third-party code should be prepared to handle both possible entry formats. + * @since v15.6.0 + */ + readonly infoAccess: string | undefined; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate: X509Certificate | undefined; + /** + * The public key `KeyObject` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: NonSharedBuffer; + /** + * The serial number of this certificate. + * + * Serial numbers are assigned by certificate authorities and do not uniquely + * identify certificates. Consider using `x509.fingerprint256` as a unique + * identifier instead. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The algorithm used to sign the certificate or `undefined` if the signature algorithm is unknown by OpenSSL. + * @since v24.9.0 + */ + readonly signatureAlgorithm: string | undefined; + /** + * The OID of the algorithm used to sign the certificate. + * @since v24.9.0 + */ + readonly signatureAlgorithmOid: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time from which this certificate is valid, encapsulated in a `Date` object. + * @since v22.10.0 + */ + readonly validFromDate: Date; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + /** + * The date/time until which this certificate is valid, encapsulated in a `Date` object. + * @since v22.10.0 + */ + readonly validToDate: Date; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any email addresses. + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching email + * address, the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: Pick): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * + * If the certificate matches the given host name, the matching subject name is + * returned. The returned name might be an exact match (e.g., `foo.example.com`) + * or it might contain wildcards (e.g., `*.example.com`). Because host name + * comparisons are case-insensitive, the returned subject name might also differ + * from the given `name` in capitalization. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS"). + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching DNS name, + * the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * + * Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they + * must match the given `ip` address exactly. Other subject alternative names as + * well as the subject field of the certificate are ignored. + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string): string | undefined; + /** + * Checks whether this certificate was potentially issued by the given `otherCert` + * by comparing the certificate metadata. + * + * This is useful for pruning a list of possible issuer certificates which have been + * selected using a more rudimentary filtering routine, i.e. just based on subject + * and issuer names. + * + * Finally, to verify that this certificate's signature was produced by a private key + * corresponding to `otherCert`'s public key use `x509.verify(publicKey)` + * with `otherCert`'s public key represented as a `KeyObject` + * like so + * + * ```js + * if (!x509.verify(otherCert.publicKey)) { + * throw new Error('otherCert did not issue x509'); + * } + * ``` + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsBigInt, + callback: (err: Error | null, prime: bigint) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsArrayBuffer, + callback: (err: Error | null, prime: ArrayBuffer) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptions, + callback: (err: Error | null, prime: ArrayBuffer | bigint) => void, + ): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most `2**-64` for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime( + value: LargeNumberLike, + options: CheckPrimeOptions, + callback: (err: Error | null, result: boolean) => void, + ): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + /** + * Load and set the `engine` for some or all OpenSSL functions (selected by flags). + * + * `engine` could be either an id or a path to the engine's shared library. + * + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`): + * + * * `crypto.constants.ENGINE_METHOD_RSA` + * * `crypto.constants.ENGINE_METHOD_DSA` + * * `crypto.constants.ENGINE_METHOD_DH` + * * `crypto.constants.ENGINE_METHOD_RAND` + * * `crypto.constants.ENGINE_METHOD_EC` + * * `crypto.constants.ENGINE_METHOD_CIPHERS` + * * `crypto.constants.ENGINE_METHOD_DIGESTS` + * * `crypto.constants.ENGINE_METHOD_PKEY_METHS` + * * `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` + * * `crypto.constants.ENGINE_METHOD_ALL` + * * `crypto.constants.ENGINE_METHOD_NONE` + * @since v0.11.11 + * @param flags + */ + function setEngine(engine: string, flags?: number): void; + /** + * A convenient alias for {@link webcrypto.getRandomValues}. This + * implementation is not compliant with the Web Crypto spec, to write + * web-compatible code use {@link webcrypto.getRandomValues} instead. + * @since v17.4.0 + * @return Returns `typedArray`. + */ + function getRandomValues(typedArray: T): T; + type Argon2Algorithm = "argon2d" | "argon2i" | "argon2id"; + interface Argon2Parameters { + /** + * REQUIRED, this is the password for password hashing applications of Argon2. + */ + message: string | ArrayBuffer | NodeJS.ArrayBufferView; + /** + * REQUIRED, must be at least 8 bytes long. This is the salt for password hashing applications of Argon2. + */ + nonce: string | ArrayBuffer | NodeJS.ArrayBufferView; + /** + * REQUIRED, degree of parallelism determines how many computational chains (lanes) + * can be run. Must be greater than 1 and less than `2**24-1`. + */ + parallelism: number; + /** + * REQUIRED, the length of the key to generate. Must be greater than 4 and + * less than `2**32-1`. + */ + tagLength: number; + /** + * REQUIRED, memory cost in 1KiB blocks. Must be greater than + * `8 * parallelism` and less than `2**32-1`. The actual number of blocks is rounded + * down to the nearest multiple of `4 * parallelism`. + */ + memory: number; + /** + * REQUIRED, number of passes (iterations). Must be greater than 1 and less + * than `2**32-1`. + */ + passes: number; + /** + * OPTIONAL, Random additional input, + * similar to the salt, that should **NOT** be stored with the derived key. This is known as pepper in + * password hashing applications. If used, must have a length not greater than `2**32-1` bytes. + */ + secret?: string | ArrayBuffer | NodeJS.ArrayBufferView | undefined; + /** + * OPTIONAL, Additional data to + * be added to the hash, functionally equivalent to salt or secret, but meant for + * non-random data. If used, must have a length not greater than `2**32-1` bytes. + */ + associatedData?: string | ArrayBuffer | NodeJS.ArrayBufferView | undefined; + } + /** + * Provides an asynchronous [Argon2](https://www.rfc-editor.org/rfc/rfc9106.html) implementation. Argon2 is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `nonce` should be as unique as possible. It is recommended that a nonce is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `message`, `nonce`, `secret` or `associatedData`, please + * consider [caveats when using strings as inputs to cryptographic APIs](https://nodejs.org/docs/latest-v24.x/api/crypto.html#using-strings-as-inputs-to-cryptographic-apis). + * + * The `callback` function is called with two arguments: `err` and `derivedKey`. + * `err` is an exception object when key derivation fails, otherwise `err` is + * `null`. `derivedKey` is passed to the callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { argon2, randomBytes } = await import('node:crypto'); + * + * const parameters = { + * message: 'password', + * nonce: randomBytes(16), + * parallelism: 4, + * tagLength: 64, + * memory: 65536, + * passes: 3, + * }; + * + * argon2('argon2id', parameters, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // 'af91dad...9520f15' + * }); + * ``` + * @since v24.7.0 + * @param algorithm Variant of Argon2, one of `"argon2d"`, `"argon2i"` or `"argon2id"`. + * @experimental + */ + function argon2( + algorithm: Argon2Algorithm, + parameters: Argon2Parameters, + callback: (err: Error | null, derivedKey: NonSharedBuffer) => void, + ): void; + /** + * Provides a synchronous [Argon2][] implementation. Argon2 is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `nonce` should be as unique as possible. It is recommended that a nonce is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `message`, `nonce`, `secret` or `associatedData`, please + * consider [caveats when using strings as inputs to cryptographic APIs](https://nodejs.org/docs/latest-v24.x/api/crypto.html#using-strings-as-inputs-to-cryptographic-apis). + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { argon2Sync, randomBytes } = await import('node:crypto'); + * + * const parameters = { + * message: 'password', + * nonce: randomBytes(16), + * parallelism: 4, + * tagLength: 64, + * memory: 65536, + * passes: 3, + * }; + * + * const derivedKey = argon2Sync('argon2id', parameters); + * console.log(derivedKey.toString('hex')); // 'af91dad...9520f15' + * ``` + * @since v24.7.0 + * @experimental + */ + function argon2Sync(algorithm: Argon2Algorithm, parameters: Argon2Parameters): NonSharedBuffer; + /** + * A convenient alias for `crypto.webcrypto.subtle`. + * @since v17.4.0 + */ + const subtle: webcrypto.SubtleCrypto; + /** + * An implementation of the Web Crypto API standard. + * + * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details. + * @since v15.0.0 + */ + const webcrypto: webcrypto.Crypto; + namespace webcrypto { + type BufferSource = ArrayBufferView | ArrayBuffer; + type KeyFormat = "jwk" | "pkcs8" | "raw" | "raw-public" | "raw-secret" | "raw-seed" | "spki"; + type KeyType = "private" | "public" | "secret"; + type KeyUsage = + | "encrypt" + | "decrypt" + | "sign" + | "verify" + | "deriveKey" + | "deriveBits" + | "encapsulateBits" + | "decapsulateBits" + | "encapsulateKey" + | "decapsulateKey" + | "wrapKey" + | "unwrapKey"; + type AlgorithmIdentifier = Algorithm | string; + type HashAlgorithmIdentifier = AlgorithmIdentifier; + type NamedCurve = string; + type BigInteger = Uint8Array; + interface AeadParams extends Algorithm { + additionalData?: BufferSource; + iv: BufferSource; + tagLength: number; + } + interface AesCbcParams extends Algorithm { + iv: BufferSource; + } + interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; + } + interface AesDerivedKeyParams extends Algorithm { + length: number; + } + // TODO: remove in next major + /** @deprecated Replaced by `AeadParams`. */ + interface AesGcmParams extends Algorithm { + additionalData?: BufferSource; + iv: BufferSource; + tagLength?: number; + } + interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface AesKeyGenParams extends Algorithm { + length: number; + } + interface Algorithm { + name: string; + } + interface Argon2Params extends Algorithm { + associatedData?: BufferSource; + memory: number; + nonce: BufferSource; + parallelism: number; + passes: number; + secretValue?: BufferSource; + version?: number; + } + interface CShakeParams extends Algorithm { + customization?: BufferSource; + functionName?: BufferSource; + length: number; + } + interface ContextParams extends Algorithm { + context?: BufferSource; + } + interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; + } + interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; + } + interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: BufferSource; + salt: BufferSource; + } + interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; + } + interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; + } + interface KeyAlgorithm { + name: string; + } + interface KmacImportParams extends Algorithm { + length?: number; + } + interface KmacKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface KmacKeyGenParams extends Algorithm { + length?: number; + } + interface KmacParams extends Algorithm { + customization?: BufferSource; + length: number; + } + interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: BufferSource; + } + interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; + } + interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; + } + interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaOaepParams extends Algorithm { + label?: BufferSource; + } + interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; + } + interface RsaPssParams extends Algorithm { + saltLength: number; + } + /** + * Importing the `webcrypto` object (`import { webcrypto } from 'node:crypto'`) gives an instance of the `Crypto` class. + * `Crypto` is a singleton that provides access to the remainder of the crypto API. + * @since v15.0.0 + */ + interface Crypto { + /** + * Provides access to the `SubtleCrypto` API. + * @since v15.0.0 + */ + readonly subtle: SubtleCrypto; + /** + * Generates cryptographically strong random values. + * The given `typedArray` is filled with random values, and a reference to `typedArray` is returned. + * + * The given `typedArray` must be an integer-based instance of {@link NodeJS.TypedArray}, i.e. `Float32Array` and `Float64Array` are not accepted. + * + * An error will be thrown if the given `typedArray` is larger than 65,536 bytes. + * @since v15.0.0 + */ + getRandomValues>( + typedArray: T, + ): T; + /** + * Generates a random {@link https://www.rfc-editor.org/rfc/rfc4122.txt RFC 4122} version 4 UUID. + * The UUID is generated using a cryptographic pseudorandom number generator. + * @since v16.7.0 + */ + randomUUID(): UUID; + } + /** + * @since v15.0.0 + */ + interface CryptoKey { + /** + * An object detailing the algorithm for which the key can be used along with additional algorithm-specific parameters. + * @since v15.0.0 + */ + readonly algorithm: KeyAlgorithm; + /** + * When `true`, the {@link CryptoKey} can be extracted using either `subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`. + * @since v15.0.0 + */ + readonly extractable: boolean; + /** + * A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key. + * @since v15.0.0 + */ + readonly type: KeyType; + /** + * An array of strings identifying the operations for which the key may be used. + * + * The possible usages are: + * - `'encrypt'` - The key may be used to encrypt data. + * - `'decrypt'` - The key may be used to decrypt data. + * - `'sign'` - The key may be used to generate digital signatures. + * - `'verify'` - The key may be used to verify digital signatures. + * - `'deriveKey'` - The key may be used to derive a new key. + * - `'deriveBits'` - The key may be used to derive bits. + * - `'wrapKey'` - The key may be used to wrap another key. + * - `'unwrapKey'` - The key may be used to unwrap another key. + * + * Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`). + * @since v15.0.0 + */ + readonly usages: KeyUsage[]; + } + /** + * The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair. + * @since v15.0.0 + */ + interface CryptoKeyPair { + /** + * A {@link CryptoKey} whose type will be `'private'`. + * @since v15.0.0 + */ + privateKey: CryptoKey; + /** + * A {@link CryptoKey} whose type will be `'public'`. + * @since v15.0.0 + */ + publicKey: CryptoKey; + } + interface EncapsulatedBits { + sharedKey: ArrayBuffer; + ciphertext: ArrayBuffer; + } + interface EncapsulatedKey { + sharedKey: CryptoKey; + ciphertext: ArrayBuffer; + } + /** + * @since v15.0.0 + */ + interface SubtleCrypto { + /** + * A message recipient uses their asymmetric private key to decrypt an + * "encapsulated key" (ciphertext), thereby recovering a temporary symmetric + * key (represented as `ArrayBuffer`) which is then used to decrypt a message. + * + * The algorithms currently supported include: + * + * * `'ML-KEM-512'` + * * `'ML-KEM-768'` + * * `'ML-KEM-1024'` + * @since v24.7.0 + * @returns Fulfills with `ArrayBuffer` upon success. + */ + decapsulateBits( + decapsulationAlgorithm: AlgorithmIdentifier, + decapsulationKey: CryptoKey, + ciphertext: BufferSource, + ): Promise; + /** + * A message recipient uses their asymmetric private key to decrypt an + * "encapsulated key" (ciphertext), thereby recovering a temporary symmetric + * key (represented as `CryptoKey`) which is then used to decrypt a message. + * + * The algorithms currently supported include: + * + * * `'ML-KEM-512'` + * * `'ML-KEM-768'` + * * `'ML-KEM-1024'` + * @since v24.7.0 + * @param usages See [Key usages](https://nodejs.org/docs/latest-v24.x/api/webcrypto.html#cryptokeyusages). + * @returns Fulfills with `CryptoKey` upon success. + */ + decapsulateKey( + decapsulationAlgorithm: AlgorithmIdentifier, + decapsulationKey: CryptoKey, + ciphertext: BufferSource, + sharedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | AesDerivedKeyParams | KmacImportParams, + extractable: boolean, + usages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `key`, + * this method attempts to decipher the provided `data`. If successful, + * the returned promise will be resolved with an `` containing the plaintext result. + * + * The algorithms currently supported include: + * + * * `'AES-CBC'` + * * `'AES-CTR'` + * * `'AES-GCM'` + * * `'AES-OCB'` + * * `'ChaCha20-Poly1305'` + * * `'RSA-OAEP'` + * @since v15.0.0 + */ + decrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AeadParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `baseKey`, + * this method attempts to generate `length` bits. + * The Node.js implementation requires that when `length` is a number it must be multiple of `8`. + * When `length` is `null` the maximum number of bits for a given algorithm is generated. This is allowed + * for the `'ECDH'`, `'X25519'`, and `'X448'` algorithms. + * If successful, the returned promise will be resolved with an `` containing the generated data. + * + * The algorithms currently supported include: + * + * * `'Argon2d'` + * * `'Argon2i'` + * * `'Argon2id'` + * * `'ECDH'` + * * `'HKDF'` + * * `'PBKDF2'` + * * `'X25519'` + * * `'X448'` + * @since v15.0.0 + */ + deriveBits( + algorithm: EcdhKeyDeriveParams, + baseKey: CryptoKey, + length?: number | null, + ): Promise; + deriveBits( + algorithm: EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params | Argon2Params, + baseKey: CryptoKey, + length: number, + ): Promise; + /** + * Using the method and parameters specified in `algorithm`, and the keying material provided by `baseKey`, + * this method attempts to generate a new ` based on the method and parameters in `derivedKeyAlgorithm`. + * + * Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to generate raw keying material, + * then passing the result into the `subtle.importKey()` method using the `deriveKeyAlgorithm`, `extractable`, and `keyUsages` parameters as input. + * + * The algorithms currently supported include: + * + * * `'Argon2d'` + * * `'Argon2i'` + * * `'Argon2id'` + * * `'ECDH'` + * * `'HKDF'` + * * `'PBKDF2'` + * * `'X25519'` + * * `'X448'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + deriveKey( + algorithm: EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params | Argon2Params, + baseKey: CryptoKey, + derivedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | AesDerivedKeyParams | KmacImportParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + /** + * Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`. + * If successful, the returned promise is resolved with an `` containing the computed digest. + * + * If `algorithm` is provided as a ``, it must be one of: + * + * * `'cSHAKE128'` + * * `'cSHAKE256'` + * * `'SHA-1'` + * * `'SHA-256'` + * * `'SHA-384'` + * * `'SHA-512'` + * * `'SHA3-256'` + * * `'SHA3-384'` + * * `'SHA3-512'` + * + * If `algorithm` is provided as an ``, it must have a `name` property whose value is one of the above. + * @since v15.0.0 + */ + digest(algorithm: AlgorithmIdentifier | CShakeParams, data: BufferSource): Promise; + /** + * Uses a message recipient's asymmetric public key to encrypt a temporary symmetric key. + * This encrypted key is the "encapsulated key" represented as `EncapsulatedBits`. + * + * The algorithms currently supported include: + * + * * `'ML-KEM-512'` + * * `'ML-KEM-768'` + * * `'ML-KEM-1024'` + * @since v24.7.0 + * @returns Fulfills with `EncapsulatedBits` upon success. + */ + encapsulateBits( + encapsulationAlgorithm: AlgorithmIdentifier, + encapsulationKey: CryptoKey, + ): Promise; + /** + * Uses a message recipient's asymmetric public key to encrypt a temporary symmetric key. + * This encrypted key is the "encapsulated key" represented as `EncapsulatedKey`. + * + * The algorithms currently supported include: + * + * * `'ML-KEM-512'` + * * `'ML-KEM-768'` + * * `'ML-KEM-1024'` + * @since v24.7.0 + * @param usages See [Key usages](https://nodejs.org/docs/latest-v24.x/api/webcrypto.html#cryptokeyusages). + * @returns Fulfills with `EncapsulatedKey` upon success. + */ + encapsulateKey( + encapsulationAlgorithm: AlgorithmIdentifier, + encapsulationKey: CryptoKey, + sharedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | AesDerivedKeyParams | KmacImportParams, + extractable: boolean, + usages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters specified by `algorithm` and the keying material provided by `key`, + * this method attempts to encipher `data`. If successful, + * the returned promise is resolved with an `` containing the encrypted result. + * + * The algorithms currently supported include: + * + * * `'AES-CBC'` + * * `'AES-CTR'` + * * `'AES-GCM'` + * * `'AES-OCB'` + * * `'ChaCha20-Poly1305'` + * * `'RSA-OAEP'` + * @since v15.0.0 + */ + encrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AeadParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Exports the given key into the specified format, if supported. + * + * If the `` is not extractable, the returned promise will reject. + * + * When `format` is either `'pkcs8'` or `'spki'` and the export is successful, + * the returned promise will be resolved with an `` containing the exported key data. + * + * When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a + * JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, `'jwk'`, `'raw-secret'`, + * `'raw-public'`, or `'raw-seed'`. + * @returns `` containing ``. + * @since v15.0.0 + */ + exportKey(format: "jwk", key: CryptoKey): Promise; + exportKey(format: Exclude, key: CryptoKey): Promise; + /** + * Using the parameters provided in `algorithm`, this method + * attempts to generate new keying material. Depending on the algorithm used + * either a single `CryptoKey` or a `CryptoKeyPair` is generated. + * + * The `CryptoKeyPair` (public and private key) generating algorithms supported + * include: + * + * * `'ECDH'` + * * `'ECDSA'` + * * `'Ed25519'` + * * `'Ed448'` + * * `'ML-DSA-44'` + * * `'ML-DSA-65'` + * * `'ML-DSA-87'` + * * `'ML-KEM-512'` + * * `'ML-KEM-768'` + * * `'ML-KEM-1024'` + * * `'RSA-OAEP'` + * * `'RSA-PSS'` + * * `'RSASSA-PKCS1-v1_5'` + * * `'X25519'` + * * `'X448'` + * + * The `CryptoKey` (secret key) generating algorithms supported include: + * * `'AES-CBC'` + * * `'AES-CTR'` + * * `'AES-GCM'` + * * `'AES-KW'` + * * `'AES-OCB'` + * * `'ChaCha20-Poly1305'` + * * `'HMAC'` + * * `'KMAC128'` + * * `'KMAC256'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + generateKey( + algorithm: RsaHashedKeyGenParams | EcKeyGenParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params | KmacKeyGenParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AlgorithmIdentifier, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Derives the public key from a given private key. + * @since v24.7.0 + * @param key A private key from which to derive the corresponding public key. + * @param keyUsages See [Key usages](https://nodejs.org/docs/latest-v24.x/api/webcrypto.html#cryptokeyusages). + * @returns Fulfills with a `CryptoKey` upon success. + */ + getPublicKey(key: CryptoKey, keyUsages: KeyUsage[]): Promise; + /** + * This method attempts to interpret the provided `keyData` + * as the given `format` to create a `CryptoKey` instance using the provided + * `algorithm`, `extractable`, and `keyUsages` arguments. If the import is + * successful, the returned promise will be resolved with a {CryptoKey} + * representation of the key material. + * + * If importing KDF algorithm keys, `extractable` must be `false`. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, `'jwk'`, `'raw-secret'`, + * `'raw-public'`, or `'raw-seed'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + importKey( + format: "jwk", + keyData: JsonWebKey, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm + | KmacImportParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + importKey( + format: Exclude, + keyData: BufferSource, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm + | KmacImportParams, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given by `algorithm` and the keying material provided by `key`, + * this method attempts to generate a cryptographic signature of `data`. If successful, + * the returned promise is resolved with an `` containing the generated signature. + * + * The algorithms currently supported include: + * + * * `'ECDSA'` + * * `'Ed25519'` + * * `'Ed448'` + * * `'HMAC'` + * * `'KMAC128'` + * * `'KMAC256'` + * * `'ML-DSA-44'` + * * `'ML-DSA-65'` + * * `'ML-DSA-87'` + * * `'RSA-PSS'` + * * `'RSASSA-PKCS1-v1_5'` + * @since v15.0.0 + */ + sign( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | ContextParams | KmacParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * This method attempts to decrypt a wrapped key and create a `` instance. + * It is equivalent to calling `subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`, `unwrapAlgo`, and `unwrappingKey` arguments as input) + * then passing the results in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`, `extractable`, and `keyUsages` arguments as inputs. + * If successful, the returned promise is resolved with a `` object. + * + * The wrapping algorithms currently supported include: + * + * * `'AES-CBC'` + * * `'AES-CTR'` + * * `'AES-GCM'` + * * `'AES-KW'` + * * `'AES-OCB'` + * * `'ChaCha20-Poly1305'` + * * `'RSA-OAEP'` + * + * The unwrapped key algorithms supported include: + * + * * `'AES-CBC'` + * * `'AES-CTR'` + * * `'AES-GCM'` + * * `'AES-KW'` + * * `'AES-OCB'` + * * `'ChaCha20-Poly1305'` + * * `'ECDH'` + * * `'ECDSA'` + * * `'Ed25519'` + * * `'Ed448'` + * * `'HMAC'` + * * `'KMAC128'` + * * `'KMAC256'` + * * `'ML-DSA-44'` + * * `'ML-DSA-65'` + * * `'ML-DSA-87'` + * * `'ML-KEM-512'` + * * `'ML-KEM-768'` + * * `'ML-KEM-1024'` + * * `'RSA-OAEP'` + * * `'RSA-PSS'` + * * `'RSASSA-PKCS1-v1_5'` + * * `'X25519'` + * * `'X448'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, `'jwk'`, `'raw-secret'`, + * `'raw-public'`, or `'raw-seed'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + unwrapKey( + format: KeyFormat, + wrappedKey: BufferSource, + unwrappingKey: CryptoKey, + unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AeadParams, + unwrappedKeyAlgorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm + | KmacImportParams, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given in `algorithm` and the keying material provided by `key`, + * This method attempts to verify that `signature` is a valid cryptographic signature of `data`. + * The returned promise is resolved with either `true` or `false`. + * + * The algorithms currently supported include: + * + * * `'ECDSA'` + * * `'Ed25519'` + * * `'Ed448'` + * * `'HMAC'` + * * `'KMAC128'` + * * `'KMAC256'` + * * `'ML-DSA-44'` + * * `'ML-DSA-65'` + * * `'ML-DSA-87'` + * * `'RSA-PSS'` + * * `'RSASSA-PKCS1-v1_5'` + * @since v15.0.0 + */ + verify( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | ContextParams | KmacParams, + key: CryptoKey, + signature: BufferSource, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * This method exports the keying material into the format identified by `format`, + * then encrypts it using the method and parameters specified by `wrapAlgo` and the keying material provided by `wrappingKey`. + * It is the equivalent to calling `subtle.exportKey()` using `format` and `key` as the arguments, + * then passing the result to the `subtle.encrypt()` method using `wrappingKey` and `wrapAlgo` as inputs. + * If successful, the returned promise will be resolved with an `` containing the encrypted key data. + * + * The wrapping algorithms currently supported include: + * + * * `'AES-CBC'` + * * `'AES-CTR'` + * * `'AES-GCM'` + * * `'AES-KW'` + * * `'AES-OCB'` + * * `'ChaCha20-Poly1305'` + * * `'RSA-OAEP'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, `'jwk'`, `'raw-secret'`, + * `'raw-public'`, or `'raw-seed'`. + * @since v15.0.0 + */ + wrapKey( + format: KeyFormat, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AeadParams, + ): Promise; + } + } +} +declare module "node:crypto" { + export * from "crypto"; +} diff --git a/tools/ui/node_modules/@types/node/dgram.d.ts b/tools/ui/node_modules/@types/node/dgram.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc69f0b48e1a5ad641af078a098df62410cb135a --- /dev/null +++ b/tools/ui/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,600 @@ +/** + * The `node:dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/dgram.js) + */ +declare module "dgram" { + import { NonSharedBuffer } from "node:buffer"; + import { AddressInfo, BlockList } from "node:net"; + import * as dns from "node:dns"; + import { Abortable, EventEmitter } from "node:events"; + interface RemoteInfo { + address: string; + family: "IPv4" | "IPv6"; + port: number; + size: number; + } + interface BindOptions { + port?: number | undefined; + address?: string | undefined; + exclusive?: boolean | undefined; + fd?: number | undefined; + } + type SocketType = "udp4" | "udp6"; + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean | undefined; + reusePort?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + recvBufferSize?: number | undefined; + sendBufferSize?: number | undefined; + lookup?: + | (( + hostname: string, + options: dns.LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ) => void) + | undefined; + receiveBlockList?: BlockList | undefined; + sendBlockList?: BlockList | undefined; + } + /** + * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram + * messages. When `address` and `port` are not passed to `socket.bind()` the + * method will bind the socket to the "all interfaces" address on a random port + * (it does the right thing for both `udp4` and `udp6` sockets). The bound address + * and port can be retrieved using `socket.address().address` and `socket.address().port`. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.close()` on the socket: + * + * ```js + * const controller = new AbortController(); + * const { signal } = controller; + * const server = dgram.createSocket({ type: 'udp4', signal }); + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * // Later, when you want to close the server. + * controller.abort(); + * ``` + * @since v0.11.13 + * @param options Available options are: + * @param callback Attached as a listener for `'message'` events. Optional. + */ + function createSocket(type: SocketType, callback?: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): Socket; + /** + * Encapsulates the datagram functionality. + * + * New instances of `dgram.Socket` are created using {@link createSocket}. + * The `new` keyword is not to be used to create `dgram.Socket` instances. + * @since v0.1.99 + */ + class Socket extends EventEmitter { + /** + * Tells the kernel to join a multicast group at the given `multicastAddress` and `multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the `multicastInterface` argument is not + * specified, the operating system will choose + * one interface and will add membership to it. To add membership to every + * available interface, call `addMembership` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * + * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: + * + * ```js + * import cluster from 'node:cluster'; + * import dgram from 'node:dgram'; + * + * if (cluster.isPrimary) { + * cluster.fork(); // Works ok. + * cluster.fork(); // Fails with EADDRINUSE. + * } else { + * const s = dgram.createSocket('udp4'); + * s.bind(1234, () => { + * s.addMembership('224.0.0.114'); + * }); + * } + * ``` + * @since v0.6.9 + */ + addMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * Returns an object containing the address information for a socket. + * For UDP sockets, this object will contain `address`, `family`, and `port` properties. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.99 + */ + address(): AddressInfo; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address`. If `port` is not + * specified or is `0`, the operating system will attempt to bind to a + * random port. If `address` is not specified, the operating system will + * attempt to listen on all addresses. Once binding is complete, a `'listening'` event is emitted and the optional `callback` function is + * called. + * + * Specifying both a `'listening'` event listener and passing a `callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * Example of a UDP server listening on port 41234: + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @since v0.1.99 + * @param callback with no parameters. Called when binding is complete. + */ + bind(port?: number, address?: string, callback?: () => void): this; + bind(port?: number, callback?: () => void): this; + bind(callback?: () => void): this; + bind(options: BindOptions, callback?: () => void): this; + /** + * Close the underlying socket and stop listening for data on it. If a callback is + * provided, it is added as a listener for the `'close'` event. + * @since v0.1.99 + * @param callback Called when the socket has been closed. + */ + close(callback?: () => void): this; + /** + * Associates the `dgram.Socket` to a remote address and port. Every + * message sent by this handle is automatically sent to that destination. Also, + * the socket will only receive messages from that remote peer. + * Trying to call `connect()` on an already connected socket will result + * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not + * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) + * will be used by default. Once the connection is complete, a `'connect'` event + * is emitted and the optional `callback` function is called. In case of failure, + * the `callback` is called or, failing this, an `'error'` event is emitted. + * @since v12.0.0 + * @param callback Called when the connection is completed or on error. + */ + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + /** + * A synchronous function that disassociates a connected `dgram.Socket` from + * its remote address. Trying to call `disconnect()` on an unbound or already + * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. + * @since v12.0.0 + */ + disconnect(): void; + /** + * Instructs the kernel to leave a multicast group at `multicastAddress` using the `IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * kernel when the socket is closed or the process terminates, so most apps will + * never have reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v0.6.9 + */ + dropMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_RCVBUF` socket receive buffer size in bytes. + */ + getRecvBufferSize(): number; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_SNDBUF` socket send buffer size in bytes. + */ + getSendBufferSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of bytes queued for sending. + */ + getSendQueueSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of send requests currently in the queue awaiting to be processed. + */ + getSendQueueCount(): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active. The `socket.ref()` method adds the socket back to the reference + * counting and restores the default behavior. + * + * Calling `socket.ref()` multiples times will have no additional effect. + * + * The `socket.ref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + ref(): this; + /** + * Returns an object containing the `address`, `family`, and `port` of the remote + * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception + * if the socket is not connected. + * @since v12.0.0 + */ + remoteAddress(): AddressInfo; + /** + * Broadcasts a datagram on the socket. + * For connectionless sockets, the destination `port` and `address` must be + * specified. Connected sockets, on the other hand, will use their associated + * remote endpoint, so the `port` and `address` arguments must not be set. + * + * The `msg` argument contains the message to be sent. + * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, + * any `TypedArray` or a `DataView`, + * the `offset` and `length` specify the offset within the `Buffer` where the + * message begins and the number of bytes in the message, respectively. + * If `msg` is a `String`, then it is automatically converted to a `Buffer` with `'utf8'` encoding. With messages that + * contain multi-byte characters, `offset` and `length` will be calculated with + * respect to `byte length` and not the character position. + * If `msg` is an array, `offset` and `length` must not be specified. + * + * The `address` argument is a string. If the value of `address` is a host name, + * DNS will be used to resolve the address of the host. If `address` is not + * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) will be used by default. + * + * If the socket has not been previously bound with a call to `bind`, the socket + * is assigned a random port number and is bound to the "all interfaces" address + * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + * + * An optional `callback` function may be specified to as a way of reporting + * DNS errors or for determining when it is safe to reuse the `buf` object. + * DNS lookups delay the time to send for at least one tick of the + * Node.js event loop. + * + * The only way to know for sure that the datagram has been sent is by using a `callback`. If an error occurs and a `callback` is given, the error will be + * passed as the first argument to the `callback`. If a `callback` is not given, + * the error is emitted as an `'error'` event on the `socket` object. + * + * Offset and length are optional but both _must_ be set if either are used. + * They are supported only when the first argument is a `Buffer`, a `TypedArray`, + * or a `DataView`. + * + * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. + * + * Example of sending a UDP packet to a port on `localhost`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.send(message, 41234, 'localhost', (err) => { + * client.close(); + * }); + * ``` + * + * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('Some '); + * const buf2 = Buffer.from('bytes'); + * const client = dgram.createSocket('udp4'); + * client.send([buf1, buf2], 41234, (err) => { + * client.close(); + * }); + * ``` + * + * Sending multiple buffers might be faster or slower depending on the + * application and operating system. Run benchmarks to + * determine the optimal strategy on a case-by-case basis. Generally speaking, + * however, sending multiple buffers is faster. + * + * Example of sending a UDP packet using a socket connected to a port on `localhost`: + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.connect(41234, 'localhost', (err) => { + * client.send(message, (err) => { + * client.close(); + * }); + * }); + * ``` + * @since v0.1.99 + * @param msg Message to be sent. + * @param offset Offset in the buffer where the message starts. + * @param length Number of bytes in the message. + * @param port Destination port. + * @param address Destination host name or IP address. + * @param callback Called when the message has been sent. + */ + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + /** + * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP + * packets may be sent to a local interface's broadcast address. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.6.9 + */ + setBroadcast(flag: boolean): void; + /** + * _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC + * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ + * _with a scope index is written as `'IP%scope'` where scope is an interface name_ + * _or interface number._ + * + * Sets the default outgoing multicast interface of the socket to a chosen + * interface or back to system interface selection. The `multicastInterface` must + * be a valid string representation of an IP from the socket's family. + * + * For IPv4 sockets, this should be the IP configured for the desired physical + * interface. All packets sent to multicast on the socket will be sent on the + * interface determined by the most recent successful use of this call. + * + * For IPv6 sockets, `multicastInterface` should include a scope to indicate the + * interface as in the examples that follow. In IPv6, individual `send` calls can + * also use explicit scope in addresses, so only packets sent to a multicast + * address without specifying an explicit scope are affected by the most recent + * successful use of this call. + * + * This method throws `EBADF` if called on an unbound socket. + * + * #### Example: IPv6 outgoing multicast interface + * + * On most systems, where scope format uses the interface name: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%eth1'); + * }); + * ``` + * + * On Windows, where scope format uses an interface number: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%2'); + * }); + * ``` + * + * #### Example: IPv4 outgoing multicast interface + * + * All systems use an IP of the host on the desired physical interface: + * + * ```js + * const socket = dgram.createSocket('udp4'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('10.0.0.2'); + * }); + * ``` + * @since v8.6.0 + */ + setMulticastInterface(multicastInterface: string): void; + /** + * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, + * multicast packets will also be received on the local interface. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastLoopback(flag: boolean): boolean; + /** + * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for + * "Time to Live", in this context it specifies the number of IP hops that a + * packet is allowed to travel through, specifically for multicast traffic. Each + * router or gateway that forwards a packet decrements the TTL. If the TTL is + * decremented to 0 by a router, it will not be forwarded. + * + * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastTTL(ttl: number): number; + /** + * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setRecvBufferSize(size: number): void; + /** + * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setSendBufferSize(size: number): void; + /** + * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", + * in this context it specifies the number of IP hops that a packet is allowed to + * travel through. Each router or gateway that forwards a packet decrements the + * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + * Changing TTL values is typically done for network probes or when multicasting. + * + * The `ttl` argument may be between 1 and 255\. The default on most systems + * is 64. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.101 + */ + setTTL(ttl: number): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active, allowing the process to exit even if the socket is still + * listening. + * + * Calling `socket.unref()` multiple times will have no additional effect. + * + * The `socket.unref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given `sourceAddress` and `groupAddress`, using the `multicastInterface` with the `IP_ADD_SOURCE_MEMBERSHIP` socket + * option. If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. To add membership to every available interface, call `socket.addSourceSpecificMembership()` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * @since v13.1.0, v12.16.0 + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Instructs the kernel to leave a source-specific multicast channel at the given `sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP` socket option. This method is + * automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. error + * 4. listening + * 5. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: NonSharedBuffer, rinfo: RemoteInfo): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this; + /** + * Calls `socket.close()` and returns a promise that fulfills when the socket has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } +} +declare module "node:dgram" { + export * from "dgram"; +} diff --git a/tools/ui/node_modules/@types/node/diagnostics_channel.d.ts b/tools/ui/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..025847de1b38b42ec2c746f7ac3b46d1474a800b --- /dev/null +++ b/tools/ui/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,576 @@ +/** + * The `node:diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @since v15.1.0, v14.17.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/diagnostics_channel.js) + */ +declare module "diagnostics_channel" { + import { AsyncLocalStorage } from "node:async_hooks"; + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string | symbol): boolean; + /** + * This is the primary entry-point for anyone wanting to publish to a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return The named channel object + */ + function channel(name: string | symbol): Channel; + type ChannelListener = (message: unknown, name: string | symbol) => void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * diagnostics_channel.subscribe('my-channel', (message, name) => { + * // Received data + * }); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The handler to receive channel messages + */ + function subscribe(name: string | symbol, onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with {@link subscribe}. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * function onMessage(message, name) { + * // Received data + * } + * + * diagnostics_channel.subscribe('my-channel', onMessage); + * + * diagnostics_channel.unsubscribe('my-channel', onMessage); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean; + /** + * Creates a `TracingChannel` wrapper for the given `TracingChannel Channels`. If a name is given, the corresponding tracing + * channels will be created in the form of `tracing:${name}:${eventType}` where `eventType` corresponds to the types of `TracingChannel Channels`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channelsByName = diagnostics_channel.tracingChannel('my-channel'); + * + * // or... + * + * const channelsByCollection = diagnostics_channel.tracingChannel({ + * start: diagnostics_channel.channel('tracing:my-channel:start'), + * end: diagnostics_channel.channel('tracing:my-channel:end'), + * asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'), + * asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'), + * error: diagnostics_channel.channel('tracing:my-channel:error'), + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param nameOrChannels Channel name or object containing all the `TracingChannel Channels` + * @return Collection of channels to trace with + */ + function tracingChannel< + StoreType = unknown, + ContextType extends object = StoreType extends object ? StoreType : object, + >( + nameOrChannels: string | TracingChannelCollection, + ): TracingChannel; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is used to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + * @since v15.1.0, v14.17.0 + */ + class Channel { + readonly name: string | symbol; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + */ + readonly hasSubscribers: boolean; + private constructor(name: string | symbol); + /** + * Publish a message to any subscribers to the channel. This will trigger + * message handlers synchronously so they will execute within the same context. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.publish({ + * some: 'message', + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param message The message to send to the channel subscribers + */ + publish(message: unknown): void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @since v15.1.0, v14.17.0 + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + unsubscribe(onMessage: ChannelListener): void; + /** + * When `channel.runStores(context, ...)` is called, the given context data + * will be applied to any store bound to the channel. If the store has already been + * bound the previous `transform` function will be replaced with the new one. + * The `transform` function may be omitted to set the given context data as the + * context directly. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (data) => { + * return { data }; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to which to bind the context data + * @param transform Transform context data before setting the store context + */ + bindStore(store: AsyncLocalStorage, transform?: (context: ContextType) => StoreType): void; + /** + * Remove a message handler previously registered to this channel with `channel.bindStore(store)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store); + * channel.unbindStore(store); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to unbind from the channel. + * @return `true` if the store was found, `false` otherwise. + */ + unbindStore(store: AsyncLocalStorage): boolean; + /** + * Applies the given data to any AsyncLocalStorage instances bound to the channel + * for the duration of the given function, then publishes to the channel within + * the scope of that data is applied to the stores. + * + * If a transform function was given to `channel.bindStore(store)` it will be + * applied to transform the message data before it becomes the context value for + * the store. The prior storage context is accessible from within the transform + * function in cases where context linking is required. + * + * The context applied to the store should be accessible in any async code which + * continues from execution which began during the given function, however + * there are some situations in which `context loss` may occur. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (message) => { + * const parent = store.getStore(); + * return new Span(message, parent); + * }); + * channel.runStores({ some: 'message' }, () => { + * store.getStore(); // Span({ some: 'message' }) + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param context Message to send to subscribers and bind to stores + * @param fn Handler to run within the entered storage context + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runStores( + context: ContextType, + fn: (this: ThisArg, ...args: Args) => Result, + thisArg?: ThisArg, + ...args: Args + ): Result; + } + interface TracingChannelSubscribers { + start: (message: ContextType) => void; + end: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncStart: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncEnd: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + error: ( + message: ContextType & { + error: unknown; + }, + ) => void; + } + interface TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + } + /** + * The class `TracingChannel` is a collection of `TracingChannel Channels` which + * together express a single traceable action. It is used to formalize and + * simplify the process of producing events for tracing application flow. {@link tracingChannel} is used to construct a `TracingChannel`. As with `Channel` it is recommended to create and reuse a + * single `TracingChannel` at the top-level of the file rather than creating them + * dynamically. + * @since v19.9.0 + * @experimental + */ + class TracingChannel implements TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + /** + * Helper to subscribe a collection of functions to the corresponding channels. + * This is the same as calling `channel.subscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.subscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + */ + subscribe(subscribers: TracingChannelSubscribers): void; + /** + * Helper to unsubscribe a collection of functions from the corresponding channels. + * This is the same as calling `channel.unsubscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.unsubscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + * @return `true` if all handlers were successfully unsubscribed, and `false` otherwise. + */ + unsubscribe(subscribers: TracingChannelSubscribers): void; + /** + * Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error. + * This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceSync(() => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Function to wrap a trace around + * @param context Shared object to correlate events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceSync( + fn: (this: ThisArg, ...args: Args) => Result, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Result; + /** + * Trace a promise-returning function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce an `asyncStart event` and `asyncEnd event` when a promise continuation is reached. It may also + * produce an `error event` if the given function throws an error or the + * returned promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.tracePromise(async () => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Promise-returning function to wrap a trace around + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return Chained from promise returned by the given function + */ + tracePromise( + fn: (this: ThisArg, ...args: Args) => Promise, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Promise; + /** + * Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or + * the returned + * promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * The `position` will be -1 by default to indicate the final argument should + * be used as the callback. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceCallback((arg1, callback) => { + * // Do something + * callback(null, 'result'); + * }, 1, { + * some: 'thing', + * }, thisArg, arg1, callback); + * ``` + * + * The callback will also be run with `channel.runStores(context, ...)` which + * enables context loss recovery in some cases. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * const myStore = new AsyncLocalStorage(); + * + * // The start channel sets the initial store data to something + * // and stores that store data value on the trace context object + * channels.start.bindStore(myStore, (data) => { + * const span = new Span(data); + * data.span = span; + * return span; + * }); + * + * // Then asyncStart can restore from that data it stored previously + * channels.asyncStart.bindStore(myStore, (data) => { + * return data.span; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn callback using function to wrap a trace around + * @param position Zero-indexed argument position of expected callback + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceCallback( + fn: (this: ThisArg, ...args: Args) => Result, + position?: number, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Result; + /** + * `true` if any of the individual channels has a subscriber, `false` if not. + * + * This is a helper method available on a {@link TracingChannel} instance to check + * if any of the [TracingChannel Channels](https://nodejs.org/api/diagnostics_channel.html#tracingchannel-channels) have subscribers. + * A `true` is returned if any of them have at least one subscriber, a `false` is returned otherwise. + * + * ```js + * const diagnostics_channel = require('node:diagnostics_channel'); + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * if (channels.hasSubscribers) { + * // Do something + * } + * ``` + * @since v22.0.0, v20.13.0 + */ + readonly hasSubscribers: boolean; + } +} +declare module "node:diagnostics_channel" { + export * from "diagnostics_channel"; +} diff --git a/tools/ui/node_modules/@types/node/dns.d.ts b/tools/ui/node_modules/@types/node/dns.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ba0d122131db78b75ae36ab6374c8cf6e4563411 --- /dev/null +++ b/tools/ui/node_modules/@types/node/dns.d.ts @@ -0,0 +1,923 @@ +/** + * The `node:dns` module enables name resolution. For example, use it to look up IP + * addresses of host names. + * + * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the + * DNS protocol for lookups. {@link lookup} uses the operating system + * facilities to perform name resolution. It may not need to perform any network + * communication. To perform name resolution the way other applications on the same + * system do, use {@link lookup}. + * + * ```js + * import dns from 'node:dns'; + * + * dns.lookup('example.org', (err, address, family) => { + * console.log('address: %j family: IPv%s', address, family); + * }); + * // address: "93.184.216.34" family: IPv4 + * ``` + * + * All other functions in the `node:dns` module connect to an actual DNS server to + * perform name resolution. They will always use the network to perform DNS + * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform + * DNS queries, bypassing other name-resolution facilities. + * + * ```js + * import dns from 'node:dns'; + * + * dns.resolve4('archive.org', (err, addresses) => { + * if (err) throw err; + * + * console.log(`addresses: ${JSON.stringify(addresses)}`); + * + * addresses.forEach((a) => { + * dns.reverse(a, (err, hostnames) => { + * if (err) { + * throw err; + * } + * console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); + * }); + * }); + * }); + * ``` + * + * See the [Implementation considerations section](https://nodejs.org/docs/latest-v24.x/api/dns.html#implementation-considerations) for more information. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/dns.js) + */ +declare module "dns" { + import * as dnsPromises from "node:dns/promises"; + // Supported getaddrinfo flags. + /** + * Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses are + * only returned if the current system has at least one IPv4 address configured. + */ + export const ADDRCONFIG: number; + /** + * If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. It is not supported + * on some operating systems (e.g. FreeBSD 10.1). + */ + export const V4MAPPED: number; + /** + * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as + * well as IPv4 mapped IPv6 addresses. + */ + export const ALL: number; + export interface LookupOptions { + /** + * The record family. Must be `4`, `6`, or `0`. For backward compatibility reasons, `'IPv4'` and `'IPv6'` are interpreted + * as `4` and `6` respectively. The value 0 indicates that either an IPv4 or IPv6 address is returned. If the value `0` is used + * with `{ all: true } (see below)`, both IPv4 and IPv6 addresses are returned. + * @default 0 + */ + family?: number | "IPv4" | "IPv6" | undefined; + /** + * One or more [supported `getaddrinfo`](https://nodejs.org/docs/latest-v24.x/api/dns.html#supported-getaddrinfo-flags) flags. Multiple flags may be + * passed by bitwise `OR`ing their values. + */ + hints?: number | undefined; + /** + * When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address. + * @default false + */ + all?: boolean | undefined; + /** + * When `verbatim`, the resolved addresses are return unsorted. When `ipv4first`, the resolved addresses are sorted + * by placing IPv4 addresses before IPv6 addresses. When `ipv6first`, the resolved addresses are sorted by placing IPv6 + * addresses before IPv4 addresses. Default value is configurable using + * {@link setDefaultResultOrder} or [`--dns-result-order`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--dns-result-orderorder). + * @default `verbatim` (addresses are not reordered) + * @since v22.1.0 + */ + order?: "ipv4first" | "ipv6first" | "verbatim" | undefined; + /** + * When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 + * addresses are placed before IPv6 addresses. This option will be deprecated in favor of `order`. When both are specified, + * `order` has higher precedence. New code should only use `order`. Default value is configurable using {@link setDefaultResultOrder} + * @default true (addresses are not reordered) + * @deprecated Please use `order` option + */ + verbatim?: boolean | undefined; + } + export interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + export interface LookupAllOptions extends LookupOptions { + all: true; + } + export interface LookupAddress { + /** + * A string representation of an IPv4 or IPv6 address. + */ + address: string; + /** + * `4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a + * bug in the name resolution service used by the operating system. + */ + family: number; + } + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is `0` or not provided, then + * IPv4 and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the arguments for `callback` change to `(err, addresses)`, with `addresses` being an array of objects with the + * properties `address` and `family`. + * + * On error, `err` is an `Error` object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. + * The implementation uses an operating system facility that can associate names + * with addresses and vice versa. This implementation can have subtle but + * important consequences on the behavior of any Node.js program. Please take some + * time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v24.x/api/dns.html#implementation-considerations) + * before using `dns.lookup()`. + * + * Example usage: + * + * ```js + * import dns from 'node:dns'; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * dns.lookup('example.com', options, (err, address, family) => + * console.log('address: %j family: IPv%s', address, family)); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dns.lookup('example.com', options, (err, addresses) => + * console.log('addresses: %j', addresses)); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v24.x/api/util.html#utilpromisifyoriginal) ed + * version, and `all` is not set to `true`, it returns a `Promise` for an `Object` with `address` and `family` properties. + * @since v0.1.90 + */ + export function lookup( + hostname: string, + family: number, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupAllOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void, + ): void; + export function lookup( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; + function __promisify__(hostname: string, options: LookupOptions): Promise; + } + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On an error, `err` is an [`Error`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) object, + * where `err.code` is the error code. + * + * ```js + * import dns from 'node:dns'; + * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { + * console.log(hostname, service); + * // Prints: localhost ssh + * }); + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v24.x/api/util.html#utilpromisifyoriginal) ed + * version, it returns a `Promise` for an `Object` with `hostname` and `service` properties. + * @since v0.11.14 + */ + export function lookupService( + address: string, + port: number, + callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void, + ): void; + export namespace lookupService { + function __promisify__( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + } + export interface ResolveOptions { + ttl: boolean; + } + export interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + export interface RecordWithTtl { + address: string; + ttl: number; + } + /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ + export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + export interface AnyARecord extends RecordWithTtl { + type: "A"; + } + export interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + export interface CaaRecord { + critical: number; + issue?: string | undefined; + issuewild?: string | undefined; + iodef?: string | undefined; + contactemail?: string | undefined; + contactphone?: string | undefined; + } + export interface AnyCaaRecord extends CaaRecord { + type: "CAA"; + } + export interface MxRecord { + priority: number; + exchange: string; + } + export interface AnyMxRecord extends MxRecord { + type: "MX"; + } + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + export interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + export interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + export interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + export interface TlsaRecord { + certUsage: number; + selector: number; + match: number; + data: ArrayBuffer; + } + export interface AnyTlsaRecord extends TlsaRecord { + type: "TLSA"; + } + export interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + export interface AnyNsRecord { + type: "NS"; + value: string; + } + export interface AnyPtrRecord { + type: "PTR"; + value: string; + } + export interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + export type AnyRecord = + | AnyARecord + | AnyAaaaRecord + | AnyCaaRecord + | AnyCnameRecord + | AnyMxRecord + | AnyNaptrRecord + | AnyNsRecord + | AnyPtrRecord + | AnySoaRecord + | AnySrvRecord + | AnyTlsaRecord + | AnyTxtRecord; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. The `callback` function has arguments `(err, records)`. When successful, `records` will be an array of resource + * records. The type and structure of individual results varies based on `rrtype`: + * + * + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) object, + * where `err.code` is one of the `DNS error codes`. + * @since v0.1.27 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + export function resolve( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "ANY", + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "CAA", + callback: (err: NodeJS.ErrnoException | null, address: CaaRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "MX", + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "NAPTR", + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SOA", + callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SRV", + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "TLSA", + callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "TXT", + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: string, + callback: ( + err: NodeJS.ErrnoException | null, + addresses: + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[], + ) => void, + ): void; + export namespace resolve { + function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function __promisify__(hostname: string, rrtype: "ANY"): Promise; + function __promisify__(hostname: string, rrtype: "CAA"): Promise; + function __promisify__(hostname: string, rrtype: "MX"): Promise; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + function __promisify__(hostname: string, rrtype: "SOA"): Promise; + function __promisify__(hostname: string, rrtype: "SRV"): Promise; + function __promisify__(hostname: string, rrtype: "TLSA"): Promise; + function __promisify__(hostname: string, rrtype: "TXT"): Promise; + function __promisify__( + hostname: string, + rrtype: string, + ): Promise< + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[] + >; + } + /** + * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve4( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv6 addresses. + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve6( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`). + * @since v0.3.2 + */ + export function resolveCname( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of certification authority authorization records + * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + export function resolveCaa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void, + ): void; + export namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of objects containing both a `priority` and `exchange` property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v0.1.27 + */ + export function resolveMx( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will contain an array of + * objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v0.9.12 + */ + export function resolveNaptr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of name server records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`). + * @since v0.1.90 + */ + export function resolveNs( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of strings containing the reply records. + * @since v6.0.0 + */ + export function resolvePtr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. The `address` argument passed to the `callback` function will + * be an object with the following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v0.11.10 + */ + export function resolveSoa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void, + ): void; + export namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of objects with the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v0.1.27 + */ + export function resolveSrv( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve certificate associations (`TLSA` records) for + * the `hostname`. The `records` argument passed to the `callback` function is an + * array of objects with these properties: + * + * * `certUsage` + * * `selector` + * * `match` + * * `data` + * + * ```js + * { + * certUsage: 3, + * selector: 1, + * match: 1, + * data: [ArrayBuffer] + * } + * ``` + * @since v23.9.0, v22.15.0 + */ + export function resolveTlsa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void, + ): void; + export namespace resolveTlsa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. The `records` argument passed to the `callback` function is a + * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v0.1.27 + */ + export function resolveTxt( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * The `ret` argument passed to the `callback` function will be an array containing + * various types of records. Each object has a property `type` that indicates the + * type of the current record. And depending on the `type`, additional properties + * will be present on the object: + * + * + * + * Here is an example of the `ret` object passed to the callback: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * + * DNS server operators may choose not to respond to `ANY` queries. It may be better to call individual methods like {@link resolve4}, {@link resolveMx}, and so on. For more details, see + * [RFC 8482](https://tools.ietf.org/html/rfc8482). + */ + export function resolveAny( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) object, where `err.code` is + * one of the [DNS error codes](https://nodejs.org/docs/latest-v24.x/api/dns.html#error-codes). + * @since v0.1.16 + */ + export function reverse( + ip: string, + callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void, + ): void; + /** + * Get the default value for `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v24.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `order` defaulting to `ipv4first`. + * * `ipv6first`: for `order` defaulting to `ipv6first`. + * * `verbatim`: for `order` defaulting to `verbatim`. + * @since v18.17.0 + */ + export function getDefaultResultOrder(): "ipv4first" | "ipv6first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dns.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dns.setServers()` method must not be called while a DNS query is in + * progress. + * + * The {@link setServers} method affects only {@link resolve}, `dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v0.11.3 + * @param servers array of [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952#section-6) formatted addresses + */ + export function setServers(servers: readonly string[]): void; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v0.11.3 + */ + export function getServers(): string[]; + /** + * Set the default value of `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v24.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * The default is `verbatim` and {@link setDefaultResultOrder} have higher + * priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--dns-result-orderorder). When using + * [worker threads](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html), {@link setDefaultResultOrder} from the main + * thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. + */ + export function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + // Error codes + export const NODATA: "ENODATA"; + export const FORMERR: "EFORMERR"; + export const SERVFAIL: "ESERVFAIL"; + export const NOTFOUND: "ENOTFOUND"; + export const NOTIMP: "ENOTIMP"; + export const REFUSED: "EREFUSED"; + export const BADQUERY: "EBADQUERY"; + export const BADNAME: "EBADNAME"; + export const BADFAMILY: "EBADFAMILY"; + export const BADRESP: "EBADRESP"; + export const CONNREFUSED: "ECONNREFUSED"; + export const TIMEOUT: "ETIMEOUT"; + export const EOF: "EOF"; + export const FILE: "EFILE"; + export const NOMEM: "ENOMEM"; + export const DESTRUCTION: "EDESTRUCTION"; + export const BADSTR: "EBADSTR"; + export const BADFLAGS: "EBADFLAGS"; + export const NONAME: "ENONAME"; + export const BADHINTS: "EBADHINTS"; + export const NOTINITIALIZED: "ENOTINITIALIZED"; + export const LOADIPHLPAPI: "ELOADIPHLPAPI"; + export const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + export const CANCELLED: "ECANCELLED"; + export interface ResolverOptions { + /** + * Query timeout in milliseconds, or `-1` to use the default timeout. + */ + timeout?: number | undefined; + /** + * The number of tries the resolver will try contacting each name server before giving up. + * @default 4 + */ + tries?: number | undefined; + /** + * The max retry timeout, in milliseconds. + * @default 0 + */ + maxTimeout?: number | undefined; + } + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v24.x/api/dns.html#dnssetserversservers) does not affect + * other resolvers: + * + * ```js + * import { Resolver } from 'node:dns'; + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org', (err, addresses) => { + * // ... + * }); + * ``` + * + * The following methods from the `node:dns` module are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v8.3.0 + */ + export class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTlsa: typeof resolveTlsa; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } + export { dnsPromises as promises }; +} +declare module "node:dns" { + export * from "dns"; +} diff --git a/tools/ui/node_modules/@types/node/dns/promises.d.ts b/tools/ui/node_modules/@types/node/dns/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..efb9fbfdf4258584324b30edf9250750b95d75fa --- /dev/null +++ b/tools/ui/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,503 @@ +/** + * The `dns.promises` API provides an alternative set of asynchronous DNS methods + * that return `Promise` objects rather than using callbacks. The API is accessible + * via `import { promises as dnsPromises } from 'node:dns'` or `import dnsPromises from 'node:dns/promises'`. + * @since v10.6.0 + */ +declare module "dns/promises" { + import { + AnyRecord, + CaaRecord, + LookupAddress, + LookupAllOptions, + LookupOneOptions, + LookupOptions, + MxRecord, + NaptrRecord, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + ResolveWithTtlOptions, + SoaRecord, + SrvRecord, + TlsaRecord, + } from "node:dns"; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v10.6.0 + */ + function getServers(): string[]; + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the `Promise` is resolved with `addresses` being an array of objects with the properties `address` and `family`. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options) does not necessarily have anything to do with the DNS + * protocol. The implementation uses an operating system facility that can + * associate names with addresses and vice versa. This implementation can have + * subtle but important consequences on the behavior of any Node.js program. Please + * take some time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * import dns from 'node:dns'; + * const dnsPromises = dns.promises; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('address: %j family: IPv%s', result.address, result.family); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * }); + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('addresses: %j', result); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * }); + * ``` + * @since v10.6.0 + */ + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. + * + * ```js + * import dnsPromises from 'node:dns'; + * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { + * console.log(result.hostname, result.service); + * // Prints: localhost ssh + * }); + * ``` + * @since v10.6.0 + */ + function lookupService( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. When successful, the `Promise` is resolved with an + * array of resource records. The type and structure of individual results vary + * based on `rrtype`: + * + * + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). + * @since v10.6.0 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function resolve(hostname: string, rrtype: "ANY"): Promise; + function resolve(hostname: string, rrtype: "CAA"): Promise; + function resolve(hostname: string, rrtype: "MX"): Promise; + function resolve(hostname: string, rrtype: "NAPTR"): Promise; + function resolve(hostname: string, rrtype: "SOA"): Promise; + function resolve(hostname: string, rrtype: "SRV"): Promise; + function resolve(hostname: string, rrtype: "TLSA"): Promise; + function resolve(hostname: string, rrtype: "TXT"): Promise; + function resolve(hostname: string, rrtype: string): Promise< + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[] + >; + /** + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4 + * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv6 + * addresses. + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * On success, the `Promise` is resolved with an array containing various types of + * records. Each object has a property `type` that indicates the type of the + * current record. And depending on the `type`, additional properties will be + * present on the object: + * + * + * + * Here is an example of the result object: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * @since v10.6.0 + */ + function resolveAny(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, + * the `Promise` is resolved with an array of objects containing available + * certification authority authorization records available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + function resolveCaa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, + * the `Promise` is resolved with an array of canonical name records available for + * the `hostname` (e.g. `['bar.example.com']`). + * @since v10.6.0 + */ + function resolveCname(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects + * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v10.6.0 + */ + function resolveMx(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. On success, the `Promise` is resolved with an array + * of objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v10.6.0 + */ + function resolveNaptr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. On success, the `Promise` is resolved with an array of name server + * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). + * @since v10.6.0 + */ + function resolveNs(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. On success, the `Promise` is resolved with an array of strings + * containing the reply records. + * @since v10.6.0 + */ + function resolvePtr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. On success, the `Promise` is resolved with an object with the + * following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v10.6.0 + */ + function resolveSoa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects with + * the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v10.6.0 + */ + function resolveSrv(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve certificate associations (`TLSA` records) for + * the `hostname`. On success, the `Promise` is resolved with an array of objectsAdd commentMore actions + * with these properties: + * + * * `certUsage` + * * `selector` + * * `match` + * * `data` + * + * ```js + * { + * certUsage: 3, + * selector: 1, + * match: 1, + * data: [ArrayBuffer] + * } + * ``` + * @since v23.9.0, v22.15.0 + */ + function resolveTlsa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. On success, the `Promise` is resolved with a two-dimensional array + * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v10.6.0 + */ + function resolveTxt(hostname: string): Promise; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Get the default value for `verbatim` in {@link lookup} and [dnsPromises.lookup()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v20.1.0 + */ + function getDefaultResultOrder(): "ipv4first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dnsPromises.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dnsPromises.setServers()` method must not be called while a DNS query is in + * progress. + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v10.6.0 + * @param servers array of `RFC 5952` formatted addresses + */ + function setServers(servers: readonly string[]): void; + /** + * Set the default value of `order` in `dns.lookup()` and `{@link lookup}`. The value could be: + * + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * The default is `verbatim` and [dnsPromises.setDefaultResultOrder()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * have higher priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). + * When using [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), [`dnsPromises.setDefaultResultOrder()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * from the main thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + // Error codes + const NODATA: "ENODATA"; + const FORMERR: "EFORMERR"; + const SERVFAIL: "ESERVFAIL"; + const NOTFOUND: "ENOTFOUND"; + const NOTIMP: "ENOTIMP"; + const REFUSED: "EREFUSED"; + const BADQUERY: "EBADQUERY"; + const BADNAME: "EBADNAME"; + const BADFAMILY: "EBADFAMILY"; + const BADRESP: "EBADRESP"; + const CONNREFUSED: "ECONNREFUSED"; + const TIMEOUT: "ETIMEOUT"; + const EOF: "EOF"; + const FILE: "EFILE"; + const NOMEM: "ENOMEM"; + const DESTRUCTION: "EDESTRUCTION"; + const BADSTR: "EBADSTR"; + const BADFLAGS: "EBADFLAGS"; + const NONAME: "ENONAME"; + const BADHINTS: "EBADHINTS"; + const NOTINITIALIZED: "ENOTINITIALIZED"; + const LOADIPHLPAPI: "ELOADIPHLPAPI"; + const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + const CANCELLED: "ECANCELLED"; + + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetserversservers) does not affect + * other resolvers: + * + * ```js + * import { promises } from 'node:dns'; + * const resolver = new promises.Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org').then((addresses) => { + * // ... + * }); + * + * // Alternatively, the same code can be written using async-await style. + * (async function() { + * const addresses = await resolver.resolve4('example.org'); + * })(); + * ``` + * + * The following methods from the `dnsPromises` API are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v10.6.0 + */ + class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTlsa: typeof resolveTlsa; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module "node:dns/promises" { + export * from "dns/promises"; +} diff --git a/tools/ui/node_modules/@types/node/domain.d.ts b/tools/ui/node_modules/@types/node/domain.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d6eaecbc8b237a1b0717c2db22d863bd79a36146 --- /dev/null +++ b/tools/ui/node_modules/@types/node/domain.d.ts @@ -0,0 +1,166 @@ +/** + * **This module is pending deprecation.** Once a replacement API has been + * finalized, this module will be fully deprecated. Most developers should + * **not** have cause to use this module. Users who absolutely must have + * the functionality that domains provide may rely on it for the time being + * but should expect to have to migrate to a different solution + * in the future. + * + * Domains provide a way to handle multiple different IO operations as a + * single group. If any of the event emitters or callbacks registered to a + * domain emit an `'error'` event, or throw an error, then the domain object + * will be notified, rather than losing the context of the error in the `process.on('uncaughtException')` handler, or causing the program to + * exit immediately with an error code. + * @deprecated Since v1.4.2 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/domain.js) + */ +declare module "domain" { + import EventEmitter = require("node:events"); + /** + * The `Domain` class encapsulates the functionality of routing errors and + * uncaught exceptions to the active `Domain` object. + * + * To handle the errors that it catches, listen to its `'error'` event. + */ + class Domain extends EventEmitter { + /** + * An array of event emitters that have been explicitly added to the domain. + */ + members: EventEmitter[]; + /** + * The `enter()` method is plumbing used by the `run()`, `bind()`, and `intercept()` methods to set the active domain. It sets `domain.active` and `process.domain` to the domain, and implicitly + * pushes the domain onto the domain + * stack managed by the domain module (see {@link exit} for details on the + * domain stack). The call to `enter()` delimits the beginning of a chain of + * asynchronous calls and I/O operations bound to a domain. + * + * Calling `enter()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + enter(): void; + /** + * The `exit()` method exits the current domain, popping it off the domain stack. + * Any time execution is going to switch to the context of a different chain of + * asynchronous calls, it's important to ensure that the current domain is exited. + * The call to `exit()` delimits either the end of or an interruption to the chain + * of asynchronous calls and I/O operations bound to a domain. + * + * If there are multiple, nested domains bound to the current execution context, `exit()` will exit any domains nested within this domain. + * + * Calling `exit()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + exit(): void; + /** + * Run the supplied function in the context of the domain, implicitly + * binding all event emitters, timers, and low-level requests that are + * created in that context. Optionally, arguments can be passed to + * the function. + * + * This is the most basic way to use a domain. + * + * ```js + * import domain from 'node:domain'; + * import fs from 'node:fs'; + * const d = domain.create(); + * d.on('error', (er) => { + * console.error('Caught error!', er); + * }); + * d.run(() => { + * process.nextTick(() => { + * setTimeout(() => { // Simulating some various async stuff + * fs.open('non-existent file', 'r', (er, fd) => { + * if (er) throw er; + * // proceed... + * }); + * }, 100); + * }); + * }); + * ``` + * + * In this example, the `d.on('error')` handler will be triggered, rather + * than crashing the program. + */ + run(fn: (...args: any[]) => T, ...args: any[]): T; + /** + * Explicitly adds an emitter to the domain. If any event handlers called by + * the emitter throw an error, or if the emitter emits an `'error'` event, it + * will be routed to the domain's `'error'` event, just like with implicit + * binding. + * + * If the `EventEmitter` was already bound to a domain, it is removed from that + * one, and bound to this one instead. + * @param emitter emitter to be added to the domain + */ + add(emitter: EventEmitter): void; + /** + * The opposite of {@link add}. Removes domain handling from the + * specified emitter. + * @param emitter emitter to be removed from the domain + */ + remove(emitter: EventEmitter): void; + /** + * The returned function will be a wrapper around the supplied callback + * function. When the returned function is called, any errors that are + * thrown will be routed to the domain's `'error'` event. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.bind((er, data) => { + * // If this throws, it will also be passed to the domain. + * return cb(er, data ? JSON.parse(data) : null); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The bound function + */ + bind(callback: T): T; + /** + * This method is almost identical to {@link bind}. However, in + * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. + * + * In this way, the common `if (err) return callback(err);` pattern can be replaced + * with a single error handler in a single place. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.intercept((data) => { + * // Note, the first argument is never passed to the + * // callback since it is assumed to be the 'Error' argument + * // and thus intercepted by the domain. + * + * // If this throws, it will also be passed to the domain + * // so the error-handling logic can be moved to the 'error' + * // event on the domain instead of being repeated throughout + * // the program. + * return cb(null, JSON.parse(data)); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The intercepted function + */ + intercept(callback: T): T; + } + function create(): Domain; +} +declare module "node:domain" { + export * from "domain"; +} diff --git a/tools/ui/node_modules/@types/node/events.d.ts b/tools/ui/node_modules/@types/node/events.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..023348e02f3690bb3cc21406141d47d264d49b7b --- /dev/null +++ b/tools/ui/node_modules/@types/node/events.d.ts @@ -0,0 +1,976 @@ +/** + * Much of the Node.js core API is built around an idiomatic asynchronous + * event-driven architecture in which certain kinds of objects (called "emitters") + * emit named events that cause `Function` objects ("listeners") to be called. + * + * For instance: a `net.Server` object emits an event each time a peer + * connects to it; a `fs.ReadStream` emits an event when the file is opened; + * a `stream` emits an event whenever data is available to be read. + * + * All objects that emit events are instances of the `EventEmitter` class. These + * objects expose an `eventEmitter.on()` function that allows one or more + * functions to be attached to named events emitted by the object. Typically, + * event names are camel-cased strings but any valid JavaScript property key + * can be used. + * + * When the `EventEmitter` object emits an event, all of the functions attached + * to that specific event are called _synchronously_. Any values returned by the + * called listeners are _ignored_ and discarded. + * + * The following example shows a simple `EventEmitter` instance with a single + * listener. The `eventEmitter.on()` method is used to register listeners, while + * the `eventEmitter.emit()` method is used to trigger the event. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * class MyEmitter extends EventEmitter {} + * + * const myEmitter = new MyEmitter(); + * myEmitter.on('event', () => { + * console.log('an event occurred!'); + * }); + * myEmitter.emit('event'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/events.js) + */ +declare module "events" { + import { AsyncResource, AsyncResourceOptions } from "node:async_hooks"; + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean | undefined; + } + interface StaticEventEmitterOptions { + /** + * Can be used to cancel awaiting events. + */ + signal?: AbortSignal | undefined; + } + interface StaticEventEmitterIteratorOptions extends StaticEventEmitterOptions { + /** + * Names of events that will end the iteration. + */ + close?: string[] | undefined; + /** + * The high watermark. The emitter is paused every time the size of events being buffered is higher than it. + * Supported only on emitters implementing `pause()` and `resume()` methods. + * @default Number.MAX_SAFE_INTEGER + */ + highWaterMark?: number | undefined; + /** + * The low watermark. The emitter is resumed every time the size of events being buffered is lower than it. + * Supported only on emitters implementing `pause()` and `resume()` methods. + * @default 1 + */ + lowWaterMark?: number | undefined; + } + interface EventEmitter = DefaultEventMap> extends NodeJS.EventEmitter {} + type EventMap = Record | DefaultEventMap; + type DefaultEventMap = [never]; + type AnyRest = [...args: any[]]; + type Args = T extends DefaultEventMap ? AnyRest : ( + K extends keyof T ? T[K] : never + ); + type Key = T extends DefaultEventMap ? string | symbol : K | keyof T; + type Key2 = T extends DefaultEventMap ? string | symbol : K & keyof T; + type Listener = T extends DefaultEventMap ? F : ( + K extends keyof T ? ( + T[K] extends unknown[] ? (...args: T[K]) => void : never + ) + : never + ); + type Listener1 = Listener void>; + type Listener2 = Listener; + + /** + * The `EventEmitter` class is defined and exposed by the `node:events` module: + * + * ```js + * import { EventEmitter } from 'node:events'; + * ``` + * + * All `EventEmitter`s emit the event `'newListener'` when new listeners are + * added and `'removeListener'` when existing listeners are removed. + * + * It supports the following option: + * @since v0.1.26 + */ + class EventEmitter = DefaultEventMap> { + constructor(options?: EventEmitterOptions); + + [EventEmitter.captureRejectionSymbol]?(error: Error, event: Key, ...args: Args): void; + + /** + * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given + * event or that is rejected if the `EventEmitter` emits `'error'` while waiting. + * The `Promise` will resolve with an array of all the arguments emitted to the + * given event. + * + * This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event + * semantics and does not listen to the `'error'` event. + * + * ```js + * import { once, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); + * + * const [value] = await once(ee, 'myevent'); + * console.log(value); + * + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); + * + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.error('error happened', err); + * } + * ``` + * + * The special handling of the `'error'` event is only used when `events.once()` is used to wait for another event. If `events.once()` is used to wait for the + * '`error'` event itself, then it is treated as any other kind of event without + * special handling: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.error('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * const ac = new AbortController(); + * + * async function foo(emitter, event, signal) { + * try { + * await once(emitter, event, { signal }); + * console.log('event emitted!'); + * } catch (error) { + * if (error.name === 'AbortError') { + * console.error('Waiting for the event was canceled!'); + * } else { + * console.error('There was an error', error.message); + * } + * } + * } + * + * foo(ee, 'foo', ac.signal); + * ac.abort(); // Abort waiting for the event + * ee.emit('foo'); // Prints: Waiting for the event was canceled! + * ``` + * @since v11.13.0, v10.16.0 + */ + static once( + emitter: NodeJS.EventEmitter, + eventName: string | symbol, + options?: StaticEventEmitterOptions, + ): Promise; + static once(emitter: EventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo')) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * ``` + * + * Returns an `AsyncIterator` that iterates `eventName` events. It will throw + * if the `EventEmitter` emits `'error'`. It removes all listeners when + * exiting the loop. The `value` returned by each iteration is an array + * composed of the emitted event arguments. + * + * An `AbortSignal` can be used to cancel waiting on events: + * + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ac = new AbortController(); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo', { signal: ac.signal })) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * + * process.nextTick(() => ac.abort()); + * ``` + * + * Use the `close` option to specify an array of event names that will end the iteration: + * + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * ee.emit('close'); + * }); + * + * for await (const event of on(ee, 'foo', { close: ['close'] })) { + * console.log(event); // prints ['bar'] [42] + * } + * // the loop will exit after 'close' is emitted + * console.log('done'); // prints 'done' + * ``` + * @since v13.6.0, v12.16.0 + * @return An `AsyncIterator` that iterates `eventName` events emitted by the `emitter` + */ + static on( + emitter: NodeJS.EventEmitter, + eventName: string | symbol, + options?: StaticEventEmitterIteratorOptions, + ): NodeJS.AsyncIterator; + static on( + emitter: EventTarget, + eventName: string, + options?: StaticEventEmitterIteratorOptions, + ): NodeJS.AsyncIterator; + /** + * A class method that returns the number of listeners for the given `eventName` registered on the given `emitter`. + * + * ```js + * import { EventEmitter, listenerCount } from 'node:events'; + * + * const myEmitter = new EventEmitter(); + * myEmitter.on('event', () => {}); + * myEmitter.on('event', () => {}); + * console.log(listenerCount(myEmitter, 'event')); + * // Prints: 2 + * ``` + * @since v0.9.12 + * @deprecated Since v3.2.0 - Use `listenerCount` instead. + * @param emitter The emitter to query + * @param eventName The event name + */ + static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the event listeners for the + * event target. This is useful for debugging and diagnostic purposes. + * + * ```js + * import { getEventListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] + * } + * ``` + * @since v15.2.0, v14.17.0 + */ + static getEventListeners(emitter: EventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + /** + * Returns the currently set max amount of listeners. + * + * For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the max event listeners for the + * event target. If the number of event handlers on a single EventTarget exceeds + * the max set, the EventTarget will print a warning. + * + * ```js + * import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * console.log(getMaxListeners(ee)); // 10 + * setMaxListeners(11, ee); + * console.log(getMaxListeners(ee)); // 11 + * } + * { + * const et = new EventTarget(); + * console.log(getMaxListeners(et)); // 10 + * setMaxListeners(11, et); + * console.log(getMaxListeners(et)); // 11 + * } + * ``` + * @since v19.9.0 + */ + static getMaxListeners(emitter: EventTarget | NodeJS.EventEmitter): number; + /** + * ```js + * import { setMaxListeners, EventEmitter } from 'node:events'; + * + * const target = new EventTarget(); + * const emitter = new EventEmitter(); + * + * setMaxListeners(5, target, emitter); + * ``` + * @since v15.4.0 + * @param n A non-negative number. The maximum number of listeners per `EventTarget` event. + * @param eventTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} + * objects. + */ + static setMaxListeners(n?: number, ...eventTargets: Array): void; + /** + * Listens once to the `abort` event on the provided `signal`. + * + * Listening to the `abort` event on abort signals is unsafe and may + * lead to resource leaks since another third party with the signal can + * call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change + * this since it would violate the web standard. Additionally, the original + * API makes it easy to forget to remove listeners. + * + * This API allows safely using `AbortSignal`s in Node.js APIs by solving these + * two issues by listening to the event such that `stopImmediatePropagation` does + * not prevent the listener from running. + * + * Returns a disposable so that it may be unsubscribed from more easily. + * + * ```js + * import { addAbortListener } from 'node:events'; + * + * function example(signal) { + * let disposable; + * try { + * signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); + * disposable = addAbortListener(signal, (e) => { + * // Do something when signal is aborted. + * }); + * } finally { + * disposable?.[Symbol.dispose](); + * } + * } + * ``` + * @since v20.5.0 + * @return Disposable that removes the `abort` listener. + */ + static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable; + /** + * This symbol shall be used to install a listener for only monitoring `'error'` events. Listeners installed using this symbol are called before the regular `'error'` listeners are called. + * + * Installing a listener using this symbol does not change the behavior once an `'error'` event is emitted. Therefore, the process will still crash if no + * regular `'error'` listener is installed. + * @since v13.6.0, v12.17.0 + */ + static readonly errorMonitor: unique symbol; + /** + * Value: `Symbol.for('nodejs.rejection')` + * + * See how to write a custom `rejection handler`. + * @since v13.4.0, v12.16.0 + */ + static readonly captureRejectionSymbol: unique symbol; + /** + * Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) + * + * Change the default `captureRejections` option on all new `EventEmitter` objects. + * @since v13.4.0, v12.16.0 + */ + static captureRejections: boolean; + /** + * By default, a maximum of `10` listeners can be registered for any single + * event. This limit can be changed for individual `EventEmitter` instances + * using the `emitter.setMaxListeners(n)` method. To change the default + * for _all_`EventEmitter` instances, the `events.defaultMaxListeners` property + * can be used. If this value is not a positive number, a `RangeError` is thrown. + * + * Take caution when setting the `events.defaultMaxListeners` because the + * change affects _all_ `EventEmitter` instances, including those created before + * the change is made. However, calling `emitter.setMaxListeners(n)` still has + * precedence over `events.defaultMaxListeners`. + * + * This is not a hard limit. The `EventEmitter` instance will allow + * more listeners to be added but will output a trace warning to stderr indicating + * that a "possible EventEmitter memory leak" has been detected. For any single + * `EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()` methods can be used to + * temporarily avoid this warning: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.setMaxListeners(emitter.getMaxListeners() + 1); + * emitter.once('event', () => { + * // do stuff + * emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); + * }); + * ``` + * + * The `--trace-warnings` command-line flag can be used to display the + * stack trace for such warnings. + * + * The emitted warning can be inspected with `process.on('warning')` and will + * have the additional `emitter`, `type`, and `count` properties, referring to + * the event emitter instance, the event's name and the number of attached + * listeners, respectively. + * Its `name` property is set to `'MaxListenersExceededWarning'`. + * @since v0.11.2 + */ + static defaultMaxListeners: number; + } + import internal = require("node:events"); + namespace EventEmitter { + // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 + export { internal as EventEmitter }; + export interface Abortable { + /** + * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. + */ + signal?: AbortSignal | undefined; + } + + export interface EventEmitterReferencingAsyncResource extends AsyncResource { + readonly eventEmitter: EventEmitterAsyncResource; + } + + export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions { + /** + * The type of async event, this is required when instantiating `EventEmitterAsyncResource` + * directly rather than as a child class. + * @default new.target.name if instantiated as a child class. + */ + name?: string | undefined; + } + + /** + * Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that + * require manual async tracking. Specifically, all events emitted by instances + * of `events.EventEmitterAsyncResource` will run within its `async context`. + * + * ```js + * import { EventEmitterAsyncResource, EventEmitter } from 'node:events'; + * import { notStrictEqual, strictEqual } from 'node:assert'; + * import { executionAsyncId, triggerAsyncId } from 'node:async_hooks'; + * + * // Async tracking tooling will identify this as 'Q'. + * const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); + * + * // 'foo' listeners will run in the EventEmitters async context. + * ee1.on('foo', () => { + * strictEqual(executionAsyncId(), ee1.asyncId); + * strictEqual(triggerAsyncId(), ee1.triggerAsyncId); + * }); + * + * const ee2 = new EventEmitter(); + * + * // 'foo' listeners on ordinary EventEmitters that do not track async + * // context, however, run in the same async context as the emit(). + * ee2.on('foo', () => { + * notStrictEqual(executionAsyncId(), ee2.asyncId); + * notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId); + * }); + * + * Promise.resolve().then(() => { + * ee1.emit('foo'); + * ee2.emit('foo'); + * }); + * ``` + * + * The `EventEmitterAsyncResource` class has the same methods and takes the + * same options as `EventEmitter` and `AsyncResource` themselves. + * @since v17.4.0, v16.14.0 + */ + export class EventEmitterAsyncResource extends EventEmitter { + /** + * @param options Only optional in child class. + */ + constructor(options?: EventEmitterAsyncResourceOptions); + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + */ + emitDestroy(): void; + /** + * The unique `asyncId` assigned to the resource. + */ + readonly asyncId: number; + /** + * The same triggerAsyncId that is passed to the AsyncResource constructor. + */ + readonly triggerAsyncId: number; + /** + * The returned `AsyncResource` object has an additional `eventEmitter` property + * that provides a reference to this `EventEmitterAsyncResource`. + */ + readonly asyncResource: EventEmitterReferencingAsyncResource; + } + /** + * The `NodeEventTarget` is a Node.js-specific extension to `EventTarget` + * that emulates a subset of the `EventEmitter` API. + * @since v14.5.0 + */ + export interface NodeEventTarget extends EventTarget { + /** + * Node.js-specific extension to the `EventTarget` class that emulates the + * equivalent `EventEmitter` API. The only difference between `addListener()` and + * `addEventListener()` is that `addListener()` will return a reference to the + * `EventTarget`. + * @since v14.5.0 + */ + addListener(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that dispatches the + * `arg` to the list of handlers for `type`. + * @since v15.2.0 + * @returns `true` if event listeners registered for the `type` exist, + * otherwise `false`. + */ + emit(type: string, arg: any): boolean; + /** + * Node.js-specific extension to the `EventTarget` class that returns an array + * of event `type` names for which event listeners are registered. + * @since 14.5.0 + */ + eventNames(): string[]; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of event listeners registered for the `type`. + * @since v14.5.0 + */ + listenerCount(type: string): number; + /** + * Node.js-specific extension to the `EventTarget` class that sets the number + * of max event listeners as `n`. + * @since v14.5.0 + */ + setMaxListeners(n: number): void; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of max event listeners. + * @since v14.5.0 + */ + getMaxListeners(): number; + /** + * Node.js-specific alias for `eventTarget.removeEventListener()`. + * @since v14.5.0 + */ + off(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + /** + * Node.js-specific alias for `eventTarget.addEventListener()`. + * @since v14.5.0 + */ + on(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that adds a `once` + * listener for the given event `type`. This is equivalent to calling `on` + * with the `once` option set to `true`. + * @since v14.5.0 + */ + once(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class. If `type` is specified, + * removes all registered listeners for `type`, otherwise removes all registered + * listeners. + * @since v14.5.0 + */ + removeAllListeners(type?: string): this; + /** + * Node.js-specific extension to the `EventTarget` class that removes the + * `listener` for the given `type`. The only difference between `removeListener()` + * and `removeEventListener()` is that `removeListener()` will return a reference + * to the `EventTarget`. + * @since v14.5.0 + */ + removeListener(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + } + } + global { + namespace NodeJS { + interface EventEmitter = DefaultEventMap> { + [EventEmitter.captureRejectionSymbol]?(error: Error, event: Key, ...args: Args): void; + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: Key, listener: Listener1): this; + /** + * Adds the `listener` function to the end of the listeners array for the event + * named `eventName`. No checks are made to see if the `listener` has already + * been added. Multiple calls passing the same combination of `eventName` and + * `listener` will result in the `listener` being added, and called, multiple times. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The `emitter.prependListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.on('foo', () => console.log('a')); + * myEE.prependListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.1.101 + * @param eventName The name of the event. + * @param listener The callback function + */ + on(eventName: Key, listener: Listener1): this; + /** + * Adds a **one-time** `listener` function for the event named `eventName`. The + * next time `eventName` is triggered, this listener is removed and then invoked. + * + * ```js + * server.once('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The `emitter.prependOnceListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.once('foo', () => console.log('a')); + * myEE.prependOnceListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.3.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + once(eventName: Key, listener: Listener1): this; + /** + * Removes the specified `listener` from the listener array for the event named `eventName`. + * + * ```js + * const callback = (stream) => { + * console.log('someone connected!'); + * }; + * server.on('connection', callback); + * // ... + * server.removeListener('connection', callback); + * ``` + * + * `removeListener()` will remove, at most, one instance of a listener from the + * listener array. If any single listener has been added multiple times to the + * listener array for the specified `eventName`, then `removeListener()` must be + * called multiple times to remove each instance. + * + * Once an event is emitted, all listeners attached to it at the + * time of emitting are called in order. This implies that any `removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution + * will not remove them from`emit()` in progress. Subsequent events behave as expected. + * + * ```js + * import { EventEmitter } from 'node:events'; + * class MyEmitter extends EventEmitter {} + * const myEmitter = new MyEmitter(); + * + * const callbackA = () => { + * console.log('A'); + * myEmitter.removeListener('event', callbackB); + * }; + * + * const callbackB = () => { + * console.log('B'); + * }; + * + * myEmitter.on('event', callbackA); + * + * myEmitter.on('event', callbackB); + * + * // callbackA removes listener callbackB but it will still be called. + * // Internal listener array at time of emit [callbackA, callbackB] + * myEmitter.emit('event'); + * // Prints: + * // A + * // B + * + * // callbackB is now removed. + * // Internal listener array [callbackA] + * myEmitter.emit('event'); + * // Prints: + * // A + * ``` + * + * Because listeners are managed using an internal array, calling this will + * change the position indices of any listener registered _after_ the listener + * being removed. This will not impact the order in which listeners are called, + * but it means that any copies of the listener array as returned by + * the `emitter.listeners()` method will need to be recreated. + * + * When a single function has been added as a handler multiple times for a single + * event (as in the example below), `removeListener()` will remove the most + * recently added instance. In the example the `once('ping')` listener is removed: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const ee = new EventEmitter(); + * + * function pong() { + * console.log('pong'); + * } + * + * ee.on('ping', pong); + * ee.once('ping', pong); + * ee.removeListener('ping', pong); + * + * ee.emit('ping'); + * ee.emit('ping'); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeListener(eventName: Key, listener: Listener1): this; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: Key, listener: Listener1): this; + /** + * Removes all listeners, or those of the specified `eventName`. + * + * It is bad practice to remove listeners added elsewhere in the code, + * particularly when the `EventEmitter` instance was created by some other + * component or module (e.g. sockets or file streams). + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeAllListeners(eventName?: Key): this; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be + * modified for this specific `EventEmitter` instance. The value can be set to `Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.3.5 + */ + setMaxListeners(n: number): this; + /** + * Returns the current max listener value for the `EventEmitter` which is either + * set by `emitter.setMaxListeners(n)` or defaults to {@link EventEmitter.defaultMaxListeners}. + * @since v1.0.0 + */ + getMaxListeners(): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * console.log(util.inspect(server.listeners('connection'))); + * // Prints: [ [Function] ] + * ``` + * @since v0.1.26 + */ + listeners(eventName: Key): Array>; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.once('log', () => console.log('log once')); + * + * // Returns a new Array with a function `onceWrapper` which has a property + * // `listener` which contains the original listener bound above + * const listeners = emitter.rawListeners('log'); + * const logFnWrapper = listeners[0]; + * + * // Logs "log once" to the console and does not unbind the `once` event + * logFnWrapper.listener(); + * + * // Logs "log once" to the console and removes the listener + * logFnWrapper(); + * + * emitter.on('log', () => console.log('log persistently')); + * // Will return a new Array with a single function bound by `.on()` above + * const newListeners = emitter.rawListeners('log'); + * + * // Logs "log persistently" twice + * newListeners[0](); + * emitter.emit('log'); + * ``` + * @since v9.4.0 + */ + rawListeners(eventName: Key): Array>; + /** + * Synchronously calls each of the listeners registered for the event named `eventName`, in the order they were registered, passing the supplied arguments + * to each. + * + * Returns `true` if the event had listeners, `false` otherwise. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEmitter = new EventEmitter(); + * + * // First listener + * myEmitter.on('event', function firstListener() { + * console.log('Helloooo! first listener'); + * }); + * // Second listener + * myEmitter.on('event', function secondListener(arg1, arg2) { + * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); + * }); + * // Third listener + * myEmitter.on('event', function thirdListener(...args) { + * const parameters = args.join(', '); + * console.log(`event with parameters ${parameters} in third listener`); + * }); + * + * console.log(myEmitter.listeners('event')); + * + * myEmitter.emit('event', 1, 2, 3, 4, 5); + * + * // Prints: + * // [ + * // [Function: firstListener], + * // [Function: secondListener], + * // [Function: thirdListener] + * // ] + * // Helloooo! first listener + * // event with parameters 1, 2 in second listener + * // event with parameters 1, 2, 3, 4, 5 in third listener + * ``` + * @since v0.1.26 + */ + emit(eventName: Key, ...args: Args): boolean; + /** + * Returns the number of listeners listening for the event named `eventName`. + * If `listener` is provided, it will return how many times the listener is found + * in the list of the listeners of the event. + * @since v3.2.0 + * @param eventName The name of the event being listened for + * @param listener The event handler function + */ + listenerCount(eventName: Key, listener?: Listener2): number; + /** + * Adds the `listener` function to the _beginning_ of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName` + * and `listener` will result in the `listener` being added, and called, multiple times. + * + * ```js + * server.prependListener('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependListener(eventName: Key, listener: Listener1): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this + * listener is removed, and then invoked. + * + * ```js + * server.prependOnceListener('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependOnceListener(eventName: Key, listener: Listener1): this; + /** + * Returns an array listing the events for which the emitter has registered + * listeners. The values in the array are strings or `Symbol`s. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * const myEE = new EventEmitter(); + * myEE.on('foo', () => {}); + * myEE.on('bar', () => {}); + * + * const sym = Symbol('symbol'); + * myEE.on(sym, () => {}); + * + * console.log(myEE.eventNames()); + * // Prints: [ 'foo', 'bar', Symbol(symbol) ] + * ``` + * @since v6.0.0 + */ + eventNames(): Array<(string | symbol) & Key2>; + } + } + } + export = EventEmitter; +} +declare module "node:events" { + import events = require("events"); + export = events; +} diff --git a/tools/ui/node_modules/@types/node/fs.d.ts b/tools/ui/node_modules/@types/node/fs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..24f37dcfd79bc7659c79bcbd68484ac90158303c --- /dev/null +++ b/tools/ui/node_modules/@types/node/fs.d.ts @@ -0,0 +1,4714 @@ +/** + * The `node:fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'node:fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'node:fs'; + * ``` + * + * All file system operations have synchronous, callback, and promise-based + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/fs.js) + */ +declare module "fs" { + import { NonSharedBuffer } from "node:buffer"; + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import { URL } from "node:url"; + import * as promises from "node:fs/promises"; + export { promises }; + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + export type PathOrFileDescriptor = PathLike | number; + export type TimeLike = string | number | Date; + export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + export type BufferEncodingOption = + | "buffer" + | { + encoding: "buffer"; + }; + export interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; + export type OpenMode = number | string; + export type Mode = number | string; + export interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + export interface Stats extends StatsBase {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat}, {@link fstat}, and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. `Stat` objects are not to be created directly using the `new` keyword. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + export class Stats { + private constructor(); + } + export interface StatsFsBase { + /** Type of file system. */ + type: T; + /** Optimal transfer block size. */ + bsize: T; + /** Total data blocks in file system. */ + blocks: T; + /** Free blocks in file system. */ + bfree: T; + /** Available blocks for unprivileged users */ + bavail: T; + /** Total file nodes in file system. */ + files: T; + /** Free file nodes in file system. */ + ffree: T; + } + export interface StatsFs extends StatsFsBase {} + /** + * Provides information about a mounted file system. + * + * Objects returned from {@link statfs} and its synchronous counterpart are of + * this type. If `bigint` in the `options` passed to those methods is `true`, the + * numeric values will be `bigint` instead of `number`. + * + * ```console + * StatFs { + * type: 1397114950, + * bsize: 4096, + * blocks: 121938943, + * bfree: 61058895, + * bavail: 61058895, + * files: 999, + * ffree: 1000000 + * } + * ``` + * + * `bigint` version: + * + * ```console + * StatFs { + * type: 1397114950n, + * bsize: 4096n, + * blocks: 121938943n, + * bfree: 61058895n, + * bavail: 61058895n, + * files: 999n, + * ffree: 1000000n + * } + * ``` + * @since v19.6.0, v18.15.0 + */ + export class StatsFs {} + export interface BigIntStatsFs extends StatsFsBase {} + export interface StatFsOptions { + bigint?: boolean | undefined; + } + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v10.10.0 + */ + export class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v10.10.0 + */ + isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v10.10.0 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v10.10.0 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v10.10.0 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v10.10.0 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v10.10.0 + */ + isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ + name: Name; + /** + * The path to the parent directory of the file this `fs.Dirent` object refers to. + * @since v20.12.0, v18.20.0 + */ + parentPath: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + */ + export class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. + * @since v12.12.0 + */ + readonly path: string; + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be fulfilled after the resource has been + * closed. + * @since v12.12.0 + */ + close(): Promise; + close(cb: NoParamCallback): void; + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * @since v12.12.0 + */ + closeSync(): void; + /** + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. + * + * A promise is returned that will be fulfilled with an `fs.Dirent`, or `null` if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + /** + * Synchronously read the next directory entry as an `fs.Dirent`. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + */ + readSync(): Dirent | null; + /** + * Calls `dir.close()` if the directory handle is open, and returns a promise that + * fulfills when disposal is complete. + * @since v24.1.0 + */ + [Symbol.asyncDispose](): Promise; + /** + * Calls `dir.closeSync()` if the directory handle is open, and returns + * `undefined`. + * @since v24.1.0 + */ + [Symbol.dispose](): void; + } + /** + * Class: fs.StatWatcher + * @since v14.3.0, v12.20.0 + * Extends `EventEmitter` + * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. + */ + export interface StatWatcher extends EventEmitter { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.StatWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.StatWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + } + export interface FSWatcher extends EventEmitter { + /** + * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. + * @since v0.5.8 + */ + close(): void; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.FSWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.FSWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.FSWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.FSWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + /** + * events.EventEmitter + * 1. change + * 2. close + * 3. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | NonSharedBuffer) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | NonSharedBuffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | NonSharedBuffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener( + event: "change", + listener: (eventType: string, filename: string | NonSharedBuffer) => void, + ): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "change", + listener: (eventType: string, filename: string | NonSharedBuffer) => void, + ): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + } + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + export class ReadStream extends stream.Readable { + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: K, listener: ReadStreamEvents[K]): this; + on(event: K, listener: ReadStreamEvents[K]): this; + once(event: K, listener: ReadStreamEvents[K]): this; + prependListener(event: K, listener: ReadStreamEvents[K]): this; + prependOnceListener(event: K, listener: ReadStreamEvents[K]): this; + } + export interface Utf8StreamOptions { + /** + * Appends writes to dest file instead of truncating it. + * @default true + */ + append?: boolean | undefined; + /** + * Which type of data you can send to the write + * function, supported values are `'utf8'` or `'buffer'`. + * @default 'utf8' + */ + contentMode?: "utf8" | "buffer" | undefined; + /** + * A path to a file to be written to (mode controlled by the + * append option). + */ + dest?: string | undefined; + /** + * A file descriptor, something that is returned by `fs.open()` + * or `fs.openSync()`. + */ + fd?: number | undefined; + /** + * An object that has the same API as the `fs` module, useful + * for mocking, testing, or customizing the behavior of the stream. + */ + fs?: object | undefined; + /** + * Perform a `fs.fsyncSync()` every time a write is + * completed. + */ + fsync?: boolean | undefined; + /** + * The maximum length of the internal buffer. If a write + * operation would cause the buffer to exceed `maxLength`, the data written is + * dropped and a drop event is emitted with the dropped data + */ + maxLength?: number | undefined; + /** + * The maximum number of bytes that can be written; + * @default 16384 + */ + maxWrite?: number | undefined; + /** + * The minimum length of the internal buffer that is + * required to be full before flushing. + */ + minLength?: number | undefined; + /** + * Ensure directory for `dest` file exists when true. + * @default false + */ + mkdir?: boolean | undefined; + /** + * Specify the creating file mode (see `fs.open()`). + */ + mode?: number | string | undefined; + /** + * Calls flush every `periodicFlush` milliseconds. + */ + periodicFlush?: number | undefined; + /** + * A function that will be called when `write()`, + * `writeSync()`, or `flushSync()` encounters an `EAGAIN` or `EBUSY` error. + * If the return value is `true` the operation will be retried, otherwise it + * will bubble the error. The `err` is the error that caused this function to + * be called, `writeBufferLen` is the length of the buffer that was written, + * and `remainingBufferLen` is the length of the remaining buffer that the + * stream did not try to write. + */ + retryEAGAIN?: ((err: Error | null, writeBufferLen: number, remainingBufferLen: number) => boolean) | undefined; + /** + * Perform writes synchronously. + */ + sync?: boolean | undefined; + } + /** + * An optimized UTF-8 stream writer that allows for flushing all the internal + * buffering on demand. It handles `EAGAIN` errors correctly, allowing for + * customization, for example, by dropping content if the disk is busy. + * @since v24.6.0 + * @experimental + */ + export class Utf8Stream extends EventEmitter { + constructor(options: Utf8StreamOptions); + /** + * Whether the stream is appending to the file or truncating it. + */ + readonly append: boolean; + /** + * The type of data that can be written to the stream. Supported + * values are `'utf8'` or `'buffer'`. + * @default 'utf8' + */ + readonly contentMode: "utf8" | "buffer"; + /** + * Close the stream immediately, without flushing the internal buffer. + */ + destroy(): void; + /** + * Close the stream gracefully, flushing the internal buffer before closing. + */ + end(): void; + /** + * The file descriptor that is being written to. + */ + readonly fd: number; + /** + * The file that is being written to. + */ + readonly file: string; + /** + * Writes the current buffer to the file if a write was not in progress. Do + * nothing if `minLength` is zero or if it is already writing. + */ + flush(callback: (err: Error | null) => void): void; + /** + * Flushes the buffered data synchronously. This is a costly operation. + */ + flushSync(): void; + /** + * Whether the stream is performing a `fs.fsyncSync()` after every + * write operation. + */ + readonly fsync: boolean; + /** + * The maximum length of the internal buffer. If a write + * operation would cause the buffer to exceed `maxLength`, the data written is + * dropped and a drop event is emitted with the dropped data. + */ + readonly maxLength: number; + /** + * The minimum length of the internal buffer that is required to be + * full before flushing. + */ + readonly minLength: number; + /** + * Whether the stream should ensure that the directory for the + * `dest` file exists. If `true`, it will create the directory if it does not + * exist. + * @default false + */ + readonly mkdir: boolean; + /** + * The mode of the file that is being written to. + */ + readonly mode: number | string; + /** + * The number of milliseconds between flushes. If set to `0`, no + * periodic flushes will be performed. + */ + readonly periodicFlush: number; + /** + * Reopen the file in place, useful for log rotation. + * @param file A path to a file to be written to (mode + * controlled by the append option). + */ + reopen(file: PathLike): void; + /** + * Whether the stream is writing synchronously or asynchronously. + */ + readonly sync: boolean; + /** + * When the `options.contentMode` is set to `'utf8'` when the stream is created, + * the `data` argument must be a string. If the `contentMode` is set to `'buffer'`, + * the `data` argument must be a `Buffer`. + * @param data The data to write. + */ + write(data: string | Buffer): boolean; + /** + * Whether the stream is currently writing data to the file. + */ + readonly writing: boolean; + /** + * Calls `utf8Stream.destroy()`. + */ + [Symbol.dispose](): void; + /** + * events.EventEmitter + * 1. change + * 2. close + * 3. error + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "drop", listener: (data: string | Buffer) => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "write", listener: (n: number) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "drop", listener: (data: string | Buffer) => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "ready", listener: () => void): this; + on(event: "write", listener: (n: number) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "drop", listener: (data: string | Buffer) => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "ready", listener: () => void): this; + once(event: "write", listener: (n: number) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "drop", listener: (data: string | Buffer) => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "write", listener: (n: number) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "drop", listener: (data: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "write", listener: (n: number) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } + + /** + * The Keys are events of the ReadStream and the values are the functions that are called when the event is emitted. + */ + type ReadStreamEvents = { + close: () => void; + data: (chunk: Buffer | string) => void; + end: () => void; + error: (err: Error) => void; + open: (fd: number) => void; + pause: () => void; + readable: () => void; + ready: () => void; + resume: () => void; + } & CustomEvents; + + /** + * string & {} allows to allow any kind of strings for the event + * but still allows to have auto completion for the normal events. + */ + type CustomEvents = { [Key in string & {} | symbol]: (...args: any[]) => void }; + + /** + * The Keys are events of the WriteStream and the values are the functions that are called when the event is emitted. + */ + type WriteStreamEvents = { + close: () => void; + drain: () => void; + error: (err: Error) => void; + finish: () => void; + open: (fd: number) => void; + pipe: (src: stream.Readable) => void; + ready: () => void; + unpipe: (src: stream.Readable) => void; + } & CustomEvents; + /** + * * Extends `stream.Writable` + * + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + export class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: K, listener: WriteStreamEvents[K]): this; + on(event: K, listener: WriteStreamEvents[K]): this; + once(event: K, listener: WriteStreamEvents[K]): this; + prependListener(event: K, listener: WriteStreamEvents[K]): this; + prependOnceListener(event: K, listener: WriteStreamEvents[K]): this; + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'node:fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] + */ + export function truncate(path: PathLike, len: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function truncate(path: PathLike, callback: NoParamCallback): void; + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number): Promise; + } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] + */ + export function truncateSync(path: PathLike, len?: number): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncate(fd: number, len: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: NoParamCallback): void; + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number): Promise; + } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncateSync(fd: number, len?: number): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 + */ + export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 + */ + export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'node:fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 + */ + export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 + */ + export function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + /** @deprecated */ + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * {@link stat} follows symbolic links. Use {@link lstat} to look at the + * links themselves. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'node:fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + export interface StatSyncFn extends Function { + (path: PathLike, options?: undefined): Stats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }, + ): Stats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + }, + ): BigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + }, + ): Stats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + }, + ): BigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + }, + ): Stats | BigIntStats; + (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const statSync: StatSyncFn; + /** + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + /** + * Retrieves the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstatSync( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Stats; + export function fstatSync( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): BigIntStats; + export function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; + /** + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + /** + * Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfs(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void): void; + export function statfs( + path: PathLike, + options: + | (StatFsOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs | BigIntStatsFs) => void, + ): void; + export namespace statfs { + /** + * Asynchronous statfs(2) - Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * @param path A path to an existing file or directory on the file system to be queried. + */ + function __promisify__( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatFsOptions): Promise; + } + /** + * Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfsSync( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): StatsFs; + export function statfsSync( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): BigIntStatsFs; + export function statfsSync(path: PathLike, options?: StatFsOptions): StatsFs | BigIntStatsFs; + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than + * a possible + * exception are given to the completion callback. + * @since v0.1.31 + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.31 + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`. + * If the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. Junction + * points on NTFS volumes can only point to directories. + * + * Relative targets are relative to the link's parent directory. + * + * ```js + * import { symlink } from 'node:fs'; + * + * symlink('./mew', './mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` which points to `mew` in the + * same directory: + * + * ```bash + * $ tree . + * . + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + * @param [type='null'] + */ + export function symlink( + target: PathLike, + path: PathLike, + type: symlink.Type | undefined | null, + callback: NoParamCallback, + ): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + type Type = "dir" | "file" | "junction"; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 + * @param [type='null'] + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: NonSharedBuffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: BufferEncodingOption): NonSharedBuffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string | NonSharedBuffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..`, and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd` to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: NonSharedBuffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v9.2.0 + */ + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + function native( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: NonSharedBuffer) => void, + ): void; + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | NonSharedBuffer) => void, + ): void; + function native( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: BufferEncodingOption): NonSharedBuffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string | NonSharedBuffer; + export namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): NonSharedBuffer; + function native(path: PathLike, options?: EncodingOption): string | NonSharedBuffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 + */ + export function unlink(path: PathLike, callback: NoParamCallback): void; + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 + */ + export function unlinkSync(path: PathLike): void; + export interface RmDirOptions { + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. + * Use `fs.rm(path, { recursive: true, force: true })` instead. + * + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 + */ + export function rmdir(path: PathLike, callback: NoParamCallback): void; + export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirOptions): Promise; + } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 + */ + export function rmdirSync(path: PathLike, options?: RmDirOptions): void; + export interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + export function rm(path: PathLike, callback: NoParamCallback): void; + export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + export namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). Returns `undefined`. + * @since v14.14.0 + */ + export function rmSync(path: PathLike, options?: RmOptions): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created (for instance, if it was previously created). + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. If `recursive` is false and the directory exists, + * an `EEXIST` error occurs. + * + * ```js + * import { mkdir } from 'node:fs'; + * + * // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. + * mkdir('./tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'node:fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + export function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: Mode | MakeDirectoryOptions | null | undefined, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: NoParamCallback): void; + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: Mode | MakeDirectoryOptions | null, + ): Promise; + } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is `true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + export function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`import { sep } from 'node:path'`). + * + * ```js + * import { tmpdir } from 'node:os'; + * import { mkdtemp } from 'node:fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'node:path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: NonSharedBuffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp( + prefix: string, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: BufferEncodingOption): NonSharedBuffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string | NonSharedBuffer; + export interface DisposableTempDir extends Disposable { + /** + * The path of the created directory. + */ + path: string; + /** + * A function which removes the created directory. + */ + remove(): void; + /** + * The same as `remove`. + */ + [Symbol.dispose](): void; + } + /** + * Returns a disposable object whose `path` property holds the created directory + * path. When the object is disposed, the directory and its contents will be + * removed if it still exists. If the directory cannot be deleted, disposal will + * throw an error. The object has a `remove()` method which will perform the same + * task. + * + * + * + * For detailed information, see the documentation of `fs.mkdtemp()`. + * + * There is no callback-based version of this API because it is designed for use + * with the `using` syntax. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v24.4.0 + */ + export function mkdtempDisposableSync(prefix: string, options?: EncodingOption): DisposableTempDir; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)` where `files` is an array of the names of the files in the directory excluding `'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.1.8 + */ + export function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + callback: (err: NodeJS.ErrnoException | null, files: NonSharedBuffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | NonSharedBuffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + export function readdir( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options: + | "buffer" + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function __promisify__( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise[]>; + } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.1.21 + */ + export function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): NonSharedBuffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): string[] | NonSharedBuffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + export function readdirSync( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 + */ + export function close(fd: number, callback?: NoParamCallback): void; + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 + */ + export function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + mode: Mode | undefined | null, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param [flags='r'] See `support of file system `flags``. + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] + */ + export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds, `Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v0.4.2 + */ + export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 + */ + export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 + */ + export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 + */ + export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 + */ + export function fsync(fd: number, callback: NoParamCallback): void; + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.96 + */ + export function fsyncSync(fd: number): void; + export interface WriteOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `buffer.byteLength - offset` + */ + length?: number | undefined; + /** + * @default null + */ + position?: number | null | undefined; + } + /** + * Write `buffer` to the file specified by `fd`. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where `bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.2 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param options An object with the following properties: + * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`. + * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + buffer: TBuffer, + options: WriteOptions, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + export function write( + fd: number, + string: string, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param options An object with the following properties: + * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`. + * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + options?: WriteOptions, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + * @return The number of bytes written. + */ + export function writeSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset?: number | null, + length?: number | null, + position?: number | null, + ): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): number; + export type ReadPosition = number | bigint; + export interface ReadOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + export interface ReadOptionsWithBuffer extends ReadOptions { + buffer?: T | undefined; + } + /** @deprecated Use `ReadOptions` instead. */ + // TODO: remove in future major + export interface ReadSyncOptions extends ReadOptions {} + /** @deprecated Use `ReadOptionsWithBuffer` instead. */ + // TODO: remove in future major + export interface ReadAsyncOptions extends ReadOptionsWithBuffer {} + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 + * @param buffer The buffer that the data will be written to. + * @param offset The position in `buffer` to write the data to. + * @param length The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + /** + * Similar to the above `fs.read` function, this version takes an optional `options` object. + * If not otherwise specified in an `options` object, + * `buffer` defaults to `Buffer.alloc(16384)`, + * `offset` defaults to `0`, + * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 + * `position` defaults to `null` + * @since v12.17.0, 13.11.0 + */ + export function read( + fd: number, + options: ReadOptionsWithBuffer, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + buffer: TBuffer, + options: ReadOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NonSharedBuffer) => void, + ): void; + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__( + fd: number, + options: ReadOptionsWithBuffer, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__(fd: number): Promise<{ + bytesRead: number; + buffer: NonSharedBuffer; + }>; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + * @param [position='null'] + */ + export function readSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset: number, + length: number, + position: ReadPosition | null, + ): number; + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadOptions): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: NodeJS.ErrnoException | null, data: string) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile( + path: PathOrFileDescriptor, + callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, + ): void; + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): Promise; + } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of `fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): NonSharedBuffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): string | NonSharedBuffer; + export type WriteFileOptions = + | ( + & ObjectEncodingOptions + & Abortable + & { + mode?: Mode | undefined; + flag?: string | undefined; + flush?: boolean | undefined; + } + ) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling `fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'node:fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFile( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + callback: NoParamCallback, + ): void; + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): Promise; + } + /** + * Returns `undefined`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFileSync( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFile( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__( + file: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): Promise; + } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'node:fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFileSync( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export interface WatchFileOptions { + bigint?: boolean | undefined; + persistent?: boolean | undefined; + interval?: number | undefined; + } + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint?: false | undefined; + }) + | undefined, + listener: StatsListener, + ): StatWatcher; + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint: true; + }) + | undefined, + listener: BigIntStatsListener, + ): StatWatcher; + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watchFile(filename: PathLike, listener: StatsListener): StatWatcher; + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` + */ + export function unwatchFile(filename: PathLike, listener?: StatsListener): void; + export function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void; + export interface WatchOptions extends Abortable { + encoding?: BufferEncoding | "buffer" | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + } + export interface WatchOptionsWithBufferEncoding extends WatchOptions { + encoding: "buffer"; + } + export interface WatchOptionsWithStringEncoding extends WatchOptions { + encoding?: BufferEncoding | undefined; + } + export type WatchEventType = "rename" | "change"; + export type WatchListener = (event: WatchEventType, filename: T | null) => void; + export type StatsListener = (curr: Stats, prev: Stats) => void; + export type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of `eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned `fs.FSWatcher`. + * @since v0.5.10 + * @param listener + */ + export function watch( + filename: PathLike, + options?: WatchOptionsWithStringEncoding | BufferEncoding | null, + listener?: WatchListener, + ): FSWatcher; + export function watch( + filename: PathLike, + options: WatchOptionsWithBufferEncoding | "buffer", + listener: WatchListener, + ): FSWatcher; + export function watch( + filename: PathLike, + options: WatchOptions | BufferEncoding | "buffer" | null, + listener: WatchListener, + ): FSWatcher; + export function watch(filename: PathLike, listener: WatchListener): FSWatcher; + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'node:fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err` parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won't be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + /** @deprecated */ + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback` parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'node:fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 + */ + export function existsSync(path: PathLike): boolean; + export namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if `package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'node:fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file is readable and writable. + * access(file, constants.R_OK | constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function access(path: PathLike, callback: NoParamCallback): void; + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + /** + * Synchronously tests a user's permissions for the file or directory specified + * by `path`. The `mode` argument is an optional integer that specifies the + * accessibility checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and + * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'node:fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function accessSync(path: PathLike, mode?: number): void; + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | promises.FileHandle | undefined; + mode?: number | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + signal?: AbortSignal | null | undefined; + highWaterMark?: number | undefined; + } + interface FSImplementation { + open?: (...args: any[]) => any; + close?: (...args: any[]) => any; + } + interface CreateReadStreamFSImplementation extends FSImplementation { + read: (...args: any[]) => any; + } + interface CreateWriteStreamFSImplementation extends FSImplementation { + write: (...args: any[]) => any; + writev?: (...args: any[]) => any; + } + interface ReadStreamOptions extends StreamOptions { + fs?: CreateReadStreamFSImplementation | null | undefined; + end?: number | undefined; + } + interface WriteStreamOptions extends StreamOptions { + fs?: CreateWriteStreamFSImplementation | null | undefined; + flush?: boolean | undefined; + } + /** + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs` implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for `open` is also required. If `autoClose` is `true`, an override for `close` is + * also required. + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` option to be set to `r+` rather than the + * default `w`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs` implementations for `open`, `write`, `writev`, and `close`. Overriding `write()` without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for at least one of `write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close` is also required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the `path` argument and will use the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createWriteStream(path: PathLike, options?: BufferEncoding | WriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 + */ + export function fdatasync(fd: number, callback: NoParamCallback): void; + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.1.96 + */ + export function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'node:fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; + export namespace copyFile { + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; + } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'node:fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using `writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and `buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an `Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] + */ + export function writev( + fd: number, + buffers: TBuffers, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: TBuffers) => void, + ): void; + export function writev( + fd: number, + buffers: TBuffers, + position: number | null, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: TBuffers) => void, + ): void; + // Providing a default type parameter doesn't provide true BC for userland consumers, but at least suppresses TS2314 + // TODO: remove default in future major version + export interface WriteVResult { + bytesWritten: number; + buffers: T; + } + export namespace writev { + function __promisify__( + fd: number, + buffers: TBuffers, + position?: number, + ): Promise>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @param [position='null'] + * @return The number of bytes written. + */ + export function writevSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and `buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + */ + export function readv( + fd: number, + buffers: TBuffers, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: TBuffers) => void, + ): void; + export function readv( + fd: number, + buffers: TBuffers, + position: number | null, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: TBuffers) => void, + ): void; + // Providing a default type parameter doesn't provide true BC for userland consumers, but at least suppresses TS2314 + // TODO: remove default in future major version + export interface ReadVResult { + bytesRead: number; + buffers: T; + } + export namespace readv { + function __promisify__( + fd: number, + buffers: TBuffers, + position?: number, + ): Promise>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + + export interface OpenAsBlobOptions { + /** + * An optional mime type for the blob. + * + * @default 'undefined' + */ + type?: string | undefined; + } + + /** + * Returns a `Blob` whose data is backed by the given file. + * + * The file must not be modified after the `Blob` is created. Any modifications + * will cause reading the `Blob` data to fail with a `DOMException` error. + * Synchronous stat operations on the file when the `Blob` is created, and before + * each read in order to detect whether the file data has been modified on disk. + * + * ```js + * import { openAsBlob } from 'node:fs'; + * + * const blob = await openAsBlob('the.file.txt'); + * const ab = await blob.arrayBuffer(); + * blob.stream(); + * ``` + * @since v19.8.0 + */ + export function openAsBlob(path: PathLike, options?: OpenAsBlobOptions): Promise; + + export interface OpenDirOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + /** + * @default false + */ + recursive?: boolean | undefined; + } + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export function opendir( + path: PathLike, + options: OpenDirOptions, + cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void, + ): void; + export namespace opendir { + function __promisify__(path: PathLike, options?: OpenDirOptions): Promise; + } + export interface BigIntStats extends StatsBase { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + export interface BigIntOptions { + bigint: true; + } + export interface StatOptions { + bigint?: boolean | undefined; + } + export interface StatSyncOptions extends StatOptions { + throwIfNoEntry?: boolean | undefined; + } + interface CopyOptionsBase { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean | undefined; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean | undefined; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean | undefined; + /** + * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} + */ + mode?: number | undefined; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean | undefined; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean | undefined; + /** + * When true, path resolution for symlinks will be skipped + * @default false + */ + verbatimSymlinks?: boolean | undefined; + } + export interface CopyOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?: ((source: string, destination: string) => boolean | Promise) | undefined; + } + export interface CopySyncOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?: ((source: string, destination: string) => boolean) | undefined; + } + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cp( + source: string | URL, + destination: string | URL, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + export function cp( + source: string | URL, + destination: string | URL, + opts: CopyOptions, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + /** + * Synchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; + + // TODO: collapse + interface _GlobOptions { + /** + * Current working directory. + * @default process.cwd() + */ + cwd?: string | URL | undefined; + /** + * `true` if the glob should return paths as `Dirent`s, `false` otherwise. + * @default false + * @since v22.2.0 + */ + withFileTypes?: boolean | undefined; + /** + * Function to filter out files/directories or a + * list of glob patterns to be excluded. If a function is provided, return + * `true` to exclude the item, `false` to include it. + * If a string array is provided, each string should be a glob pattern that + * specifies paths to exclude. Note: Negation patterns (e.g., '!foo.js') are + * not supported. + * @default undefined + */ + exclude?: ((fileName: T) => boolean) | readonly string[] | undefined; + } + export interface GlobOptions extends _GlobOptions {} + export interface GlobOptionsWithFileTypes extends _GlobOptions { + withFileTypes: true; + } + export interface GlobOptionsWithoutFileTypes extends _GlobOptions { + withFileTypes?: false | undefined; + } + + /** + * Retrieves the files matching the specified pattern. + * + * ```js + * import { glob } from 'node:fs'; + * + * glob('*.js', (err, matches) => { + * if (err) throw err; + * console.log(matches); + * }); + * ``` + * @since v22.0.0 + */ + export function glob( + pattern: string | readonly string[], + callback: (err: NodeJS.ErrnoException | null, matches: string[]) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + callback: ( + err: NodeJS.ErrnoException | null, + matches: Dirent[], + ) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + callback: ( + err: NodeJS.ErrnoException | null, + matches: string[], + ) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptions, + callback: ( + err: NodeJS.ErrnoException | null, + matches: Dirent[] | string[], + ) => void, + ): void; + /** + * ```js + * import { globSync } from 'node:fs'; + * + * console.log(globSync('*.js')); + * ``` + * @since v22.0.0 + * @returns paths of files that match the pattern. + */ + export function globSync(pattern: string | readonly string[]): string[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + ): Dirent[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + ): string[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptions, + ): Dirent[] | string[]; +} +declare module "node:fs" { + export * from "fs"; +} diff --git a/tools/ui/node_modules/@types/node/fs/promises.d.ts b/tools/ui/node_modules/@types/node/fs/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6612bff37b2425236245a1fb487264e686cfc5c8 --- /dev/null +++ b/tools/ui/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1330 @@ +/** + * The `fs/promises` API provides asynchronous file system methods that return + * promises. + * + * The promise APIs use the underlying Node.js threadpool to perform file + * system operations off the event loop thread. These operations are not + * synchronized or threadsafe. Care must be taken when performing multiple + * concurrent modifications on the same file or data corruption may occur. + * @since v10.0.0 + */ +declare module "fs/promises" { + import { NonSharedBuffer } from "node:buffer"; + import { Abortable } from "node:events"; + import { Stream } from "node:stream"; + import { ReadableStream } from "node:stream/web"; + import { + BigIntStats, + BigIntStatsFs, + BufferEncodingOption, + constants as fsConstants, + CopyOptions, + Dir, + Dirent, + EncodingOption, + GlobOptions, + GlobOptionsWithFileTypes, + GlobOptionsWithoutFileTypes, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, + PathLike, + ReadOptions, + ReadOptionsWithBuffer, + ReadPosition, + ReadStream, + ReadVResult, + RmDirOptions, + RmOptions, + StatFsOptions, + StatOptions, + Stats, + StatsFs, + TimeLike, + WatchEventType, + WatchOptions as _WatchOptions, + WriteStream, + WriteVResult, + } from "node:fs"; + import { Interface as ReadlineInterface } from "node:readline"; + interface FileChangeInfo { + eventType: WatchEventType; + filename: T | null; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + /** @deprecated This interface will be removed in a future version. Use `import { ReadOptionsWithBuffer } from "node:fs"` instead. */ + interface FileReadOptions { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: ReadPosition | null; + } + interface CreateReadStreamOptions extends Abortable { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + end?: number | undefined; + highWaterMark?: number | undefined; + } + interface CreateWriteStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + flush?: boolean | undefined; + } + interface ReadableWebStreamOptions { + autoClose?: boolean | undefined; + } + // TODO: Add `EventEmitter` close + interface FileHandle { + /** + * The numeric file descriptor managed by the {FileHandle} object. + * @since v10.0.0 + */ + readonly fd: number; + /** + * Alias of `filehandle.writeFile()`. + * + * When operating on file handles, the mode cannot be changed from what it was set + * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + appendFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). + * @since v10.0.0 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + * @return Fulfills with `undefined` upon success. + */ + chown(uid: number, gid: number): Promise; + /** + * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). + * @since v10.0.0 + * @param mode the file mode bit mask. + * @return Fulfills with `undefined` upon success. + */ + chmod(mode: Mode): Promise; + /** + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is + * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from + * the current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If the `FileHandle` points to a character device that only supports blocking + * reads (such as keyboard or sound card), read operations do not finish until data + * is available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('/dev/input/event0'); + * // Create a stream from some character device. + * const stream = fd.createReadStream(); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('sample.txt'); + * fd.createReadStream({ start: 90, end: 99 }); + * ``` + * @since v16.11.0 + */ + createReadStream(options?: CreateReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` `open` option to be set to `r+` rather than + * the default `r`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * @since v16.11.0 + */ + createWriteStream(options?: CreateWriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. + * + * Unlike `filehandle.sync` this method does not flush modified metadata. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + datasync(): Promise; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + sync(): Promise; + /** + * Reads data from the file and stores that in the given buffer. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * @since v10.0.0 + * @param buffer A buffer that will be filled with the file data read. + * @param offset The location in the buffer at which to start filling. + * @param length The number of bytes to read. + * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an + * integer, the current file position will remain unchanged. + * @return Fulfills upon success with an object with two properties: + */ + read( + buffer: T, + offset?: number | null, + length?: number | null, + position?: ReadPosition | null, + ): Promise>; + read( + buffer: T, + options?: ReadOptions, + ): Promise>; + read( + options?: ReadOptionsWithBuffer, + ): Promise>; + /** + * Returns a byte-oriented `ReadableStream` that may be used to read the file's + * contents. + * + * An error will be thrown if this method is called more than once or is called + * after the `FileHandle` is closed or closing. + * + * ```js + * import { + * open, + * } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const chunk of file.readableWebStream()) + * console.log(chunk); + * + * await file.close(); + * ``` + * + * While the `ReadableStream` will read the file to completion, it will not + * close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method. + * @since v17.0.0 + */ + readableWebStream(options?: ReadableWebStreamOptions): ReadableStream; + /** + * Asynchronously reads the entire contents of a file. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support reading. + * + * If one or more `filehandle.read()` calls are made on a file handle and then a `filehandle.readFile()` call is made, the data will be read from the current + * position till the end of the file. It doesn't always read from the beginning + * of the file. + * @since v10.0.0 + * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the + * data will be a string. + */ + readFile( + options?: + | ({ encoding?: null | undefined } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + */ + readFile( + options: + | ({ encoding: BufferEncoding } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + */ + readFile( + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Convenience method to create a `readline` interface and stream over the file. + * See `filehandle.createReadStream()` for the options. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const line of file.readLines()) { + * console.log(line); + * } + * ``` + * @since v18.11.0 + */ + readLines(options?: CreateReadStreamOptions): ReadlineInterface; + /** + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. + */ + stat( + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + }, + ): Promise; + stat(opts?: StatOptions): Promise; + /** + * Truncates the file. + * + * If the file was larger than `len` bytes, only the first `len` bytes will be + * retained in the file. + * + * The following example retains only the first four bytes of the file: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle = null; + * try { + * filehandle = await open('temp.txt', 'r+'); + * await filehandle.truncate(4); + * } finally { + * await filehandle?.close(); + * } + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + truncate(len?: number): Promise; + /** + * Change the file system timestamps of the object referenced by the `FileHandle` then fulfills the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: TimeLike, mtime: TimeLike): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * The promise is fulfilled with no arguments upon success. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support writing. + * + * It is unsafe to use `filehandle.writeFile()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). + * + * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the + * current position till the end of the file. It doesn't always write from the + * beginning of the file. + * @since v10.0.0 + */ + writeFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Write `buffer` to the file. + * + * The promise is fulfilled with an object containing two properties: + * + * It is unsafe to use `filehandle.write()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). For this + * scenario, use `filehandle.createWriteStream()`. + * + * On Linux, positional writes do not work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v10.0.0 + * @param offset The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. + * @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current + * position. See the POSIX pwrite(2) documentation for more detail. + */ + write( + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + buffer: TBuffer, + options?: { offset?: number; length?: number; position?: number }, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + data: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + /** + * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. + * + * The promise is fulfilled with an object containing a two properties: + * + * It is unsafe to call `writev()` multiple times on the same file without waiting + * for the promise to be fulfilled (or rejected). + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * position. + */ + writev( + buffers: TBuffers, + position?: number, + ): Promise>; + /** + * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s + * @since v13.13.0, v12.17.0 + * @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @return Fulfills upon success an object containing two properties: + */ + readv( + buffers: TBuffers, + position?: number, + ): Promise>; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle; + * try { + * filehandle = await open('thefile.txt', 'r'); + * } finally { + * await filehandle?.close(); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + close(): Promise; + /** + * Calls `filehandle.close()` and returns a promise that fulfills when the + * filehandle is closed. + * @since v20.4.0, v18.8.0 + */ + [Symbol.asyncDispose](): Promise; + } + const constants: typeof fsConstants; + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If the accessibility check is successful, the promise is fulfilled with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access, constants } from 'node:fs/promises'; + * + * try { + * await access('/etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can access'); + * } catch { + * console.error('cannot access'); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file's state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v10.0.0 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { copyFile, constants } from 'node:fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * ``` + * @since v10.0.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; + /** + * Opens a `FileHandle`. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v10.0.0 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags?: string | number, mode?: Mode): Promise; + /** + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len` bytes. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise; + /** + * Removes the directory identified by `path`. + * + * Using `fsPromises.rmdir()` on a file (not a directory) results in the + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rmdir(path: PathLike, options?: RmDirOptions): Promise; + /** + * Removes files and directories (modeled on the standard POSIX `rm` utility). + * @since v14.14.0 + * @return Fulfills with `undefined` upon success. + */ + function rm(path: PathLike, options?: RmOptions): Promise; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * + * ```js + * import { mkdir } from 'node:fs/promises'; + * + * try { + * const projectFolder = new URL('./test/project/', import.meta.url); + * const createDir = await mkdir(projectFolder, { recursive: true }); + * + * console.log(`created ${createDir}`); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * @since v10.0.0 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned + * will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the returned array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from 'node:fs/promises'; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a directory. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function readdir( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise[]>; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * fulfilled with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, the link path + * returned will be passed as a `Buffer` object. + * @since v10.0.0 + * @return Fulfills with the `linkString` upon success. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink( + path: PathLike, + options?: ObjectEncodingOptions | string | null, + ): Promise; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `'dir'`, `'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will + * autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not + * exist, `'file'` will be used. Windows junction points require the destination + * path to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. Junction points on NTFS volumes + * can only point to directories. + * @since v10.0.0 + * @param [type='null'] + * @return Fulfills with `undefined` upon success. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v19.6.0, v18.15.0 + * @return Fulfills with the {fs.StatFs} object for the given `path`. + */ + function statfs( + path: PathLike, + opts?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function statfs( + path: PathLike, + opts: StatFsOptions & { + bigint: true; + }, + ): Promise; + function statfs(path: PathLike, opts?: StatFsOptions): Promise; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise; + /** + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the ownership on a symbolic link. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v14.5.0, v12.19.0 + * @return Fulfills with `undefined` upon success. + */ + function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Determines the actual location of `path` using the same semantics as the `fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `'buffer'`, the path returned will be + * passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v10.0.0 + * @return Fulfills with the resolved path upon success. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options?: ObjectEncodingOptions | BufferEncoding | null, + ): Promise; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs/promises'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * try { + * await mkdtemp(join(tmpdir(), 'foo-')); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the `prefix` must end with a trailing + * platform-specific path separator + * (`import { sep } from 'node:path'`). + * @since v10.0.0 + * @return Fulfills with a string containing the file system path of the newly created temporary directory. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp( + prefix: string, + options?: ObjectEncodingOptions | BufferEncoding | null, + ): Promise; + interface DisposableTempDir extends AsyncDisposable { + /** + * The path of the created directory. + */ + path: string; + /** + * A function which removes the created directory. + */ + remove(): Promise; + /** + * The same as `remove`. + */ + [Symbol.asyncDispose](): Promise; + } + /** + * The resulting Promise holds an async-disposable object whose `path` property + * holds the created directory path. When the object is disposed, the directory + * and its contents will be removed asynchronously if it still exists. If the + * directory cannot be deleted, disposal will throw an error. The object has an + * async `remove()` method which will perform the same task. + * + * Both this function and the disposal function on the resulting object are + * async, so it should be used with `await` + `await using` as in + * `await using dir = await fsPromises.mkdtempDisposable('prefix')`. + * + * + * + * For detailed information, see the documentation of `fsPromises.mkdtemp()`. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v24.4.0 + */ + function mkdtempDisposable(prefix: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * Any specified `FileHandle` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. + * + * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs/promises'; + * import { Buffer } from 'node:buffer'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * const promise = writeFile('message.txt', data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v10.0.0 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathLike | FileHandle, + data: + | string + | NodeJS.ArrayBufferView + | Iterable + | AsyncIterable + | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + /** + * If all data is successfully written to the file, and `flush` + * is `true`, `filehandle.sync()` is used to flush the data. + * @default false + */ + flush?: boolean | undefined; + } & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * The `path` may be specified as a `FileHandle` that has been opened + * for appending (using `fsPromises.open()`). + * @since v10.0.0 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile( + path: PathLike | FileHandle, + data: string | Uint8Array, + options?: (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined }) | BufferEncoding | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `Buffer` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory's contents will be + * returned. + * + * An example of reading a `package.json` file located in the same directory of the + * running code: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * try { + * const filePath = new URL('./package.json', import.meta.url); + * const contents = await readFile(filePath, { encoding: 'utf8' }); + * console.log(contents); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * + * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `FileHandle` has to support reading. + * @since v10.0.0 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ( + & ObjectEncodingOptions + & Abortable + & { + flag?: OpenMode | undefined; + } + ) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * + * Example using async iteration: + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + * @return Fulfills with an {fs.Dir}. + */ + function opendir(path: PathLike, options?: OpenDirOptions): Promise; + interface WatchOptions extends _WatchOptions { + maxQueue?: number | undefined; + overflow?: "ignore" | "throw" | undefined; + } + interface WatchOptionsWithBufferEncoding extends WatchOptions { + encoding: "buffer"; + } + interface WatchOptionsWithStringEncoding extends WatchOptions { + encoding?: BufferEncoding | undefined; + } + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * import { watch } from 'node:fs/promises'; + * + * const ac = new AbortController(); + * const { signal } = ac; + * setTimeout(() => ac.abort(), 10000); + * + * (async () => { + * try { + * const watcher = watch(__filename, { signal }); + * for await (const event of watcher) + * console.log(event); + * } catch (err) { + * if (err.name === 'AbortError') + * return; + * throw err; + * } + * })(); + * ``` + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. + * @since v15.9.0, v14.18.0 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options?: WatchOptionsWithStringEncoding | BufferEncoding, + ): NodeJS.AsyncIterator>; + function watch( + filename: PathLike, + options: WatchOptionsWithBufferEncoding | "buffer", + ): NodeJS.AsyncIterator>; + function watch( + filename: PathLike, + options: WatchOptions | BufferEncoding | "buffer", + ): NodeJS.AsyncIterator>; + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + * @return Fulfills with `undefined` upon success. + */ + function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise; + /** + * ```js + * import { glob } from 'node:fs/promises'; + * + * for await (const entry of glob('*.js')) + * console.log(entry); + * ``` + * @since v22.0.0 + * @returns An AsyncIterator that yields the paths of files + * that match the pattern. + */ + function glob(pattern: string | readonly string[]): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + ): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + ): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptions, + ): NodeJS.AsyncIterator; +} +declare module "node:fs/promises" { + export * from "fs/promises"; +} diff --git a/tools/ui/node_modules/@types/node/globals.d.ts b/tools/ui/node_modules/@types/node/globals.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9c6837d3a2fa11d5a4a10dc0a6c5d0f8d9fbd627 --- /dev/null +++ b/tools/ui/node_modules/@types/node/globals.d.ts @@ -0,0 +1,170 @@ +declare var global: typeof globalThis; + +declare var process: NodeJS.Process; +declare var console: Console; + +interface ErrorConstructor { + /** + * Creates a `.stack` property on `targetObject`, which when accessed returns + * a string representing the location in the code at which + * `Error.captureStackTrace()` was called. + * + * ```js + * const myObject = {}; + * Error.captureStackTrace(myObject); + * myObject.stack; // Similar to `new Error().stack` + * ``` + * + * The first line of the trace will be prefixed with + * `${myObject.name}: ${myObject.message}`. + * + * The optional `constructorOpt` argument accepts a function. If given, all frames + * above `constructorOpt`, including `constructorOpt`, will be omitted from the + * generated stack trace. + * + * The `constructorOpt` argument is useful for hiding implementation + * details of error generation from the user. For instance: + * + * ```js + * function a() { + * b(); + * } + * + * function b() { + * c(); + * } + * + * function c() { + * // Create an error without stack trace to avoid calculating the stack trace twice. + * const { stackTraceLimit } = Error; + * Error.stackTraceLimit = 0; + * const error = new Error(); + * Error.stackTraceLimit = stackTraceLimit; + * + * // Capture the stack trace above function b + * Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace + * throw error; + * } + * + * a(); + * ``` + */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + /** + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any; + /** + * The `Error.stackTraceLimit` property specifies the number of stack frames + * collected by a stack trace (whether generated by `new Error().stack` or + * `Error.captureStackTrace(obj)`). + * + * The default value is `10` but may be set to any valid JavaScript number. Changes + * will affect any stack trace captured _after_ the value has been changed. + * + * If set to a non-number value, or set to a negative number, stack traces will + * not capture any frames. + */ + stackTraceLimit: number; +} + +/** + * Enable this API with the `--expose-gc` CLI flag. + */ +declare var gc: NodeJS.GCFunction | undefined; + +declare namespace NodeJS { + interface CallSite { + getColumnNumber(): number | null; + getEnclosingColumnNumber(): number | null; + getEnclosingLineNumber(): number | null; + getEvalOrigin(): string | undefined; + getFileName(): string | null; + getFunction(): Function | undefined; + getFunctionName(): string | null; + getLineNumber(): number | null; + getMethodName(): string | null; + getPosition(): number; + getPromiseIndex(): number | null; + getScriptHash(): string; + getScriptNameOrSourceURL(): string | null; + getThis(): unknown; + getTypeName(): string | null; + isAsync(): boolean; + isConstructor(): boolean; + isEval(): boolean; + isNative(): boolean; + isPromiseAll(): boolean; + isToplevel(): boolean; + } + + interface ErrnoException extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean | undefined }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): this; + end(data: string | Uint8Array, cb?: () => void): this; + end(str: string, encoding?: BufferEncoding, cb?: () => void): this; + } + + interface ReadWriteStream extends ReadableStream, WritableStream {} + + interface RefCounted { + ref(): this; + unref(): this; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } + + type PartialOptions = { [K in keyof T]?: T[K] | undefined }; + + interface GCFunction { + (minor?: boolean): void; + (options: NodeJS.GCOptions & { execution: "async" }): Promise; + (options: NodeJS.GCOptions): void; + } + + interface GCOptions { + execution?: "sync" | "async" | undefined; + flavor?: "regular" | "last-resort" | undefined; + type?: "major-snapshot" | "major" | "minor" | undefined; + filename?: string | undefined; + } + + /** An iterable iterator returned by the Node.js API. */ + interface Iterator extends IteratorObject { + [Symbol.iterator](): NodeJS.Iterator; + } + + /** An async iterable iterator returned by the Node.js API. */ + interface AsyncIterator extends AsyncIteratorObject { + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + } +} diff --git a/tools/ui/node_modules/@types/node/globals.typedarray.d.ts b/tools/ui/node_modules/@types/node/globals.typedarray.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cae4c0b1aad37c0f47dcbe92415736813eab1c09 --- /dev/null +++ b/tools/ui/node_modules/@types/node/globals.typedarray.d.ts @@ -0,0 +1,41 @@ +export {}; // Make this a module + +declare global { + namespace NodeJS { + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float16Array + | Float32Array + | Float64Array; + type ArrayBufferView = + | TypedArray + | DataView; + + // The following aliases are required to allow use of non-shared ArrayBufferViews in @types/node + // while maintaining compatibility with TS <=5.6. + // TODO: remove once @types/node no longer supports TS 5.6, and replace with native types. + type NonSharedUint8Array = Uint8Array; + type NonSharedUint8ClampedArray = Uint8ClampedArray; + type NonSharedUint16Array = Uint16Array; + type NonSharedUint32Array = Uint32Array; + type NonSharedInt8Array = Int8Array; + type NonSharedInt16Array = Int16Array; + type NonSharedInt32Array = Int32Array; + type NonSharedBigUint64Array = BigUint64Array; + type NonSharedBigInt64Array = BigInt64Array; + type NonSharedFloat16Array = Float16Array; + type NonSharedFloat32Array = Float32Array; + type NonSharedFloat64Array = Float64Array; + type NonSharedDataView = DataView; + type NonSharedTypedArray = TypedArray; + type NonSharedArrayBufferView = ArrayBufferView; + } +} diff --git a/tools/ui/node_modules/@types/node/http.d.ts b/tools/ui/node_modules/@types/node/http.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b4cf59bff75ab4c2cb0f80e2ba604d2f8ffd4c0 --- /dev/null +++ b/tools/ui/node_modules/@types/node/http.d.ts @@ -0,0 +1,2154 @@ +/** + * To use the HTTP server and client one must import the `node:http` module. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```json + * { "content-length": "123", + * "content-type": "text/plain", + * "connection": "keep-alive", + * "host": "example.com", + * "accept": "*" } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders` property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders` list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'example.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/http.js) + */ +declare module "http" { + import { NonSharedBuffer } from "node:buffer"; + import * as stream from "node:stream"; + import { URL } from "node:url"; + import { LookupOptions } from "node:dns"; + import { EventEmitter } from "node:events"; + import { LookupFunction, Server as NetServer, Socket, TcpSocketConnectOpts } from "node:net"; + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + accept?: string | undefined; + "accept-encoding"?: string | undefined; + "accept-language"?: string | undefined; + "accept-patch"?: string | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + "alt-svc"?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + connection?: string | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + "proxy-authenticate"?: string | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "retry-after"?: string | undefined; + "sec-fetch-site"?: string | undefined; + "sec-fetch-mode"?: string | undefined; + "sec-fetch-user"?: string | undefined; + "sec-fetch-dest"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | undefined; + "sec-websocket-version"?: string | undefined; + "set-cookie"?: string[] | undefined; + "strict-transport-security"?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + upgrade?: string | undefined; + "user-agent"?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + "www-authenticate"?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends NodeJS.Dict { + accept?: string | string[] | undefined; + "accept-charset"?: string | string[] | undefined; + "accept-encoding"?: string | string[] | undefined; + "accept-language"?: string | string[] | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + "cdn-cache-control"?: string | undefined; + connection?: string | string[] | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | number | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-security-policy"?: string | undefined; + "content-security-policy-report-only"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | string[] | undefined; + dav?: string | string[] | undefined; + dnt?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-range"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + link?: string | string[] | undefined; + location?: string | undefined; + "max-forwards"?: string | undefined; + origin?: string | undefined; + pragma?: string | string[] | undefined; + "proxy-authenticate"?: string | string[] | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + "public-key-pins-report-only"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "referrer-policy"?: string | undefined; + refresh?: string | undefined; + "retry-after"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | string[] | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | string[] | undefined; + "sec-websocket-version"?: string | undefined; + server?: string | undefined; + "set-cookie"?: string | string[] | undefined; + "strict-transport-security"?: string | undefined; + te?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + "user-agent"?: string | undefined; + upgrade?: string | undefined; + "upgrade-insecure-requests"?: string | undefined; + vary?: string | undefined; + via?: string | string[] | undefined; + warning?: string | undefined; + "www-authenticate"?: string | string[] | undefined; + "x-content-type-options"?: string | undefined; + "x-dns-prefetch-control"?: string | undefined; + "x-frame-options"?: string | undefined; + "x-xss-protection"?: string | undefined; + } + interface ClientRequestArgs extends Pick { + _defaultAgent?: Agent | undefined; + agent?: Agent | boolean | undefined; + auth?: string | null | undefined; + createConnection?: + | (( + options: ClientRequestArgs, + oncreate: (err: Error | null, socket: stream.Duplex) => void, + ) => stream.Duplex | null | undefined) + | undefined; + defaultPort?: number | string | undefined; + family?: number | undefined; + headers?: OutgoingHttpHeaders | readonly string[] | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + insecureHTTPParser?: boolean | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + lookup?: LookupFunction | undefined; + /** + * @default 16384 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + port?: number | string | null | undefined; + protocol?: string | null | undefined; + setDefaultHeaders?: boolean | undefined; + setHost?: boolean | undefined; + signal?: AbortSignal | undefined; + socketPath?: string | undefined; + timeout?: number | undefined; + uniqueHeaders?: Array | undefined; + joinDuplicateHeaders?: boolean | undefined; + } + interface ServerOptions< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > { + /** + * Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. + */ + IncomingMessage?: Request | undefined; + /** + * Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. + */ + ServerResponse?: Response | undefined; + /** + * Sets the timeout value in milliseconds for receiving the entire request from the client. + * @see Server.requestTimeout for more information. + * @default 300000 + * @since v18.0.0 + */ + requestTimeout?: number | undefined; + /** + * It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. + * @default false + * @since v18.14.0 + */ + joinDuplicateHeaders?: boolean | undefined; + /** + * The number of milliseconds of inactivity a server needs to wait for additional incoming data, + * after it has finished writing the last response, before a socket will be destroyed. + * @see Server.keepAliveTimeout for more information. + * @default 5000 + * @since v18.0.0 + */ + keepAliveTimeout?: number | undefined; + /** + * An additional buffer time added to the + * `server.keepAliveTimeout` to extend the internal socket timeout. + * @since 24.6.0 + * @default 1000 + */ + keepAliveTimeoutBuffer?: number | undefined; + /** + * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. + * @default 30000 + */ + connectionsCheckingInterval?: number | undefined; + /** + * Sets the timeout value in milliseconds for receiving the complete HTTP headers from the client. + * See {@link Server.headersTimeout} for more information. + * @default 60000 + * @since 18.0.0 + */ + headersTimeout?: number | undefined; + /** + * Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. + * Default: @see stream.getDefaultHighWaterMark(). + * @since v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean | undefined; + /** + * Optionally overrides the value of `--max-http-header-size` for requests received by + * this server, i.e. the maximum length of request headers in bytes. + * @default 16384 + * @since v13.3.0 + */ + maxHeaderSize?: number | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default true + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it forces the server to respond with a 400 (Bad Request) status code + * to any HTTP/1.1 request message that lacks a Host header (as mandated by the specification). + * @default true + * @since 20.0.0 + */ + requireHostHeader?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * A list of response headers that should be sent only once. + * If the header's value is an array, the items will be joined using `; `. + */ + uniqueHeaders?: Array | undefined; + /** + * A callback which receives an + * incoming request and returns a boolean, to control which upgrade attempts + * should be accepted. Accepted upgrades will fire an `'upgrade'` event (or + * their sockets will be destroyed, if no listener is registered) while + * rejected upgrades will fire a `'request'` event like any non-upgrade + * request. + * @since v24.9.0 + * @default () => server.listenerCount('upgrade') > 0 + */ + shouldUpgradeCallback?: ((request: InstanceType) => boolean) | undefined; + /** + * If set to `true`, an error is thrown when writing to an HTTP response which does not have a body. + * @default false + * @since v18.17.0, v20.2.0 + */ + rejectNonStandardBodyWrites?: boolean | undefined; + /** + * If set to `true`, requests without `Content-Length` or `Transfer-Encoding` headers (indicating no body) + * will be initialized with an already-ended body stream, so they will never emit any stream events + * (like `'data'` or `'end'`). You can use `req.readableEnded` to detect this case. + * @default false + * @since v24.12.0 + */ + optimizeEmptyRequests?: boolean | undefined; + } + type RequestListener< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > = (req: InstanceType, res: InstanceType & { req: InstanceType }) => void; + /** + * @since v0.1.17 + */ + class Server< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ + setTimeout(msecs?: number, callback?: (socket: Socket) => void): this; + setTimeout(callback: (socket: Socket) => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @since v0.7.0 + */ + maxHeadersCount: number | null; + /** + * The maximum number of requests socket can handle + * before closing keep alive connection. + * + * A value of `0` will disable the limit. + * + * When the limit is reached it will set the `Connection` header value to `close`, + * but will not actually close the connection, subsequent requests sent + * after the limit is reached will get `503 Service Unavailable` as a response. + * @since v16.10.0 + */ + maxRequestsPerSocket: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v11.3.0, v10.14.0 + */ + headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. + * + * This timeout value is combined with the + * `server.keepAliveTimeoutBuffer` option to determine the actual socket + * timeout, calculated as: + * socketTimeout = keepAliveTimeout + keepAliveTimeoutBuffer + * If the server receives new data before the keep-alive timeout has fired, it + * will reset the regular inactivity timeout, i.e., `server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the HTTP server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ + keepAliveTimeout: number; + /** + * An additional buffer time added to the + * `server.keepAliveTimeout` to extend the internal socket timeout. + * + * This buffer helps reduce connection reset (`ECONNRESET`) errors by increasing + * the socket timeout slightly beyond the advertised keep-alive timeout. + * + * This option applies only to new incoming connections. + * @since v24.6.0 + * @default 1000 + */ + keepAliveTimeoutBuffer: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 + */ + requestTimeout: number; + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request + * or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: RequestListener): this; + addListener(event: "checkExpectation", listener: RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + addListener(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + addListener(event: "request", listener: RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "clientError", err: Error, socket: stream.Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer): boolean; + emit(event: "dropRequest", req: InstanceType, socket: stream.Duplex): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: RequestListener): this; + on(event: "checkExpectation", listener: RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + on( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + on(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + on(event: "request", listener: RequestListener): this; + on( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: RequestListener): this; + once(event: "checkExpectation", listener: RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + once( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + once(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + once(event: "request", listener: RequestListener): this; + once( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: RequestListener): this; + prependListener(event: "checkExpectation", listener: RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + prependListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependListener(event: "request", listener: RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + prependOnceListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependOnceListener(event: "request", listener: RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: NonSharedBuffer) => void, + ): this; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract outgoing message from + * the perspective of the participants of an HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + readonly req: Request; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + /** + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 + */ + readonly headersSent: boolean; + /** + * Alias of `outgoingMessage.socket`. + * @since v0.3.0 + * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. + */ + readonly connection: Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: Socket | null; + constructor(); + /** + * Once a socket is associated with the message and is connected, `socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value. If the header already exists in the to-be-sent + * headers, its value will be replaced. Use an array of strings to send multiple + * headers with the same name. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | readonly string[]): this; + /** + * Sets multiple header values for implicit headers. headers must be an instance of + * `Headers` or `Map`, if a header already exists in the to-be-sent headers, its + * value will be replaced. + * + * ```js + * const headers = new Headers({ foo: 'bar' }); + * outgoingMessage.setHeaders(headers); + * ``` + * + * or + * + * ```js + * const headers = new Map([['foo', 'bar']]); + * outgoingMessage.setHeaders(headers); + * ``` + * + * When headers have been set with `outgoingMessage.setHeaders()`, they will be + * merged with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * const headers = new Headers({ 'Content-Type': 'text/html' }); + * res.setHeaders(headers); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * @since v19.6.0, v18.15.0 + * @param name Header name + * @param value Header value + */ + setHeaders(headers: Headers | Map): this; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple + * times. + * + * If there were no previous values for the header, this is equivalent to calling `outgoingMessage.setHeader(name, value)`. + * + * Depending of the value of `options.uniqueHeaders` when the client request or the + * server were created, this will end up in the header being sent multiple times or + * a single time with values joined using `; `. + * @since v18.3.0, v16.17.0 + * @param name Header name + * @param value Header value + */ + appendHeader(name: string, value: string | readonly string[]): this; + /** + * Gets the value of the HTTP header with the given name. If that header is not + * set, the returned value will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` method does + * not prototypically inherit from the JavaScript `Object`. This means that + * typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * and others are not defined and will not work. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v7.7.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All names are lowercase. + * @since v7.7.0 + */ + getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v7.7.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + * @param name Header name + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers will **only** be emitted if the message is chunked encoded. If not, + * the trailers will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header field names in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Flushes the message headers. + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()` bypasses the optimization and kickstarts the message. + * @since v1.6.0 + */ + flushHeaders(): void; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ + statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ + statusMessage: string; + /** + * If set to `true`, Node.js will check whether the `Content-Length` header value and the size of the body, in bytes, are equal. + * Mismatching the `Content-Length` header value will result + * in an `Error` being thrown, identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * @since v18.10.0, v16.18.0 + */ + strictContentLength: boolean; + constructor(req: Request); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends an HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on `Server`. + * @since v0.3.0 + */ + writeContinue(callback?: () => void): void; + /** + * Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. The optional `callback` argument will be called when + * the response message has been written. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * 'x-trace-id': 'id for diagnostics', + * }); + * + * const earlyHintsCallback = () => console.log('early hints message sent'); + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }, earlyHintsCallback); + * ``` + * @since v18.11.0 + * @param hints An object containing the values of headers + * @param callback Will be called when the response message has been written + */ + writeEarlyHints(hints: Record, callback?: () => void): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain', + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is read in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * will check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `Error` being thrown. + * @since v0.1.30 + */ + writeHead( + statusCode: number, + statusMessage?: string, + headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], + ): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(callback?: () => void): void; + } + interface InformationEvent { + statusCode: number; + statusMessage: string; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object. `'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an `'error'` listener registered. + * + * Set `Content-Length` header to limit the response body size. + * If `response.strictContentLength` is set to `true`, mismatching the `Content-Length` header value will result in an `Error` being thrown, + * identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * + * `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. + * @since v0.1.17 + */ + class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + * @deprecated Since v17.0.0, v16.12.0 - Check `destroyed` instead. + */ + aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ + host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ + protocol: string; + /** + * When sending request through a keep-alive enabled agent, the underlying socket + * might be reused. But if server closes connection at unfortunate time, client + * may run into a 'ECONNRESET' error. + * + * ```js + * import http from 'node:http'; + * const agent = new http.Agent({ keepAlive: true }); + * + * // Server has a 5 seconds keep-alive timeout by default + * http + * .createServer((req, res) => { + * res.write('hello\n'); + * res.end(); + * }) + * .listen(3000); + * + * setInterval(() => { + * // Adapting a keep-alive agent + * http.get('http://localhost:3000', { agent }, (res) => { + * res.on('data', (data) => { + * // Do nothing + * }); + * }); + * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout + * ``` + * + * By marking a request whether it reused socket or not, we can do + * automatic error retry base on it. + * + * ```js + * import http from 'node:http'; + * const agent = new http.Agent({ keepAlive: true }); + * + * function retriableRequest() { + * const req = http + * .get('http://localhost:3000', { agent }, (res) => { + * // ... + * }) + * .on('error', (err) => { + * // Check if retry is needed + * if (req.reusedSocket && err.code === 'ECONNRESET') { + * retriableRequest(); + * } + * }); + * } + * + * retriableRequest(); + * ``` + * @since v13.0.0, v12.16.0 + */ + reusedSocket: boolean; + /** + * Limits maximum response headers count. If set to 0, no limit will be applied. + */ + maxHeadersCount: number; + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + /** + * The request method. + * @since v0.1.97 + */ + method: string; + /** + * The request path. + * @since v0.4.0 + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + onSocket(socket: Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0, v14.17.0 + */ + getRawHeaderNames(): string[]; + /** + * @deprecated + */ + addListener(event: "abort", listener: () => void): this; + addListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + addListener(event: "continue", listener: () => void): this; + addListener(event: "information", listener: (info: InformationEvent) => void): this; + addListener(event: "response", listener: (response: IncomingMessage) => void): this; + addListener(event: "socket", listener: (socket: Socket) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + on(event: "abort", listener: () => void): this; + on( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + on(event: "continue", listener: () => void): this; + on(event: "information", listener: (info: InformationEvent) => void): this; + on(event: "response", listener: (response: IncomingMessage) => void): this; + on(event: "socket", listener: (socket: Socket) => void): this; + on(event: "timeout", listener: () => void): this; + on( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + once(event: "abort", listener: () => void): this; + once( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + once(event: "continue", listener: () => void): this; + once(event: "information", listener: (info: InformationEvent) => void): this; + once(event: "response", listener: (response: IncomingMessage) => void): this; + once(event: "socket", listener: (socket: Socket) => void): this; + once(event: "timeout", listener: () => void): this; + once( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependListener(event: "abort", listener: () => void): this; + prependListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + prependListener(event: "continue", listener: () => void): this; + prependListener(event: "information", listener: (info: InformationEvent) => void): this; + prependListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependListener(event: "socket", listener: (socket: Socket) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependOnceListener(event: "abort", listener: () => void): this; + prependOnceListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: "continue", listener: () => void): this; + prependOnceListener(event: "information", listener: (info: InformationEvent) => void): this; + prependOnceListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependOnceListener(event: "socket", listener: (socket: Socket) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers, and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the `IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ + class IncomingMessage extends stream.Readable { + constructor(socket: Socket); + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from stream.Readable. + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v0.1.1 + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST', + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ + complete: boolean; + /** + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. + */ + connection: Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specified a socket + * type other than `net.Socket` or internally nulled. + * @since v0.3.0 + */ + socket: Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`, `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`, `last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`, `retry-after`, `server`, or `user-agent` are discarded. + * To allow duplicate values of the headers listed above to be joined, + * use the option `joinDuplicateHeaders` in {@link request} and {@link createServer}. See RFC 9110 Section 5.3 for more + * information. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with `; `. + * * For all other headers, the values are joined together with `, `. + * @since v0.1.5 + */ + headers: IncomingHttpHeaders; + /** + * Similar to `message.headers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': ['curl/7.22.0'], + * // host: ['127.0.0.1:8000'], + * // accept: ['*'] } + * console.log(request.headersDistinct); + * ``` + * @since v18.3.0, v16.17.0 + */ + headersDistinct: NodeJS.Dict; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ + trailers: NodeJS.Dict; + /** + * Similar to `message.trailers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * Only populated at the `'end'` event. + * @since v18.3.0, v16.17.0 + */ + trailersDistinct: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and `process.env.HOST` is undefined: + * + * ```console + * $ node + * > new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * URL { + * href: 'http://localhost/status?name=ryan', + * origin: 'http://localhost', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost', + * hostname: 'localhost', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * + * Ensure that you set `process.env.HOST` to the server's host name, or consider replacing this part entirely. If using `req.headers.host`, ensure proper + * validation is used, as clients may specify a custom `Host` header. + * @since v0.1.90 + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error` is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ + destroy(error?: Error): this; + } + interface ProxyEnv extends NodeJS.ProcessEnv { + HTTP_PROXY?: string | undefined; + HTTPS_PROXY?: string | undefined; + NO_PROXY?: string | undefined; + http_proxy?: string | undefined; + https_proxy?: string | undefined; + no_proxy?: string | undefined; + } + interface AgentOptions extends NodeJS.PartialOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean | undefined; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number | undefined; + /** + * Milliseconds to subtract from + * the server-provided `keep-alive: timeout=...` hint when determining socket + * expiration time. This buffer helps ensure the agent closes the socket + * slightly before the server does, reducing the chance of sending a request + * on a socket that’s about to be closed by the server. + * @since v24.7.0 + * @default 1000 + */ + agentKeepAliveTimeoutBuffer?: number | undefined; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number | undefined; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number | undefined; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number | undefined; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number | undefined; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: "fifo" | "lifo" | undefined; + /** + * Environment variables for proxy configuration. See + * [Built-in Proxy Support](https://nodejs.org/docs/latest-v24.x/api/http.html#built-in-proxy-support) for details. + * @since v24.5.0 + */ + proxyEnv?: ProxyEnv | undefined; + /** + * Default port to use when the port is not specified in requests. + * @since v24.5.0 + */ + defaultPort?: number | undefined; + /** + * The protocol to use for the agent. + * @since v24.5.0 + */ + protocol?: string | undefined; + } + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the `keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing `{agent: false}` as an option to the `http.get()` or `http.request()` functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false, // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * + * `options` in [`socket.connect()`](https://nodejs.org/docs/latest-v24.x/api/net.html#socketconnectoptions-connectlistener) are also supported. + * + * To configure any of them, a custom {@link Agent} instance must be created. + * + * ```js + * import http from 'node:http'; + * const keepAliveAgent = new http.Agent({ keepAlive: true }); + * options.agent = keepAliveAgent; + * http.request(options, onResponseCallback) + * ``` + * @since v0.3.4 + */ + class Agent extends EventEmitter { + /** + * By default set to 256. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ + maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ + maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ + maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ + readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ + readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ + readonly requests: NodeJS.ReadOnlyDict; + constructor(opts?: AgentOptions); + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 + */ + destroy(): void; + /** + * Produces a socket/stream to be used for HTTP requests. + * + * By default, this function behaves identically to `net.createConnection()`, synchronously + * returning the created socket. The optional `callback` parameter in the signature is not + * used by this default implementation. + * + * However, custom agents may override this method to provide greater flexibility, + * for example, to create sockets asynchronously. When overriding `createConnection`: + * + * 1. **Synchronous socket creation**: The overriding method can return the socket/stream directly. + * 2. **Asynchronous socket creation**: The overriding method can accept the `callback` and pass + * the created socket/stream to it (e.g., `callback(null, newSocket)`). If an error occurs during + * socket creation, it should be passed as the first argument to the `callback` (e.g., `callback(err)`). + * + * The agent will call the provided `createConnection` function with `options` and this internal + * `callback`. The `callback` provided by the agent has a signature of `(err, stream)`. + * @since v0.11.4 + * @param options Options containing connection details. Check `net.createConnection()` + * for the format of the options. For custom agents, this object is passed + * to the custom `createConnection` function. + * @param callback (Optional, primarily for custom agents) A function to be called by a custom + * `createConnection` implementation when the socket is created, especially for + * asynchronous operations. + * @returns `stream.Duplex` The created socket. This is returned by the default implementation + * or by a custom synchronous `createConnection` implementation. If a + * custom `createConnection` uses the `callback` for asynchronous operation, + * this return value might not be the primary way to obtain the socket. + */ + createConnection( + options: ClientRequestArgs, + callback?: (err: Error | null, stream: stream.Duplex) => void, + ): stream.Duplex | null | undefined; + /** + * Called when `socket` is detached from a request and could be persisted by the`Agent`. Default behavior is to: + * + * ```js + * socket.setKeepAlive(true, this.keepAliveMsecs); + * socket.unref(); + * return true; + * ``` + * + * This method can be overridden by a particular `Agent` subclass. If this + * method returns a falsy value, the socket will be destroyed instead of persisting + * it for use with the next request. + * + * The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`. + * @since v8.1.0 + */ + keepSocketAlive(socket: stream.Duplex): void; + /** + * Called when `socket` is attached to `request` after being persisted because of + * the keep-alive options. Default behavior is to: + * + * ```js + * socket.ref(); + * ``` + * + * This method can be overridden by a particular `Agent` subclass. + * + * The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`. + * @since v8.1.0 + */ + reuseSocket(socket: stream.Duplex, request: ClientRequest): void; + /** + * Get a unique name for a set of request options, to determine whether a + * connection can be reused. For an HTTP agent, this returns`host:port:localAddress` or `host:port:localAddress:family`. For an HTTPS agent, + * the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options + * that determine socket reusability. + * @since v0.11.4 + * @param options A set of options providing information for name generation + */ + getName(options?: ClientRequestArgs): string; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer(); + * + * // Listen to the request event + * server.on('request', (request, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.1.13 + */ + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + >(requestListener?: RequestListener): Server; + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + >( + options: ServerOptions, + requestListener?: RequestListener, + ): Server; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * `options` in `socket.connect()` are also supported. + * + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the `options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import http from 'node:http'; + * import { Buffer } from 'node:buffer'; + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!', + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData), + * }, + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort()` on the corresponding `AbortController` will behave the same way as calling `.destroy()` on the + * request. Specifically, the `'error'` event will be emitted with an error with + * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'` and the `cause`, if one was provided. + * @since v0.3.6 + */ + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: IncomingMessage) => void, + ): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET by default and calls `req.end()` automatically. The callback must take care to + * consume the response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the method set to GET by default. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + /** + * Performs the low-level validations on the provided `name` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `name` will result in a `TypeError` being thrown, + * identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Example: + * + * ```js + * import { validateHeaderName } from 'node:http'; + * + * try { + * validateHeaderName(''); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' + * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' + * } + * ``` + * @since v14.3.0 + * @param [label='Header name'] Label for error message. + */ + function validateHeaderName(name: string): void; + /** + * Performs the low-level validations on the provided `value` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `value` will result in a `TypeError` being thrown. + * + * * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Examples: + * + * ```js + * import { validateHeaderValue } from 'node:http'; + * + * try { + * validateHeaderValue('x-my-header', undefined); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true + * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' + * } + * + * try { + * validateHeaderValue('x-my-header', 'oʊmɪɡə'); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true + * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' + * } + * ``` + * @since v14.3.0 + * @param name Header name + * @param value Header value + */ + function validateHeaderValue(name: string, value: string): void; + /** + * Set the maximum number of idle HTTP parsers. + * @since v18.8.0, v16.18.0 + * @param [max=1000] + */ + function setMaxIdleHTTPParsers(max: number): void; + /** + * Global instance of `Agent` which is used as the default for all HTTP client + * requests. Diverges from a default `Agent` configuration by having `keepAlive` + * enabled and a `timeout` of 5 seconds. + * @since v0.5.9 + */ + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; + /** + * A browser-compatible implementation of `WebSocket`. + * @since v22.5.0 + */ + const WebSocket: typeof import("undici-types").WebSocket; + /** + * @since v22.5.0 + */ + const CloseEvent: typeof import("undici-types").CloseEvent; + /** + * @since v22.5.0 + */ + const MessageEvent: typeof import("undici-types").MessageEvent; +} +declare module "node:http" { + export * from "http"; +} diff --git a/tools/ui/node_modules/@types/node/http2.d.ts b/tools/ui/node_modules/@types/node/http2.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ac971607fbfd0041eb02cb7ff043dbae86a3731 --- /dev/null +++ b/tools/ui/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2831 @@ +/** + * The `node:http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. + * It can be accessed using: + * + * ```js + * import http2 from 'node:http2'; + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/http2.js) + */ +declare module "http2" { + import { NonSharedBuffer } from "node:buffer"; + import EventEmitter = require("node:events"); + import * as fs from "node:fs"; + import * as net from "node:net"; + import * as stream from "node:stream"; + import * as tls from "node:tls"; + import * as url from "node:url"; + import { + IncomingHttpHeaders as Http1IncomingHttpHeaders, + IncomingMessage, + OutgoingHttpHeaders, + ServerResponse, + } from "node:http"; + export { OutgoingHttpHeaders } from "node:http"; + export interface IncomingHttpStatusHeader { + ":status"?: number | undefined; + } + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string | undefined; + ":method"?: string | undefined; + ":authority"?: string | undefined; + ":scheme"?: string | undefined; + } + // Http2Stream + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + /** @deprecated */ + sumDependencyWeight?: number | undefined; + /** @deprecated */ + weight?: number | undefined; + } + export interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + export interface StatOptions { + offset: number; + length: number; + } + export interface ServerStreamFileResponseOptions { + statCheck?: + | ((stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void) + | undefined; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?: ((err: NodeJS.ErrnoException) => void) | undefined; + } + export interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set to `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined` if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be `undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session | undefined; + /** + * Provides miscellaneous information about the current state of the `Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * @deprecated Priority signaling is no longer supported in Node.js. + */ + priority(options: unknown): void; + /** + * ```js + * import http2 from 'node:http2'; + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener( + event: "frameError", + listener: (frameType: number, errorCode: number, id: number) => void, + ): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: NonSharedBuffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number, id: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, id: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, id: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener( + event: "frameError", + listener: (frameType: number, errorCode: number, id: number) => void, + ): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener( + event: "frameError", + listener: (frameType: number, errorCode: number, id: number) => void, + ): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: "continue", listener: () => {}): this; + addListener( + event: "headers", + listener: ( + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener( + event: "response", + listener: ( + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "continue"): boolean; + emit( + event: "headers", + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit( + event: "response", + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "continue", listener: () => {}): this; + on( + event: "headers", + listener: ( + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on( + event: "response", + listener: ( + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "continue", listener: () => {}): this; + once( + event: "headers", + listener: ( + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once( + event: "response", + listener: ( + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "continue", listener: () => {}): this; + prependListener( + event: "headers", + listener: ( + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener( + event: "response", + listener: ( + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "continue", listener: () => {}): this; + prependOnceListener( + event: "headers", + listener: ( + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener( + event: "response", + listener: ( + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every `Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream` instance created for the push stream passed as the second argument, or an `Error` passed as the first argument. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to `true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream( + headers: OutgoingHttpHeaders, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + pushStream( + headers: OutgoingHttpHeaders, + options?: Pick, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + /** + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * Initiates a response. When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be used to send trailing header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders | readonly string[], options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the `http2stream.respondWithFD()` method will + * perform an `fs.fstat()` call to collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either `http2stream.sendTrailers()` + * or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD( + fd: number | fs.promises.FileHandle, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptions, + ): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream` will be closed using an + * `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * If the `onError` callback is defined, then it will be called. Otherwise, the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.error(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate `304` response: + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile( + path: string, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptionsWithError, + ): void; + } + // Http2Session + export interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + export interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + waitForTrailers?: boolean | undefined; + signal?: AbortSignal | undefined; + } + export interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + export interface Http2Session extends EventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol` property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise `false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect` callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this `Http2Session`. + * The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the `http2session.settings()` method. + * Will be `false` once all sent `SETTINGS` frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. + * The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to `http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or `tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error` is not undefined, an `'error'` event will be emitted immediately before the `'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the `Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false` otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the `maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView` containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING` payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: NonSharedBuffer) => void): boolean; + ping( + payload: NodeJS.ArrayBufferView, + callback: (err: Error | null, duration: number, payload: NonSharedBuffer) => void, + ): boolean; + /** + * Calls `ref()` on this `Http2Session` instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * import http2 from 'node:http2'; + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0, v14.18.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new `SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true` while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings( + settings: Settings, + callback?: (err: Error | null, settings: Settings, duration: number) => void, + ): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "frameError", + listener: (frameType: number, errorCode: number, id: number) => void, + ): this; + addListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void, + ): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "ping", listener: () => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, id: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "ping"): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, id: number) => void): this; + on( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void, + ): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "ping", listener: () => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, id: number) => void): this; + once( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void, + ): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "ping", listener: () => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "frameError", + listener: (frameType: number, errorCode: number, id: number) => void, + ): this; + prependListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void, + ): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "ping", listener: () => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "frameError", + listener: (frameType: number, errorCode: number, id: number) => void, + ): this; + prependOnceListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "ping", listener: () => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()` creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * When a `ClientHttp2Session` is first created, the socket may not yet be + * connected. if `clienthttp2session.request()` is called during this time, the + * actual request will be deferred until the socket is ready to go. + * If the `session` is closed before the actual request be executed, an `ERR_HTTP2_GOAWAY_SESSION` is thrown. + * + * This method is only available if `http2session.type` is equal to `http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * import http2 from 'node:http2'; + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS, + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request( + headers?: OutgoingHttpHeaders | readonly string[], + options?: ClientSessionRequestOptions, + ): ClientHttp2Stream; + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "origin", listener: (origins: string[]) => void): this; + addListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + addListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "origin", origins: readonly string[]): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit( + event: "stream", + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "origin", listener: (origins: string[]) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "origin", listener: (origins: string[]) => void): this; + once( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + once( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "origin", listener: (origins: string[]) => void): this; + prependListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "origin", listener: (origins: string[]) => void): this; + prependOnceListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependOnceListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + export interface ServerHttp2Session< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends Http2Session { + readonly server: + | Http2Server + | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * import http2 from 'node:http2'; + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * import http2 from 'node:http2'; + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL `'https://example.org/foo/bar'` is the ASCII string` 'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * import http2 from 'node:http2'; + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + addListener( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + addListener( + event: "stream", + listener: ( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit( + event: "connect", + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ): boolean; + emit( + event: "stream", + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + flags: number, + rawHeaders: string[], + ): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + on( + event: "stream", + listener: ( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + once( + event: "stream", + listener: ( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + prependListener( + event: "stream", + listener: ( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + prependOnceListener( + event: "stream", + listener: ( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + // Http2Server + export interface SessionOptions { + /** + * Sets the maximum dynamic table size for deflating header fields. + * @default 4Kib + */ + maxDeflateDynamicTableSize?: number | undefined; + /** + * Sets the maximum number of settings entries per `SETTINGS` frame. + * The minimum value allowed is `1`. + * @default 32 + */ + maxSettings?: number | undefined; + /** + * Sets the maximum memory that the `Http2Session` is permitted to use. + * The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. + * The minimum value allowed is `1`. + * This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, + * but new `Http2Stream` instances will be rejected while this limit is exceeded. + * The current number of `Http2Stream` sessions, the current memory use of the header compression tables, + * current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. + * @default 10 + */ + maxSessionMemory?: number | undefined; + /** + * Sets the maximum number of header entries. + * This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. + * The minimum value is `1`. + * @default 128 + */ + maxHeaderListPairs?: number | undefined; + /** + * Sets the maximum number of outstanding, unacknowledged pings. + * @default 10 + */ + maxOutstandingPings?: number | undefined; + /** + * Sets the maximum allowed size for a serialized, compressed block of headers. + * Attempts to send headers that exceed this limit will result in + * a `'frameError'` event being emitted and the stream being closed and destroyed. + */ + maxSendHeaderBlockLength?: number | undefined; + /** + * Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. + * @default http2.constants.PADDING_STRATEGY_NONE + */ + paddingStrategy?: number | undefined; + /** + * Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. + * Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. + * @default 100 + */ + peerMaxConcurrentStreams?: number | undefined; + /** + * The initial settings to send to the remote peer upon connection. + */ + settings?: Settings | undefined; + /** + * The array of integer values determines the settings types, + * which are included in the `CustomSettings`-property of the received remoteSettings. + * Please see the `CustomSettings`-property of the `Http2Settings` object for more information, on the allowed setting types. + */ + remoteCustomSettings?: number[] | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + /** + * If `true`, it turns on strict leading + * and trailing whitespace validation for HTTP/2 header field names and values + * as per [RFC-9113](https://www.rfc-editor.org/rfc/rfc9113.html#section-8.2.1). + * @since v24.2.0 + * @default true + */ + strictFieldWhitespaceValidation?: boolean | undefined; + } + export interface ClientSessionOptions extends SessionOptions { + /** + * Sets the maximum number of reserved push streams the client will accept at any given time. + * Once the current number of currently reserved push streams exceeds reaches this limit, + * new push streams sent by the server will be automatically rejected. + * The minimum allowed value is 0. The maximum allowed value is 232-1. + * A negative value sets this option to the maximum allowed value. + * @default 200 + */ + maxReservedRemoteStreams?: number | undefined; + /** + * An optional callback that receives the `URL` instance passed to `connect` and the `options` object, + * and returns any `Duplex` stream that is to be used as the connection for this session. + */ + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + /** + * The protocol to connect with, if not set in the `authority`. + * Value may be either `'http:'` or `'https:'`. + * @default 'https:' + */ + protocol?: "http:" | "https:" | undefined; + } + export interface ServerSessionOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends SessionOptions { + streamResetBurst?: number | undefined; + streamResetRate?: number | undefined; + Http1IncomingMessage?: Http1Request | undefined; + Http1ServerResponse?: Http1Response | undefined; + Http2ServerRequest?: Http2Request | undefined; + Http2ServerResponse?: Http2Response | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends ServerSessionOptions {} + export interface SecureServerOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface HTTP2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + export interface Http2Server< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends net.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + addListener( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + addListener( + event: "stream", + listener: ( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit( + event: "checkContinue", + request: InstanceType, + response: InstanceType, + ): boolean; + emit(event: "request", request: InstanceType, response: InstanceType): boolean; + emit( + event: "session", + session: ServerHttp2Session, + ): boolean; + emit( + event: "sessionError", + err: Error, + session: ServerHttp2Session, + ): boolean; + emit( + event: "stream", + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + flags: number, + rawHeaders: string[], + ): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + on( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + on( + event: "stream", + listener: ( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + once( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + once( + event: "stream", + listener: ( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependListener( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + prependListener( + event: "stream", + listener: ( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependOnceListener( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + prependOnceListener( + event: "stream", + listener: ( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + flags: number, + rawHeaders: string[], + ) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface Http2SecureServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends tls.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + addListener( + event: "sessionError", + listener: (err: Error) => void, + session: ServerHttp2Session, + ): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit( + event: "checkContinue", + request: InstanceType, + response: InstanceType, + ): boolean; + emit(event: "request", request: InstanceType, response: InstanceType): boolean; + emit( + event: "session", + session: ServerHttp2Session, + ): boolean; + emit( + event: "sessionError", + err: Error, + session: ServerHttp2Session, + ): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + on( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + once( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependListener( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependOnceListener( + event: "sessionError", + listener: ( + err: Error, + session: ServerHttp2Session, + ) => void, + ): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + export class Http2ServerRequest extends stream.Readable { + constructor( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + options: stream.ReadableOptions, + rawHeaders: readonly string[], + ); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from `req.headers[':authority']` if present. Otherwise, it is derived from `req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns `'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream`s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): NonSharedBuffer | string | null; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: NonSharedBuffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + export class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple times. + * + * If there were no previous values for the header, this is equivalent to calling {@link setHeader}. + * + * Attempting to set a header field name or value that contains invalid characters will result in a + * [TypeError](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-typeerror) being thrown. + * + * ```js + * // Returns headers including "set-cookie: a" and "set-cookie: b" + * const server = http2.createServer((req, res) => { + * res.setHeader('set-cookie', 'a'); + * res.appendHeader('set-cookie', 'b'); + * res.writeHead(200); + * res.end('ok'); + * }); + * ``` + * @since v20.12.0 + */ + appendHeader(name: string, value: string | string[]): void; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 `request` object. + * @since v15.7.0 + */ + readonly req: Request; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ""; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): this; + end(data: string | Uint8Array, callback?: () => void): this; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | readonly string[]): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `node:http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and `Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a status `103 Early Hints` to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }); + * ``` + * @since v18.11.0 + */ + writeEarlyHints(hints: Record): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the `Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | readonly string[]): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders | readonly string[]): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse( + headers: OutgoingHttpHeaders, + callback: (err: Error | null, res: Http2ServerResponse) => void, + ): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session` instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + export function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * import http2 from 'node:http2'; + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + export function getPackedSettings(settings: Settings): NonSharedBuffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + export function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session` instances. + * + * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * import http2 from 'node:http2'; + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8000); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + export function createServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + options: ServerOptions, + onRequestHandler?: (request: InstanceType, response: InstanceType) => void, + ): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session` instances. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8443); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + export function createSecureServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + options: SecureServerOptions, + onRequestHandler?: (request: InstanceType, response: InstanceType) => void, + ): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * import http2 from 'node:http2'; + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + export function connect( + authority: string | url.URL, + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + /** + * Create an HTTP/2 server session from an existing socket. + * @param socket A Duplex Stream + * @param options Any `{@link createServer}` options can be provided. + * @since v20.12.0 + */ + export function performServerHandshake< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + socket: stream.Duplex, + options?: ServerOptions, + ): ServerHttp2Session; +} +declare module "node:http2" { + export * from "http2"; +} diff --git a/tools/ui/node_modules/@types/node/https.d.ts b/tools/ui/node_modules/@types/node/https.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ddb6689e23cf780f831047e92c1649593cf1951f --- /dev/null +++ b/tools/ui/node_modules/@types/node/https.d.ts @@ -0,0 +1,585 @@ +/** + * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a + * separate module. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/https.js) + */ +declare module "https" { + import { NonSharedBuffer } from "node:buffer"; + import { Duplex } from "node:stream"; + import * as tls from "node:tls"; + import * as http from "node:http"; + import { URL } from "node:url"; + interface ServerOptions< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends http.ServerOptions, tls.TlsOptions {} + interface RequestOptions extends http.RequestOptions, tls.SecureContextOptions { + checkServerIdentity?: + | ((hostname: string, cert: tls.DetailedPeerCertificate) => Error | undefined) + | undefined; + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + } + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * + * Like `http.Agent`, the `createConnection(options[, callback])` method can be overridden to customize + * how TLS connections are established. + * + * > See [`agent.createConnection()`](https://nodejs.org/docs/latest-v24.x/api/http.html#agentcreateconnectionoptions-callback) + * for details on overriding this method, including asynchronous socket creation with a callback. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + createConnection( + options: RequestOptions, + callback?: (err: Error | null, stream: Duplex) => void, + ): Duplex | null | undefined; + getName(options?: RequestOptions): string; + } + interface Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor( + options: ServerOptions, + requestListener?: http.RequestListener, + ); + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Duplex) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: http.RequestListener): this; + addListener(event: "checkExpectation", listener: http.RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + addListener(event: "request", listener: http.RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "keylog", line: NonSharedBuffer, tlsSocket: tls.TLSSocket): boolean; + emit( + event: "newSession", + sessionId: NonSharedBuffer, + sessionData: NonSharedBuffer, + callback: () => void, + ): boolean; + emit( + event: "OCSPRequest", + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ): boolean; + emit( + event: "resumeSession", + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ): boolean; + emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Duplex): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType, + ): boolean; + emit(event: "clientError", err: Error, socket: Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: Duplex, head: NonSharedBuffer): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: Duplex, head: NonSharedBuffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this; + on( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + on( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Duplex) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: http.RequestListener): this; + on(event: "checkExpectation", listener: http.RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + on( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + on(event: "request", listener: http.RequestListener): this; + on( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Duplex) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: http.RequestListener): this; + once(event: "checkExpectation", listener: http.RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + once( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + once(event: "request", listener: http.RequestListener): this; + once( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Duplex) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: http.RequestListener): this; + prependListener(event: "checkExpectation", listener: http.RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + prependListener(event: "request", listener: http.RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Duplex) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: http.RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: http.RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + prependOnceListener(event: "request", listener: http.RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: NonSharedBuffer) => void, + ): this; + } + /** + * ```js + * // curl -k https://localhost:8000/ + * import https from 'node:https'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * import https from 'node:https'; + * import fs from 'node:fs'; + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample', + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + >(requestListener?: http.RequestListener): Server; + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + >( + options: ServerOptions, + requestListener?: http.RequestListener, + ): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted: `ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`, `secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import https from 'node:https'; + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false, + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * import tls from 'node:tls'; + * import https from 'node:https'; + * import crypto from 'node:crypto'; + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha256 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * import https from 'node:https'; + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function get( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + let globalAgent: Agent; +} +declare module "node:https" { + export * from "https"; +} diff --git a/tools/ui/node_modules/@types/node/index.d.ts b/tools/ui/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c140e0b49b51d08f91a4a5b68b096d54f746b982 --- /dev/null +++ b/tools/ui/node_modules/@types/node/index.d.ts @@ -0,0 +1,101 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * 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. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.8+. + +// Reference required TypeScript libraries: +/// +/// +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript 5.7+: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/tools/ui/node_modules/@types/node/inspector.d.ts b/tools/ui/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd0b888890c900ce32a5ebe9c9a016f7d455a358 --- /dev/null +++ b/tools/ui/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,277 @@ +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/inspector.js) + */ +declare module "inspector" { + import EventEmitter = require("node:events"); + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + * @since v12.11.0 + */ + connectToMainThread(): void; + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + } + /** + * Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the [security warning](https://nodejs.org/docs/latest-v24.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure) + * regarding the `host` parameter usage. + * @param port Port to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Defaults to what was specified on the CLI. + * @returns Disposable that calls `inspector.close()`. + */ + function open(port?: number, host?: string, wait?: boolean): Disposable; + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help, see: https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help, see: https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + /** + * Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; + // These methods are exposed by the V8 inspector console API (inspector/v8-console.h). + // The method signatures differ from those of the Node.js console, and are deliberately + // typed permissively. + interface InspectorConsole { + debug(...data: any[]): void; + error(...data: any[]): void; + info(...data: any[]): void; + log(...data: any[]): void; + warn(...data: any[]): void; + dir(...data: any[]): void; + dirxml(...data: any[]): void; + table(...data: any[]): void; + trace(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(...data: any[]): void; + clear(...data: any[]): void; + count(label?: any): void; + countReset(label?: any): void; + assert(value?: any, ...data: any[]): void; + profile(label?: any): void; + profileEnd(label?: any): void; + time(label?: any): void; + timeLog(label?: any): void; + timeStamp(label?: any): void; + } + /** + * An object to send messages to the remote inspector console. + * @since v11.0.0 + */ + const console: InspectorConsole; + // DevTools protocol event broadcast methods + namespace Network { + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.requestWillBeSent` event to connected frontends. This event indicates that + * the application is about to send an HTTP request. + * @since v22.6.0 + */ + function requestWillBeSent(params: RequestWillBeSentEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.dataReceived` event to connected frontends, or buffers the data if + * `Network.streamResourceContent` command was not invoked for the given request yet. + * + * Also enables `Network.getResponseBody` command to retrieve the response data. + * @since v24.2.0 + */ + function dataReceived(params: DataReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Enables `Network.getRequestPostData` command to retrieve the request data. + * @since v24.3.0 + */ + function dataSent(params: unknown): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.responseReceived` event to connected frontends. This event indicates that + * HTTP response is available. + * @since v22.6.0 + */ + function responseReceived(params: ResponseReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.loadingFinished` event to connected frontends. This event indicates that + * HTTP request has finished loading. + * @since v22.6.0 + */ + function loadingFinished(params: LoadingFinishedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.loadingFailed` event to connected frontends. This event indicates that + * HTTP request has failed to load. + * @since v22.7.0 + */ + function loadingFailed(params: LoadingFailedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.webSocketCreated` event to connected frontends. This event indicates that + * a WebSocket connection has been initiated. + * @since v24.7.0 + */ + function webSocketCreated(params: WebSocketCreatedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.webSocketHandshakeResponseReceived` event to connected frontends. + * This event indicates that the WebSocket handshake response has been received. + * @since v24.7.0 + */ + function webSocketHandshakeResponseReceived(params: WebSocketHandshakeResponseReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.webSocketClosed` event to connected frontends. + * This event indicates that a WebSocket connection has been closed. + * @since v24.7.0 + */ + function webSocketClosed(params: WebSocketClosedEventDataType): void; + } + namespace NetworkResources { + /** + * This feature is only available with the `--experimental-inspector-network-resource` flag enabled. + * + * The inspector.NetworkResources.put method is used to provide a response for a loadNetworkResource + * request issued via the Chrome DevTools Protocol (CDP). + * This is typically triggered when a source map is specified by URL, and a DevTools frontend—such as + * Chrome—requests the resource to retrieve the source map. + * + * This method allows developers to predefine the resource content to be served in response to such CDP requests. + * + * ```js + * const inspector = require('node:inspector'); + * // By preemptively calling put to register the resource, a source map can be resolved when + * // a loadNetworkResource request is made from the frontend. + * async function setNetworkResources() { + * const mapUrl = 'http://localhost:3000/dist/app.js.map'; + * const tsUrl = 'http://localhost:3000/src/app.ts'; + * const distAppJsMap = await fetch(mapUrl).then((res) => res.text()); + * const srcAppTs = await fetch(tsUrl).then((res) => res.text()); + * inspector.NetworkResources.put(mapUrl, distAppJsMap); + * inspector.NetworkResources.put(tsUrl, srcAppTs); + * }; + * setNetworkResources().then(() => { + * require('./dist/app'); + * }); + * ``` + * + * For more details, see the official CDP documentation: [Network.loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network/#method-loadNetworkResource) + * @since v24.5.0 + * @experimental + */ + function put(url: string, data: string): void; + } +} + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + */ +declare module "node:inspector" { + export * from "inspector"; +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/inspector/promises.js) + * @since v19.0.0 + */ +declare module "inspector/promises" { + import EventEmitter = require("node:events"); + export { close, console, NetworkResources, open, url, waitForDebugger } from "inspector"; + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + * @since v19.0.0 + */ + export class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + * @since v12.11.0 + */ + connectToMainThread(): void; + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + } +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @since v19.0.0 + */ +declare module "node:inspector/promises" { + export * from "inspector/promises"; +} diff --git a/tools/ui/node_modules/@types/node/inspector.generated.d.ts b/tools/ui/node_modules/@types/node/inspector.generated.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d7d3a55c6af1d17030e7776a7b7f3994329800be --- /dev/null +++ b/tools/ui/node_modules/@types/node/inspector.generated.d.ts @@ -0,0 +1,4239 @@ +// These definitions are automatically generated by the generate-inspector script. +// Do not edit this file directly. +// See scripts/generate-inspector/README.md for information on how to update the protocol definitions. +// Changes to the module itself should be added to the generator template (scripts/generate-inspector/inspector.d.ts.template). + +declare module "inspector" { + interface InspectorNotification { + method: string; + params: T; + } + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: object | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: object; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: object | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: object | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: object | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace IO { + type StreamHandle = string; + interface ReadParameterType { + /** + * Handle of the stream to read. + */ + handle: StreamHandle; + /** + * Seek to the specified offset before reading (if not specified, proceed with offset + * following the last read). Some types of streams may only support sequential reads. + */ + offset?: number | undefined; + /** + * Maximum number of bytes to read (left upon the agent discretion if not specified). + */ + size?: number | undefined; + } + interface CloseParameterType { + /** + * Handle of the stream to close. + */ + handle: StreamHandle; + } + interface ReadReturnType { + /** + * Data that were read. + */ + data: string; + /** + * Set if the end-of-file condition occurred while reading. + */ + eof: boolean; + } + } + namespace Network { + /** + * Resource type as it was perceived by the rendering engine. + */ + type ResourceType = string; + /** + * Unique request identifier. + */ + type RequestId = string; + /** + * UTC time in seconds, counted from January 1, 1970. + */ + type TimeSinceEpoch = number; + /** + * Monotonically increasing time in seconds since an arbitrary point in the past. + */ + type MonotonicTime = number; + /** + * Information about the request initiator. + */ + interface Initiator { + /** + * Type of this initiator. + */ + type: string; + /** + * Initiator JavaScript stack trace, set for Script only. + * Requires the Debugger domain to be enabled. + */ + stack?: Runtime.StackTrace | undefined; + /** + * Initiator URL, set for Parser type or for Script type (when script is importing module) or for SignedExchange type. + */ + url?: string | undefined; + /** + * Initiator line number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + lineNumber?: number | undefined; + /** + * Initiator column number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + columnNumber?: number | undefined; + /** + * Set if another request triggered this request (e.g. preflight). + */ + requestId?: RequestId | undefined; + } + /** + * HTTP request data. + */ + interface Request { + url: string; + method: string; + headers: Headers; + hasPostData: boolean; + } + /** + * HTTP response data. + */ + interface Response { + url: string; + status: number; + statusText: string; + headers: Headers; + mimeType: string; + charset: string; + } + /** + * Request / response headers as keys / values of JSON object. + */ + interface Headers { + } + interface LoadNetworkResourcePageResult { + success: boolean; + stream?: IO.StreamHandle | undefined; + } + /** + * WebSocket response data. + */ + interface WebSocketResponse { + /** + * HTTP response status code. + */ + status: number; + /** + * HTTP response status text. + */ + statusText: string; + /** + * HTTP response headers. + */ + headers: Headers; + } + interface EnableParameterType { + /** + * Buffer size in bytes to use when preserving network payloads (XHRs, etc). + * @experimental + */ + maxTotalBufferSize?: number | undefined; + /** + * Per-resource buffer size in bytes to use when preserving network payloads (XHRs, etc). + * @experimental + */ + maxResourceBufferSize?: number | undefined; + } + interface GetRequestPostDataParameterType { + /** + * Identifier of the network request to get content for. + */ + requestId: RequestId; + } + interface GetResponseBodyParameterType { + /** + * Identifier of the network request to get content for. + */ + requestId: RequestId; + } + interface StreamResourceContentParameterType { + /** + * Identifier of the request to stream. + */ + requestId: RequestId; + } + interface LoadNetworkResourceParameterType { + /** + * URL of the resource to get content for. + */ + url: string; + } + interface GetRequestPostDataReturnType { + /** + * Request body string, omitting files from multipart requests + */ + postData: string; + } + interface GetResponseBodyReturnType { + /** + * Response body. + */ + body: string; + /** + * True, if content was sent as base64. + */ + base64Encoded: boolean; + } + interface StreamResourceContentReturnType { + /** + * Data that has been buffered until streaming is enabled. + */ + bufferedData: string; + } + interface LoadNetworkResourceReturnType { + resource: LoadNetworkResourcePageResult; + } + interface RequestWillBeSentEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Request data. + */ + request: Request; + /** + * Request initiator. + */ + initiator: Initiator; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Timestamp. + */ + wallTime: TimeSinceEpoch; + } + interface ResponseReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Resource type. + */ + type: ResourceType; + /** + * Response data. + */ + response: Response; + } + interface LoadingFailedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Resource type. + */ + type: ResourceType; + /** + * Error message. + */ + errorText: string; + } + interface LoadingFinishedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + } + interface DataReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Data chunk length. + */ + dataLength: number; + /** + * Actual bytes received (might be less than dataLength for compressed encodings). + */ + encodedDataLength: number; + /** + * Data that was received. + * @experimental + */ + data?: string | undefined; + } + interface WebSocketCreatedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * WebSocket request URL. + */ + url: string; + /** + * Request initiator. + */ + initiator: Initiator; + } + interface WebSocketClosedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + } + interface WebSocketHandshakeResponseReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * WebSocket response data. + */ + response: WebSocketResponse; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string | undefined; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: object[]; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace Target { + type SessionID = string; + type TargetID = string; + interface TargetInfo { + targetId: TargetID; + type: string; + title: string; + url: string; + attached: boolean; + canAccessOpener: boolean; + } + interface SetAutoAttachParameterType { + autoAttach: boolean; + waitForDebuggerOnStart: boolean; + } + interface TargetCreatedEventDataType { + targetInfo: TargetInfo; + } + interface AttachedToTargetEventDataType { + sessionId: SessionID; + targetInfo: TargetInfo; + waitingForDebugger: boolean; + } + } + interface Session { + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, callback?: (err: Error | null, params?: object) => void): void; + post(method: string, params?: object, callback?: (err: Error | null, params?: object) => void): void; + /** + * Returns supported domains. + */ + post(method: "Schema.getDomains", callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: "Runtime.evaluate", callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: "Runtime.awaitPromise", callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: "Runtime.callFunctionOn", callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: "Runtime.getProperties", callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObject", callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObjectGroup", callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: "Runtime.runIfWaitingForDebugger", callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: "Runtime.enable", callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: "Runtime.disable", callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: "Runtime.discardConsoleEntries", callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.setCustomObjectFormatterEnabled", callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: "Runtime.compileScript", callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: "Runtime.runScript", callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: "Runtime.queryObjects", callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: "Runtime.globalLexicalScopeNames", + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: "Runtime.globalLexicalScopeNames", callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: "Debugger.enable", callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: "Debugger.disable", callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBreakpointsActive", callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setSkipAllPauses", callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: "Debugger.setBreakpointByUrl", callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: "Debugger.setBreakpoint", callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.removeBreakpoint", callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: "Debugger.getPossibleBreakpoints", + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: "Debugger.getPossibleBreakpoints", callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.continueToLocation", callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: "Debugger.pauseOnAsyncCall", params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.pauseOnAsyncCall", callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: "Debugger.stepOver", callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: "Debugger.stepInto", params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.stepInto", callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: "Debugger.stepOut", callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: "Debugger.pause", callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: "Debugger.scheduleStepIntoAsync", callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: "Debugger.resume", callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: "Debugger.getStackTrace", params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: "Debugger.getStackTrace", callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: "Debugger.searchInContent", callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: "Debugger.setScriptSource", callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: "Debugger.restartFrame", callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: "Debugger.getScriptSource", callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setPauseOnExceptions", callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: "Debugger.evaluateOnCallFrame", callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setVariableValue", callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: "Debugger.setReturnValue", params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setReturnValue", callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setAsyncCallStackDepth", callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxPatterns", callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxedRanges", callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: "Console.enable", callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: "Console.disable", callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: "Console.clearMessages", callback?: (err: Error | null) => void): void; + post(method: "Profiler.enable", callback?: (err: Error | null) => void): void; + post(method: "Profiler.disable", callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.setSamplingInterval", callback?: (err: Error | null) => void): void; + post(method: "Profiler.start", callback?: (err: Error | null) => void): void; + post(method: "Profiler.stop", callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.startPreciseCoverage", callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: "Profiler.stopPreciseCoverage", callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: "Profiler.takePreciseCoverage", callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: "Profiler.getBestEffortCoverage", callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + post(method: "HeapProfiler.enable", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.disable", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startTrackingHeapObjects", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopTrackingHeapObjects", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.takeHeapSnapshot", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.collectGarbage", callback?: (err: Error | null) => void): void; + post( + method: "HeapProfiler.getObjectByHeapObjectId", + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: "HeapProfiler.getObjectByHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.addInspectedHeapObject", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.getHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startSampling", callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopSampling", callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: "HeapProfiler.getSamplingProfile", callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Read a chunk of the stream + */ + post(method: "IO.read", params?: IO.ReadParameterType, callback?: (err: Error | null, params: IO.ReadReturnType) => void): void; + post(method: "IO.read", callback?: (err: Error | null, params: IO.ReadReturnType) => void): void; + post(method: "IO.close", params?: IO.CloseParameterType, callback?: (err: Error | null) => void): void; + post(method: "IO.close", callback?: (err: Error | null) => void): void; + /** + * Disables network tracking, prevents network events from being sent to the client. + */ + post(method: "Network.disable", callback?: (err: Error | null) => void): void; + /** + * Enables network tracking, network events will now be delivered to the client. + */ + post(method: "Network.enable", params?: Network.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: "Network.enable", callback?: (err: Error | null) => void): void; + /** + * Returns post data sent with the request. Returns an error when no data was sent with the request. + */ + post(method: "Network.getRequestPostData", params?: Network.GetRequestPostDataParameterType, callback?: (err: Error | null, params: Network.GetRequestPostDataReturnType) => void): void; + post(method: "Network.getRequestPostData", callback?: (err: Error | null, params: Network.GetRequestPostDataReturnType) => void): void; + /** + * Returns content served for the given request. + */ + post(method: "Network.getResponseBody", params?: Network.GetResponseBodyParameterType, callback?: (err: Error | null, params: Network.GetResponseBodyReturnType) => void): void; + post(method: "Network.getResponseBody", callback?: (err: Error | null, params: Network.GetResponseBodyReturnType) => void): void; + /** + * Enables streaming of the response for the given requestId. + * If enabled, the dataReceived event contains the data that was received during streaming. + * @experimental + */ + post( + method: "Network.streamResourceContent", + params?: Network.StreamResourceContentParameterType, + callback?: (err: Error | null, params: Network.StreamResourceContentReturnType) => void + ): void; + post(method: "Network.streamResourceContent", callback?: (err: Error | null, params: Network.StreamResourceContentReturnType) => void): void; + /** + * Fetches the resource and returns the content. + */ + post(method: "Network.loadNetworkResource", params?: Network.LoadNetworkResourceParameterType, callback?: (err: Error | null, params: Network.LoadNetworkResourceReturnType) => void): void; + post(method: "Network.loadNetworkResource", callback?: (err: Error | null, params: Network.LoadNetworkResourceReturnType) => void): void; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.enable", callback?: (err: Error | null) => void): void; + /** + * Disable NodeRuntime events + */ + post(method: "NodeRuntime.disable", callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", callback?: (err: Error | null) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories", callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeTracing.start", callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop", callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.sendMessageToWorker", callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.enable", callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable", callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: "NodeWorker.detach", params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.detach", callback?: (err: Error | null) => void): void; + post(method: "Target.setAutoAttach", params?: Target.SetAutoAttachParameterType, callback?: (err: Error | null) => void): void; + post(method: "Target.setAutoAttach", callback?: (err: Error | null) => void): void; + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + addListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + addListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + addListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + addListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + addListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + addListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + addListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + addListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; + emit(event: "Debugger.paused", message: InspectorNotification): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; + emit(event: "Network.requestWillBeSent", message: InspectorNotification): boolean; + emit(event: "Network.responseReceived", message: InspectorNotification): boolean; + emit(event: "Network.loadingFailed", message: InspectorNotification): boolean; + emit(event: "Network.loadingFinished", message: InspectorNotification): boolean; + emit(event: "Network.dataReceived", message: InspectorNotification): boolean; + emit(event: "Network.webSocketCreated", message: InspectorNotification): boolean; + emit(event: "Network.webSocketClosed", message: InspectorNotification): boolean; + emit(event: "Network.webSocketHandshakeResponseReceived", message: InspectorNotification): boolean; + emit(event: "NodeRuntime.waitingForDisconnect"): boolean; + emit(event: "NodeRuntime.waitingForDebugger"): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; + emit(event: "Target.targetCreated", message: InspectorNotification): boolean; + emit(event: "Target.attachedToTarget", message: InspectorNotification): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + on(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + on(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + on(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + on(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + on(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + on(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + on(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + on(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + once(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + once(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + once(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + once(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + once(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + once(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + once(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + once(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + prependListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + prependListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + prependListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependOnceListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependOnceListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependOnceListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + prependOnceListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + prependOnceListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + prependOnceListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + } +} +declare module "inspector/promises" { + export { + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + IO, + Network, + NodeRuntime, + NodeTracing, + NodeWorker, + Target, + } from 'inspector'; +} +declare module "inspector/promises" { + import { + InspectorNotification, + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + IO, + Network, + NodeRuntime, + NodeTracing, + NodeWorker, + Target, + } from "inspector"; + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + * @since v19.0.0 + */ + interface Session { + /** + * Posts a message to the inspector back-end. + * + * ```js + * import { Session } from 'node:inspector/promises'; + * try { + * const session = new Session(); + * session.connect(); + * const result = await session.post('Runtime.evaluate', { expression: '2 + 2' }); + * console.log(result); + * } catch (error) { + * console.error(error); + * } + * // Output: { result: { type: 'number', value: 4, description: '4' } } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, params?: object): Promise; + /** + * Returns supported domains. + */ + post(method: "Schema.getDomains"): Promise; + /** + * Evaluates expression on global object. + */ + post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType): Promise; + /** + * Add handler to promise with given promise object id. + */ + post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType): Promise; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType): Promise; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType): Promise; + /** + * Releases remote object with given id. + */ + post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType): Promise; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType): Promise; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: "Runtime.runIfWaitingForDebugger"): Promise; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: "Runtime.enable"): Promise; + /** + * Disables reporting of execution contexts creation. + */ + post(method: "Runtime.disable"): Promise; + /** + * Discards collected exceptions and console API calls. + */ + post(method: "Runtime.discardConsoleEntries"): Promise; + /** + * @experimental + */ + post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType): Promise; + /** + * Compiles expression. + */ + post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType): Promise; + /** + * Runs script with given id in a given context. + */ + post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType): Promise; + post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType): Promise; + /** + * Returns all let, const and class variables from global scope. + */ + post(method: "Runtime.globalLexicalScopeNames", params?: Runtime.GlobalLexicalScopeNamesParameterType): Promise; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: "Debugger.enable"): Promise; + /** + * Disables debugger for given page. + */ + post(method: "Debugger.disable"): Promise; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType): Promise; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType): Promise; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType): Promise; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType): Promise; + /** + * Removes JavaScript breakpoint. + */ + post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType): Promise; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post(method: "Debugger.getPossibleBreakpoints", params?: Debugger.GetPossibleBreakpointsParameterType): Promise; + /** + * Continues execution until specific location is reached. + */ + post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType): Promise; + /** + * @experimental + */ + post(method: "Debugger.pauseOnAsyncCall", params?: Debugger.PauseOnAsyncCallParameterType): Promise; + /** + * Steps over the statement. + */ + post(method: "Debugger.stepOver"): Promise; + /** + * Steps into the function call. + */ + post(method: "Debugger.stepInto", params?: Debugger.StepIntoParameterType): Promise; + /** + * Steps out of the function call. + */ + post(method: "Debugger.stepOut"): Promise; + /** + * Stops on the next JavaScript statement. + */ + post(method: "Debugger.pause"): Promise; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: "Debugger.scheduleStepIntoAsync"): Promise; + /** + * Resumes JavaScript execution. + */ + post(method: "Debugger.resume"): Promise; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: "Debugger.getStackTrace", params?: Debugger.GetStackTraceParameterType): Promise; + /** + * Searches for given string in script content. + */ + post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType): Promise; + /** + * Edits JavaScript source live. + */ + post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType): Promise; + /** + * Restarts particular call frame from the beginning. + */ + post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType): Promise; + /** + * Returns source for the script with given id. + */ + post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType): Promise; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType): Promise; + /** + * Evaluates expression on a given call frame. + */ + post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType): Promise; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType): Promise; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: "Debugger.setReturnValue", params?: Debugger.SetReturnValueParameterType): Promise; + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType): Promise; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType): Promise; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType): Promise; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: "Console.enable"): Promise; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: "Console.disable"): Promise; + /** + * Does nothing. + */ + post(method: "Console.clearMessages"): Promise; + post(method: "Profiler.enable"): Promise; + post(method: "Profiler.disable"): Promise; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType): Promise; + post(method: "Profiler.start"): Promise; + post(method: "Profiler.stop"): Promise; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType): Promise; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: "Profiler.stopPreciseCoverage"): Promise; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: "Profiler.takePreciseCoverage"): Promise; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: "Profiler.getBestEffortCoverage"): Promise; + post(method: "HeapProfiler.enable"): Promise; + post(method: "HeapProfiler.disable"): Promise; + post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType): Promise; + post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType): Promise; + post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType): Promise; + post(method: "HeapProfiler.collectGarbage"): Promise; + post(method: "HeapProfiler.getObjectByHeapObjectId", params?: HeapProfiler.GetObjectByHeapObjectIdParameterType): Promise; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType): Promise; + post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType): Promise; + post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType): Promise; + post(method: "HeapProfiler.stopSampling"): Promise; + post(method: "HeapProfiler.getSamplingProfile"): Promise; + /** + * Read a chunk of the stream + */ + post(method: "IO.read", params?: IO.ReadParameterType): Promise; + post(method: "IO.close", params?: IO.CloseParameterType): Promise; + /** + * Disables network tracking, prevents network events from being sent to the client. + */ + post(method: "Network.disable"): Promise; + /** + * Enables network tracking, network events will now be delivered to the client. + */ + post(method: "Network.enable", params?: Network.EnableParameterType): Promise; + /** + * Returns post data sent with the request. Returns an error when no data was sent with the request. + */ + post(method: "Network.getRequestPostData", params?: Network.GetRequestPostDataParameterType): Promise; + /** + * Returns content served for the given request. + */ + post(method: "Network.getResponseBody", params?: Network.GetResponseBodyParameterType): Promise; + /** + * Enables streaming of the response for the given requestId. + * If enabled, the dataReceived event contains the data that was received during streaming. + * @experimental + */ + post(method: "Network.streamResourceContent", params?: Network.StreamResourceContentParameterType): Promise; + /** + * Fetches the resource and returns the content. + */ + post(method: "Network.loadNetworkResource", params?: Network.LoadNetworkResourceParameterType): Promise; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.enable"): Promise; + /** + * Disable NodeRuntime events + */ + post(method: "NodeRuntime.disable"): Promise; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType): Promise; + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories"): Promise; + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType): Promise; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop"): Promise; + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType): Promise; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType): Promise; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable"): Promise; + /** + * Detached from the worker with given sessionId. + */ + post(method: "NodeWorker.detach", params?: NodeWorker.DetachParameterType): Promise; + post(method: "Target.setAutoAttach", params?: Target.SetAutoAttachParameterType): Promise; + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + addListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + addListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + addListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + addListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + addListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + addListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + addListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + addListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + addListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; + emit(event: "Debugger.paused", message: InspectorNotification): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; + emit(event: "Network.requestWillBeSent", message: InspectorNotification): boolean; + emit(event: "Network.responseReceived", message: InspectorNotification): boolean; + emit(event: "Network.loadingFailed", message: InspectorNotification): boolean; + emit(event: "Network.loadingFinished", message: InspectorNotification): boolean; + emit(event: "Network.dataReceived", message: InspectorNotification): boolean; + emit(event: "Network.webSocketCreated", message: InspectorNotification): boolean; + emit(event: "Network.webSocketClosed", message: InspectorNotification): boolean; + emit(event: "Network.webSocketHandshakeResponseReceived", message: InspectorNotification): boolean; + emit(event: "NodeRuntime.waitingForDisconnect"): boolean; + emit(event: "NodeRuntime.waitingForDebugger"): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; + emit(event: "Target.targetCreated", message: InspectorNotification): boolean; + emit(event: "Target.attachedToTarget", message: InspectorNotification): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + on(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + on(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + on(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + on(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + on(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + on(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + on(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + on(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + on(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + once(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + once(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + once(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + once(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + once(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + once(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + once(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + once(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + once(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + prependListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + prependListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + prependListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: "Debugger.resumed", listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependOnceListener(event: "Network.requestWillBeSent", listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependOnceListener(event: "Network.responseReceived", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFailed", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Network.loadingFinished", listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependOnceListener(event: "Network.dataReceived", listener: (message: InspectorNotification) => void): this; + /** + * Fired upon WebSocket creation. + */ + prependOnceListener(event: "Network.webSocketCreated", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket is closed. + */ + prependOnceListener(event: "Network.webSocketClosed", listener: (message: InspectorNotification) => void): this; + /** + * Fired when WebSocket handshake response becomes available. + */ + prependOnceListener(event: "Network.webSocketHandshakeResponseReceived", listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: "NodeRuntime.waitingForDebugger", listener: () => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + } +} diff --git a/tools/ui/node_modules/@types/node/module.d.ts b/tools/ui/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..889e2ddb60b7963b8c2d96b24efa88c621846b44 --- /dev/null +++ b/tools/ui/node_modules/@types/node/module.d.ts @@ -0,0 +1,843 @@ +/** + * @since v0.3.7 + */ +declare module "module" { + import { URL } from "node:url"; + class Module { + constructor(id: string, parent?: Module); + } + interface Module extends NodeJS.Module {} + namespace Module { + export { Module }; + } + namespace Module { + /** + * A list of the names of all modules provided by Node.js. Can be used to verify + * if a module is maintained by a third party or not. + * + * Note: the list doesn't contain prefix-only modules like `node:test`. + * @since v9.3.0, v8.10.0, v6.13.0 + */ + const builtinModules: readonly string[]; + /** + * @since v12.2.0 + * @param path Filename to be used to construct the require + * function. Must be a file URL object, file URL string, or absolute path + * string. + */ + function createRequire(path: string | URL): NodeJS.Require; + namespace constants { + /** + * The following constants are returned as the `status` field in the object returned by + * {@link enableCompileCache} to indicate the result of the attempt to enable the + * [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache). + * @since v22.8.0 + */ + namespace compileCacheStatus { + /** + * Node.js has enabled the compile cache successfully. The directory used to store the + * compile cache will be returned in the `directory` field in the + * returned object. + */ + const ENABLED: number; + /** + * The compile cache has already been enabled before, either by a previous call to + * {@link enableCompileCache}, or by the `NODE_COMPILE_CACHE=dir` + * environment variable. The directory used to store the + * compile cache will be returned in the `directory` field in the + * returned object. + */ + const ALREADY_ENABLED: number; + /** + * Node.js fails to enable the compile cache. This can be caused by the lack of + * permission to use the specified directory, or various kinds of file system errors. + * The detail of the failure will be returned in the `message` field in the + * returned object. + */ + const FAILED: number; + /** + * Node.js cannot enable the compile cache because the environment variable + * `NODE_DISABLE_COMPILE_CACHE=1` has been set. + */ + const DISABLED: number; + } + } + interface EnableCompileCacheResult { + /** + * One of the {@link constants.compileCacheStatus} + */ + status: number; + /** + * If Node.js cannot enable the compile cache, this contains + * the error message. Only set if `status` is `module.constants.compileCacheStatus.FAILED`. + */ + message?: string; + /** + * If the compile cache is enabled, this contains the directory + * where the compile cache is stored. Only set if `status` is + * `module.constants.compileCacheStatus.ENABLED` or + * `module.constants.compileCacheStatus.ALREADY_ENABLED`. + */ + directory?: string; + } + interface EnableCompileCacheOptions { + /** + * Optional. Directory to store the compile cache. If not specified, the directory specified by + * the [`NODE_COMPILE_CACHE=dir`](https://nodejs.org/docs/latest-v24.x/api/cli.html#node_compile_cachedir) + * environment variable will be used if it's set, or `path.join(os.tmpdir(), 'node-compile-cache')` otherwise. + * @since v24.12.0 + */ + directory?: string | undefined; + /** + * Optional. If `true`, enables portable compile cache so that the cache can be reused even if the project directory + * is moved. This is a best-effort feature. If not specified, it will depend on whether the environment variable + * [NODE_COMPILE_CACHE_PORTABLE=1](https://nodejs.org/docs/latest-v24.x/api/cli.html#node_compile_cache_portable1) is set. + * @since v24.12.0 + */ + portable?: boolean | undefined; + } + /** + * Enable [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache) + * in the current Node.js instance. + * + * For general use cases, it's recommended to call `module.enableCompileCache()` without specifying the + * `options.directory`, so that the directory can be overridden by the `NODE_COMPILE_CACHE` environment + * variable when necessary. + * + * Since compile cache is supposed to be a optimization that is not mission critical, this method is + * designed to not throw any exception when the compile cache cannot be enabled. Instead, it will return + * an object containing an error message in the `message` field to aid debugging. If compile cache is + * enabled successfully, the `directory` field in the returned object contains the path to the directory + * where the compile cache is stored. The `status` field in the returned object would be one of the + * `module.constants.compileCacheStatus` values to indicate the result of the attempt to enable the + * [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache). + * + * This method only affects the current Node.js instance. To enable it in child worker threads, + * either call this method in child worker threads too, or set the + * `process.env.NODE_COMPILE_CACHE` value to compile cache directory so the behavior can + * be inherited into the child workers. The directory can be obtained either from the + * `directory` field returned by this method, or with {@link getCompileCacheDir `module.getCompileCacheDir()`}. + * @since v22.8.0 + * @param options Optional. If a string is passed, it is considered to be `options.directory`. + * will be stored/retrieved. + */ + function enableCompileCache(options?: string | EnableCompileCacheOptions): EnableCompileCacheResult; + /** + * Flush the [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache) + * accumulated from modules already loaded + * in the current Node.js instance to disk. This returns after all the flushing + * file system operations come to an end, no matter they succeed or not. If there + * are any errors, this will fail silently, since compile cache misses should not + * interfere with the actual operation of the application. + * @since v22.10.0 + */ + function flushCompileCache(): void; + /** + * @since v22.8.0 + * @return Path to the [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache) + * directory if it is enabled, or `undefined` otherwise. + */ + function getCompileCacheDir(): string | undefined; + /** + * ```text + * /path/to/project + * ├ packages/ + * ├ bar/ + * ├ bar.js + * └ package.json // name = '@foo/bar' + * └ qux/ + * ├ node_modules/ + * └ some-package/ + * └ package.json // name = 'some-package' + * ├ qux.js + * └ package.json // name = '@foo/qux' + * ├ main.js + * └ package.json // name = '@foo' + * ``` + * ```js + * // /path/to/project/packages/bar/bar.js + * import { findPackageJSON } from 'node:module'; + * + * findPackageJSON('..', import.meta.url); + * // '/path/to/project/package.json' + * // Same result when passing an absolute specifier instead: + * findPackageJSON(new URL('../', import.meta.url)); + * findPackageJSON(import.meta.resolve('../')); + * + * findPackageJSON('some-package', import.meta.url); + * // '/path/to/project/packages/bar/node_modules/some-package/package.json' + * // When passing an absolute specifier, you might get a different result if the + * // resolved module is inside a subfolder that has nested `package.json`. + * findPackageJSON(import.meta.resolve('some-package')); + * // '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json' + * + * findPackageJSON('@foo/qux', import.meta.url); + * // '/path/to/project/packages/qux/package.json' + * ``` + * @since v22.14.0 + * @param specifier The specifier for the module whose `package.json` to + * retrieve. When passing a _bare specifier_, the `package.json` at the root of + * the package is returned. When passing a _relative specifier_ or an _absolute specifier_, + * the closest parent `package.json` is returned. + * @param base The absolute location (`file:` URL string or FS path) of the + * containing module. For CJS, use `__filename` (not `__dirname`!); for ESM, use + * `import.meta.url`. You do not need to pass it if `specifier` is an _absolute specifier_. + * @returns A path if the `package.json` is found. When `startLocation` + * is a package, the package's root `package.json`; when a relative or unresolved, the closest + * `package.json` to the `startLocation`. + */ + function findPackageJSON(specifier: string | URL, base?: string | URL): string | undefined; + /** + * @since v18.6.0, v16.17.0 + */ + function isBuiltin(moduleName: string): boolean; + interface RegisterOptions { + /** + * If you want to resolve `specifier` relative to a + * base URL, such as `import.meta.url`, you can pass that URL here. This + * property is ignored if the `parentURL` is supplied as the second argument. + * @default 'data:' + */ + parentURL?: string | URL | undefined; + /** + * Any arbitrary, cloneable JavaScript value to pass into the + * {@link initialize} hook. + */ + data?: Data | undefined; + /** + * [Transferable objects](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html#portpostmessagevalue-transferlist) + * to be passed into the `initialize` hook. + */ + transferList?: any[] | undefined; + } + /* eslint-disable @definitelytyped/no-unnecessary-generics */ + /** + * Register a module that exports hooks that customize Node.js module + * resolution and loading behavior. See + * [Customization hooks](https://nodejs.org/docs/latest-v24.x/api/module.html#customization-hooks). + * + * This feature requires `--allow-worker` if used with the + * [Permission Model](https://nodejs.org/docs/latest-v24.x/api/permissions.html#permission-model). + * @since v20.6.0, v18.19.0 + * @param specifier Customization hooks to be registered; this should be + * the same string that would be passed to `import()`, except that if it is + * relative, it is resolved relative to `parentURL`. + * @param parentURL f you want to resolve `specifier` relative to a base + * URL, such as `import.meta.url`, you can pass that URL here. + */ + function register( + specifier: string | URL, + parentURL?: string | URL, + options?: RegisterOptions, + ): void; + function register(specifier: string | URL, options?: RegisterOptions): void; + interface RegisterHooksOptions { + /** + * See [load hook](https://nodejs.org/docs/latest-v24.x/api/module.html#loadurl-context-nextload). + * @default undefined + */ + load?: LoadHookSync | undefined; + /** + * See [resolve hook](https://nodejs.org/docs/latest-v24.x/api/module.html#resolvespecifier-context-nextresolve). + * @default undefined + */ + resolve?: ResolveHookSync | undefined; + } + interface ModuleHooks { + /** + * Deregister the hook instance. + */ + deregister(): void; + } + /** + * Register [hooks](https://nodejs.org/docs/latest-v24.x/api/module.html#customization-hooks) + * that customize Node.js module resolution and loading behavior. + * @since v22.15.0 + * @experimental + */ + function registerHooks(options: RegisterHooksOptions): ModuleHooks; + interface StripTypeScriptTypesOptions { + /** + * Possible values are: + * * `'strip'` Only strip type annotations without performing the transformation of TypeScript features. + * * `'transform'` Strip type annotations and transform TypeScript features to JavaScript. + * @default 'strip' + */ + mode?: "strip" | "transform" | undefined; + /** + * Only when `mode` is `'transform'`, if `true`, a source map + * will be generated for the transformed code. + * @default false + */ + sourceMap?: boolean | undefined; + /** + * Specifies the source url used in the source map. + */ + sourceUrl?: string | undefined; + } + /** + * `module.stripTypeScriptTypes()` removes type annotations from TypeScript code. It + * can be used to strip type annotations from TypeScript code before running it + * with `vm.runInContext()` or `vm.compileFunction()`. + * By default, it will throw an error if the code contains TypeScript features + * that require transformation such as `Enums`, + * see [type-stripping](https://nodejs.org/docs/latest-v24.x/api/typescript.md#type-stripping) for more information. + * When mode is `'transform'`, it also transforms TypeScript features to JavaScript, + * see [transform TypeScript features](https://nodejs.org/docs/latest-v24.x/api/typescript.md#typescript-features) for more information. + * When mode is `'strip'`, source maps are not generated, because locations are preserved. + * If `sourceMap` is provided, when mode is `'strip'`, an error will be thrown. + * + * _WARNING_: The output of this function should not be considered stable across Node.js versions, + * due to changes in the TypeScript parser. + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = 'const a: number = 1;'; + * const strippedCode = stripTypeScriptTypes(code); + * console.log(strippedCode); + * // Prints: const a = 1; + * ``` + * + * If `sourceUrl` is provided, it will be used appended as a comment at the end of the output: + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = 'const a: number = 1;'; + * const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' }); + * console.log(strippedCode); + * // Prints: const a = 1\n\n//# sourceURL=source.ts; + * ``` + * + * When `mode` is `'transform'`, the code is transformed to JavaScript: + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = ` + * namespace MathUtil { + * export const add = (a: number, b: number) => a + b; + * }`; + * const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true }); + * console.log(strippedCode); + * // Prints: + * // var MathUtil; + * // (function(MathUtil) { + * // MathUtil.add = (a, b)=>a + b; + * // })(MathUtil || (MathUtil = {})); + * // # sourceMappingURL=data:application/json;base64, ... + * ``` + * @since v22.13.0 + * @param code The code to strip type annotations from. + * @returns The code with type annotations stripped. + */ + function stripTypeScriptTypes(code: string, options?: StripTypeScriptTypesOptions): string; + /* eslint-enable @definitelytyped/no-unnecessary-generics */ + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * import fs from 'node:fs'; + * import assert from 'node:assert'; + * import { syncBuiltinESMExports } from 'node:module'; + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('node:fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + interface ImportAttributes extends NodeJS.Dict { + type?: string | undefined; + } + type ImportPhase = "source" | "evaluation"; + type ModuleFormat = + | "addon" + | "builtin" + | "commonjs" + | "commonjs-typescript" + | "json" + | "module" + | "module-typescript" + | "wasm"; + type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray; + type InitializeHook = (data: Data) => void | Promise; + interface ResolveHookContext { + conditions: string[]; + importAttributes: ImportAttributes; + parentURL: string | undefined; + } + interface ResolveFnOutput { + format?: string | null | undefined; + importAttributes?: ImportAttributes | undefined; + shortCircuit?: boolean | undefined; + url: string; + } + type ResolveHook = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: Partial, + ) => ResolveFnOutput | Promise, + ) => ResolveFnOutput | Promise; + type ResolveHookSync = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: Partial, + ) => ResolveFnOutput, + ) => ResolveFnOutput; + interface LoadHookContext { + conditions: string[]; + format: string | null | undefined; + importAttributes: ImportAttributes; + } + interface LoadFnOutput { + format: string | null | undefined; + shortCircuit?: boolean | undefined; + source?: ModuleSource | undefined; + } + type LoadHook = ( + url: string, + context: LoadHookContext, + nextLoad: ( + url: string, + context?: Partial, + ) => LoadFnOutput | Promise, + ) => LoadFnOutput | Promise; + type LoadHookSync = ( + url: string, + context: LoadHookContext, + nextLoad: ( + url: string, + context?: Partial, + ) => LoadFnOutput, + ) => LoadFnOutput; + interface SourceMapsSupport { + /** + * If the source maps support is enabled + */ + enabled: boolean; + /** + * If the support is enabled for files in `node_modules`. + */ + nodeModules: boolean; + /** + * If the support is enabled for generated code from `eval` or `new Function`. + */ + generatedCode: boolean; + } + /** + * This method returns whether the [Source Map v3](https://tc39.es/ecma426/) support for stack + * traces is enabled. + * @since v23.7.0, v22.14.0 + */ + function getSourceMapsSupport(): SourceMapsSupport; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. + */ + function findSourceMap(path: string): SourceMap | undefined; + interface SetSourceMapsSupportOptions { + /** + * If enabling the support for files in `node_modules`. + * @default false + */ + nodeModules?: boolean | undefined; + /** + * If enabling the support for generated code from `eval` or `new Function`. + * @default false + */ + generatedCode?: boolean | undefined; + } + /** + * This function enables or disables the [Source Map v3](https://tc39.es/ecma426/) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options + * `--enable-source-maps`, with additional options to alter the support for files + * in `node_modules` or generated codes. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. Preferably, use the commandline options + * `--enable-source-maps` to avoid losing track of source maps of modules loaded + * before this API call. + * @since v23.7.0, v22.14.0 + */ + function setSourceMapsSupport(enabled: boolean, options?: SetSourceMapsSupportOptions): void; + interface SourceMapConstructorOptions { + /** + * @since v21.0.0, v20.5.0 + */ + lineLengths?: readonly number[] | undefined; + } + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + interface SourceOrigin { + /** + * The name of the range in the source map, if one was provided + */ + name: string | undefined; + /** + * The file name of the original source, as reported in the SourceMap + */ + fileName: string; + /** + * The 1-indexed lineNumber of the corresponding call site in the original source + */ + lineNumber: number; + /** + * The 1-indexed columnNumber of the corresponding call site in the original source + */ + columnNumber: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + constructor(payload: SourceMapPayload, options?: SourceMapConstructorOptions); + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + /** + * Given a line offset and column offset in the generated source + * file, returns an object representing the SourceMap range in the + * original file if found, or an empty object if not. + * + * The object returned contains the following keys: + * + * The returned value represents the raw range as it appears in the + * SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and + * column numbers as they appear in Error messages and CallSite + * objects. + * + * To get the corresponding 1-indexed line and column numbers from a + * lineNumber and columnNumber as they are reported by Error stacks + * and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)` + * @param lineOffset The zero-indexed line number offset in the generated source + * @param columnOffset The zero-indexed column number offset in the generated source + */ + findEntry(lineOffset: number, columnOffset: number): SourceMapping | {}; + /** + * Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source, + * find the corresponding call site location in the original source. + * + * If the `lineNumber` and `columnNumber` provided are not found in any source map, + * then an empty object is returned. + * @param lineNumber The 1-indexed line number of the call site in the generated source + * @param columnNumber The 1-indexed column number of the call site in the generated source + */ + findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {}; + } + function runMain(main?: string): void; + function wrap(script: string): string; + } + global { + interface ImportMeta { + /** + * The directory name of the current module. + * + * This is the same as the `path.dirname()` of the `import.meta.filename`. + * + * > **Caveat**: only present on `file:` modules. + * @since v21.2.0, v20.11.0 + */ + dirname: string; + /** + * The full absolute path and filename of the current module, with + * symlinks resolved. + * + * This is the same as the `url.fileURLToPath()` of the `import.meta.url`. + * + * > **Caveat** only local modules support this property. Modules not using the + * > `file:` protocol will not provide it. + * @since v21.2.0, v20.11.0 + */ + filename: string; + /** + * The absolute `file:` URL of the module. + * + * This is defined exactly the same as it is in browsers providing the URL of the + * current module file. + * + * This enables useful patterns such as relative file loading: + * + * ```js + * import { readFileSync } from 'node:fs'; + * const buffer = readFileSync(new URL('./data.proto', import.meta.url)); + * ``` + */ + url: string; + /** + * `import.meta.resolve` is a module-relative resolution function scoped to + * each module, returning the URL string. + * + * ```js + * const dependencyAsset = import.meta.resolve('component-lib/asset.css'); + * // file:///app/node_modules/component-lib/asset.css + * import.meta.resolve('./dep.js'); + * // file:///app/dep.js + * ``` + * + * All features of the Node.js module resolution are supported. Dependency + * resolutions are subject to the permitted exports resolutions within the package. + * + * **Caveats**: + * + * * This can result in synchronous file-system operations, which + * can impact performance similarly to `require.resolve`. + * * This feature is not available within custom loaders (it would + * create a deadlock). + * @since v13.9.0, v12.16.0 + * @param specifier The module specifier to resolve relative to the + * current module. + * @param parent An optional absolute parent module URL to resolve from. + * **Default:** `import.meta.url` + * @returns The absolute URL string that the specifier would resolve to. + */ + resolve(specifier: string, parent?: string | URL): string; + /** + * `true` when the current module is the entry point of the current process; `false` otherwise. + * + * Equivalent to `require.main === module` in CommonJS. + * + * Analogous to Python's `__name__ == "__main__"`. + * + * ```js + * export function foo() { + * return 'Hello, world'; + * } + * + * function main() { + * const message = foo(); + * console.log(message); + * } + * + * if (import.meta.main) main(); + * // `foo` can be imported from another module without possible side-effects from `main` + * ``` + * @since v24.2.0 + * @experimental + */ + main: boolean; + } + namespace NodeJS { + interface Module { + /** + * The module objects required for the first time by this one. + * @since v0.1.16 + */ + children: Module[]; + /** + * The `module.exports` object is created by the `Module` system. Sometimes this is + * not acceptable; many want their module to be an instance of some class. To do + * this, assign the desired export object to `module.exports`. + * @since v0.1.16 + */ + exports: any; + /** + * The fully resolved filename of the module. + * @since v0.1.16 + */ + filename: string; + /** + * The identifier for the module. Typically this is the fully resolved + * filename. + * @since v0.1.16 + */ + id: string; + /** + * `true` if the module is running during the Node.js preload + * phase. + * @since v15.4.0, v14.17.0 + */ + isPreloading: boolean; + /** + * Whether or not the module is done loading, or is in the process of + * loading. + * @since v0.1.16 + */ + loaded: boolean; + /** + * The module that first required this one, or `null` if the current module is the + * entry point of the current process, or `undefined` if the module was loaded by + * something that is not a CommonJS module (e.g. REPL or `import`). + * @since v0.1.16 + * @deprecated Please use `require.main` and `module.children` instead. + */ + parent: Module | null | undefined; + /** + * The directory name of the module. This is usually the same as the + * `path.dirname()` of the `module.id`. + * @since v11.14.0 + */ + path: string; + /** + * The search paths for the module. + * @since v0.4.0 + */ + paths: string[]; + /** + * The `module.require()` method provides a way to load a module as if + * `require()` was called from the original module. + * @since v0.5.1 + */ + require(id: string): any; + } + interface Require { + /** + * Used to import modules, `JSON`, and local files. + * @since v0.1.13 + */ + (id: string): any; + /** + * Modules are cached in this object when they are required. By deleting a key + * value from this object, the next `require` will reload the module. + * This does not apply to + * [native addons](https://nodejs.org/docs/latest-v24.x/api/addons.html), + * for which reloading will result in an error. + * @since v0.3.0 + */ + cache: Dict; + /** + * Instruct `require` on how to handle certain file extensions. + * @since v0.3.0 + * @deprecated + */ + extensions: RequireExtensions; + /** + * The `Module` object representing the entry script loaded when the Node.js + * process launched, or `undefined` if the entry point of the program is not a + * CommonJS module. + * @since v0.1.17 + */ + main: Module | undefined; + /** + * @since v0.3.0 + */ + resolve: RequireResolve; + } + /** @deprecated */ + interface RequireExtensions extends Dict<(module: Module, filename: string) => any> { + ".js": (module: Module, filename: string) => any; + ".json": (module: Module, filename: string) => any; + ".node": (module: Module, filename: string) => any; + } + interface RequireResolveOptions { + /** + * Paths to resolve module location from. If present, these + * paths are used instead of the default resolution paths, with the exception + * of + * [GLOBAL\_FOLDERS](https://nodejs.org/docs/latest-v24.x/api/modules.html#loading-from-the-global-folders) + * like `$HOME/.node_modules`, which are + * always included. Each of these paths is used as a starting point for + * the module resolution algorithm, meaning that the `node_modules` hierarchy + * is checked from this location. + * @since v8.9.0 + */ + paths?: string[] | undefined; + } + interface RequireResolve { + /** + * Use the internal `require()` machinery to look up the location of a module, + * but rather than loading the module, just return the resolved filename. + * + * If the module can not be found, a `MODULE_NOT_FOUND` error is thrown. + * @since v0.3.0 + * @param request The module path to resolve. + */ + (request: string, options?: RequireResolveOptions): string; + /** + * Returns an array containing the paths searched during resolution of `request` or + * `null` if the `request` string references a core module, for example `http` or + * `fs`. + * @since v8.9.0 + * @param request The module path whose lookup paths are being retrieved. + */ + paths(request: string): string[] | null; + } + } + /** + * The directory name of the current module. This is the same as the + * `path.dirname()` of the `__filename`. + * @since v0.1.27 + */ + var __dirname: string; + /** + * The file name of the current module. This is the current module file's absolute + * path with symlinks resolved. + * + * For a main program this is not necessarily the same as the file name used in the + * command line. + * @since v0.0.1 + */ + var __filename: string; + /** + * The `exports` variable is available within a module's file-level scope, and is + * assigned the value of `module.exports` before the module is evaluated. + * @since v0.1.16 + */ + var exports: NodeJS.Module["exports"]; + /** + * A reference to the current module. + * @since v0.1.16 + */ + var module: NodeJS.Module; + /** + * @since v0.1.13 + */ + var require: NodeJS.Require; + // Global-scope aliases for backwards compatibility with @types/node <13.0.x + // TODO: consider removing in a future major version update + /** @deprecated Use `NodeJS.Module` instead. */ + interface NodeModule extends NodeJS.Module {} + /** @deprecated Use `NodeJS.Require` instead. */ + interface NodeRequire extends NodeJS.Require {} + /** @deprecated Use `NodeJS.RequireResolve` instead. */ + interface RequireResolve extends NodeJS.RequireResolve {} + } + export = Module; +} +declare module "node:module" { + import module = require("module"); + export = module; +} diff --git a/tools/ui/node_modules/@types/node/net.d.ts b/tools/ui/node_modules/@types/node/net.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f03f9802b71f4d94edea6357afe51f8ca57a7d6a --- /dev/null +++ b/tools/ui/node_modules/@types/node/net.d.ts @@ -0,0 +1,1073 @@ +/** + * > Stability: 2 - Stable + * + * The `node:net` module provides an asynchronous network API for creating stream-based + * TCP or `IPC` servers ({@link createServer}) and clients + * ({@link createConnection}). + * + * It can be accessed using: + * + * ```js + * import net from 'node:net'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/net.js) + */ +declare module "net" { + import { NonSharedBuffer } from "node:buffer"; + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import * as dns from "node:dns"; + type LookupFunction = ( + hostname: string, + options: dns.LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | dns.LookupAddress[], family?: number) => void, + ) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + onread?: OnReadOpts | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + signal?: AbortSignal | undefined; + noDelay?: boolean | undefined; + keepAlive?: boolean | undefined; + keepAliveInitialDelay?: number | undefined; + blockList?: BlockList | undefined; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to `buffer` and a reference to `buffer`. + * Return `false` from this function to implicitly `pause()` the socket. + */ + callback(bytesWritten: number, buffer: Uint8Array): boolean; + } + interface TcpSocketConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamily?: boolean | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamilyAttemptTimeout?: number | undefined; + } + interface IpcSocketConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed"; + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately. + * If the socket is still writable it implicitly calls `socket.end()`. + * @since v0.3.4 + */ + destroySoon(): void; + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + */ + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + /** + * Sends data on the socket, with an explicit encoding for string data. + * @see {@link Socket.write} for full details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `net.Socket` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Close the TCP connection by sending an RST packet and destroy the stream. + * If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. + * Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. + * If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. + * @since v18.3.0, v16.17.0 + */ + resetAndDestroy(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property is only present if the family autoselection algorithm is enabled in `socket.connect(options)` + * and it is an array of the addresses that have been attempted. + * + * Each address is a string in the form of `$IP:$PORT`. + * If the connection was successful, then the last address is the one that the socket is currently connected to. + * @since v19.4.0 + */ + readonly autoSelectFamilyAttemptedAddresses: string[]; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`, `socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting + * (see `socket.connecting`). + * @since v11.2.0, v10.16.0 + */ + readonly pending: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress?: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort?: number; + /** + * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. + * @since v18.8.0, v16.18.0 + */ + readonly localFamily?: string; + /** + * This property represents the state of the connection as a string. + * + * * If the stream is connecting `socket.readyState` is `opening`. + * * If the stream is readable and writable, it is `open`. + * * If the stream is readable and not writable, it is `readOnly`. + * * If the stream is not readable and writable, it is `writeOnly`. + * @since v0.5.0 + */ + readonly readyState: SocketReadyState; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.11.14 + */ + readonly remoteFamily: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remotePort: number | undefined; + /** + * The socket timeout in milliseconds as set by `socket.setTimeout()`. + * It is `undefined` if a timeout has not been set. + * @since v10.7.0 + */ + readonly timeout?: number; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): this; + /** + * Half-closes the socket, with one final chunk of data. + * @see {@link Socket.end} for full details. + * @since v0.1.90 + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(buffer: Uint8Array | string, callback?: () => void): this; + /** + * Half-closes the socket, with one final chunk of data. + * @see {@link Socket.end} for full details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. connectionAttempt + * 4. connectionAttemptFailed + * 5. connectionAttemptTimeout + * 6. data + * 7. drain + * 8. end + * 9. error + * 10. lookup + * 11. ready + * 12. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (hadError: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + addListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + addListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + addListener(event: "data", listener: (data: NonSharedBuffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "timeout", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", hadError: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "connectionAttempt", ip: string, port: number, family: number): boolean; + emit(event: "connectionAttemptFailed", ip: string, port: number, family: number, error: Error): boolean; + emit(event: "connectionAttemptTimeout", ip: string, port: number, family: number): boolean; + emit(event: "data", data: NonSharedBuffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "ready"): boolean; + emit(event: "timeout"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (hadError: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + on( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + on(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; + on(event: "data", listener: (data: NonSharedBuffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + on(event: "ready", listener: () => void): this; + on(event: "timeout", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (hadError: boolean) => void): this; + once(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + once( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + once(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: NonSharedBuffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + once(event: "ready", listener: () => void): this; + once(event: "timeout", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (hadError: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + prependListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + prependListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependListener(event: "data", listener: (data: NonSharedBuffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (hadError: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener( + event: "connectionAttempt", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + prependOnceListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener(event: "data", listener: (data: NonSharedBuffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + interface ListenOptions extends Abortable { + backlog?: number | undefined; + exclusive?: boolean | undefined; + host?: string | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + reusePort?: boolean | undefined; + path?: string | undefined; + port?: number | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default false + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * Optionally overrides all `net.Socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * @default See [stream.getDefaultHighWaterMark()](https://nodejs.org/docs/latest-v24.x/api/stream.html#streamgetdefaulthighwatermarkobjectmode). + * @since v18.17.0, v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * `blockList` can be used for disabling inbound + * access to specific IP addresses, IP ranges, or IP subnets. This does not + * work if the server is behind a reverse proxy, NAT, etc. because the address + * checked against the block list is the address of the proxy, or the one + * specified by the NAT. + * @since v22.13.0 + */ + blockList?: BlockList | undefined; + } + interface DropArgument { + localAddress?: string; + localPort?: number; + localFamily?: string; + remoteAddress?: string; + remotePort?: number; + remoteFamily?: string; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server extends EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.error('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + readonly listening: boolean; + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + * 5. drop + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "drop", listener: (data?: DropArgument) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "drop", data?: DropArgument): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "drop", listener: (data?: DropArgument) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "drop", listener: (data?: DropArgument) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "drop", listener: (data?: DropArgument) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "drop", listener: (data?: DropArgument) => void): this; + /** + * Calls {@link Server.close()} and returns a promise that fulfills when the server has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } + type IPVersion = "ipv4" | "ipv6"; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0, v14.18.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0, v14.18.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0, v14.18.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0, v14.18.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0, v14.18.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + /** + * The list of rules added to the blocklist. + * @since v15.0.0, v14.18.0 + */ + rules: readonly string[]; + /** + * Returns `true` if the `value` is a `net.BlockList`. + * @since v22.13.0 + * @param value Any JS value + */ + static isBlockList(value: unknown): value is BlockList; + /** + * ```js + * const blockList = new net.BlockList(); + * const data = [ + * 'Subnet: IPv4 192.168.1.0/24', + * 'Address: IPv4 10.0.0.5', + * 'Range: IPv4 192.168.2.1-192.168.2.10', + * 'Range: IPv4 10.0.0.1-10.0.0.10', + * ]; + * blockList.fromJSON(data); + * blockList.fromJSON(JSON.stringify(data)); + * ``` + * @since v24.5.0 + * @experimental + */ + fromJSON(data: string | readonly string[]): void; + /** + * @since v24.5.0 + * @experimental + */ + toJSON(): readonly string[]; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of a TCP echo server which listens for connections + * on port 8124: + * + * ```js + * import net from 'node:net'; + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```bash + * telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```bash + * nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`. + * The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function getDefaultAutoSelectFamily(): boolean; + /** + * Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`. + * @param value The new default value. + * The initial default value is `true`, unless the command line option + * `--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function setDefaultAutoSelectFamily(value: boolean): void; + /** + * Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * The initial default value is `250` or the value specified via the command line option `--network-family-autoselection-attempt-timeout`. + * @returns The current default value of the `autoSelectFamilyAttemptTimeout` option. + * @since v19.8.0, v18.8.0 + */ + function getDefaultAutoSelectFamilyAttemptTimeout(): number; + /** + * Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * @param value The new default value, which must be a positive number. If the number is less than `10`, the value `10` is used instead. The initial default value is `250` or the value specified via the command line + * option `--network-family-autoselection-attempt-timeout`. + * @since v19.8.0, v18.8.0 + */ + function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void; + /** + * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 + * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. + * + * ```js + * net.isIP('::1'); // returns 6 + * net.isIP('127.0.0.1'); // returns 4 + * net.isIP('127.000.000.001'); // returns 0 + * net.isIP('127.0.0.1/24'); // returns 0 + * net.isIP('fhqwhgads'); // returns 0 + * ``` + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no + * leading zeroes. Otherwise, returns `false`. + * + * ```js + * net.isIPv4('127.0.0.1'); // returns true + * net.isIPv4('127.000.000.001'); // returns false + * net.isIPv4('127.0.0.1/24'); // returns false + * net.isIPv4('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. + * + * ```js + * net.isIPv6('::1'); // returns true + * net.isIPv6('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0, v14.18.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0, v14.18.0 + */ + readonly port: number; + /** + * @since v15.14.0, v14.18.0 + */ + readonly flowlabel: number; + /** + * @since v22.13.0 + * @param input An input string containing an IP address and optional port, + * e.g. `123.1.2.3:1234` or `[1::1]:1234`. + * @returns Returns a `SocketAddress` if parsing was successful. + * Otherwise returns `undefined`. + */ + static parse(input: string): SocketAddress | undefined; + } +} +declare module "node:net" { + export * from "net"; +} diff --git a/tools/ui/node_modules/@types/node/os.d.ts b/tools/ui/node_modules/@types/node/os.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..505f5b44d6495f3451ee8f84c40c53dca9ff2bfb --- /dev/null +++ b/tools/ui/node_modules/@types/node/os.d.ts @@ -0,0 +1,507 @@ +/** + * The `node:os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * import os from 'node:os'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/os.js) + */ +declare module "os" { + import { NonSharedBuffer } from "buffer"; + interface CpuInfo { + model: string; + speed: number; + times: { + /** The number of milliseconds the CPU has spent in user mode. */ + user: number; + /** The number of milliseconds the CPU has spent in nice mode. */ + nice: number; + /** The number of milliseconds the CPU has spent in sys mode. */ + sys: number; + /** The number of milliseconds the CPU has spent in idle mode. */ + idle: number; + /** The number of milliseconds the CPU has spent in irq mode. */ + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + scopeid?: number; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T | null; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * The array will be empty if no CPU information is available, such as if the `/proc` file system is unavailable. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20, + * }, + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * + * `os.cpus().length` should not be used to calculate the amount of parallelism + * available to an application. Use {@link availableParallelism} for this purpose. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns an estimate of the default amount of parallelism a program should use. + * Always returns a value greater than zero. + * + * This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism). + * @since v19.4.0, v18.14.0 + */ + function availableParallelism(): number; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See + * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + interface UserInfoOptions { + encoding?: BufferEncoding | "buffer" | undefined; + } + interface UserInfoOptionsWithBufferEncoding extends UserInfoOptions { + encoding: "buffer"; + } + interface UserInfoOptionsWithStringEncoding extends UserInfoOptions { + encoding?: BufferEncoding | undefined; + } + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and `gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a [`SystemError`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-systemerror) if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options?: UserInfoOptionsWithStringEncoding): UserInfo; + function userInfo(options: UserInfoOptionsWithBufferEncoding): UserInfo; + function userInfo(options: UserInfoOptions): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace dlopen { + const RTLD_LAZY: number; + const RTLD_NOW: number; + const RTLD_GLOBAL: number; + const RTLD_LOCAL: number; + const RTLD_DEEPBIND: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + /** + * The operating system-specific end-of-line marker. + * * `\n` on POSIX + * * `\r\n` on Windows + */ + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, + * `'mips'`, `'mipsel'`, `'ppc64'`, `'riscv64'`, `'s390x'`, and `'x64'`. + * + * The return value is equivalent to [process.arch](https://nodejs.org/docs/latest-v24.x/api/process.html#processarch). + * @since v0.5.0 + */ + function arch(): NodeJS.Architecture; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform for which + * the Node.js binary was compiled. The value is set at compile time. + * Possible values are `'aix'`, `'darwin'`, `'freebsd'`, `'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`, + * `mips`, `mips64`, `ppc64`, `ppc64le`, `s390x`, `i386`, `i686`, `x86_64`. + * + * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v18.9.0, v16.18.0 + */ + function machine(): string; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): "BE" | "LE"; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If `pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19` (low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in `os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to `PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module "node:os" { + export * from "os"; +} diff --git a/tools/ui/node_modules/@types/node/package.json b/tools/ui/node_modules/@types/node/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ae77c4329c1979baac254da2d4e1f4386d94a28e --- /dev/null +++ b/tools/ui/node_modules/@types/node/package.json @@ -0,0 +1,155 @@ +{ + "name": "@types/node", + "version": "24.13.0", + "description": "TypeScript definitions for node", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "contributors": [ + { + "name": "Microsoft TypeScript", + "githubUsername": "Microsoft", + "url": "https://github.com/Microsoft" + }, + { + "name": "Alberto Schiabel", + "githubUsername": "jkomyno", + "url": "https://github.com/jkomyno" + }, + { + "name": "Andrew Makarov", + "githubUsername": "r3nya", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "githubUsername": "btoueg", + "url": "https://github.com/btoueg" + }, + { + "name": "David Junger", + "githubUsername": "touffy", + "url": "https://github.com/touffy" + }, + { + "name": "Mohsen Azimi", + "githubUsername": "mohsen1", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nikita Galkin", + "githubUsername": "galkin", + "url": "https://github.com/galkin" + }, + { + "name": "Sebastian Silbermann", + "githubUsername": "eps1lon", + "url": "https://github.com/eps1lon" + }, + { + "name": "Wilco Bakker", + "githubUsername": "WilcoBakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "Marcin Kopacz", + "githubUsername": "chyzwar", + "url": "https://github.com/chyzwar" + }, + { + "name": "Trivikram Kamat", + "githubUsername": "trivikr", + "url": "https://github.com/trivikr" + }, + { + "name": "Junxiao Shi", + "githubUsername": "yoursunny", + "url": "https://github.com/yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "githubUsername": "qwelias", + "url": "https://github.com/qwelias" + }, + { + "name": "ExE Boss", + "githubUsername": "ExE-Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "Piotr Błażejewicz", + "githubUsername": "peterblazejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "githubUsername": "addaleax", + "url": "https://github.com/addaleax" + }, + { + "name": "Victor Perin", + "githubUsername": "victorperin", + "url": "https://github.com/victorperin" + }, + { + "name": "NodeJS Contributors", + "githubUsername": "NodeJS", + "url": "https://github.com/NodeJS" + }, + { + "name": "Linus Unnebäck", + "githubUsername": "LinusU", + "url": "https://github.com/LinusU" + }, + { + "name": "wafuwafu13", + "githubUsername": "wafuwafu13", + "url": "https://github.com/wafuwafu13" + }, + { + "name": "Matteo Collina", + "githubUsername": "mcollina", + "url": "https://github.com/mcollina" + }, + { + "name": "Dmitry Semigradsky", + "githubUsername": "Semigradsky", + "url": "https://github.com/Semigradsky" + }, + { + "name": "René", + "githubUsername": "Renegade334", + "url": "https://github.com/Renegade334" + }, + { + "name": "Yagiz Nizipli", + "githubUsername": "anonrig", + "url": "https://github.com/anonrig" + } + ], + "main": "", + "types": "index.d.ts", + "typesVersions": { + "<=5.6": { + "*": [ + "ts5.6/*" + ] + }, + "<=5.7": { + "*": [ + "ts5.7/*" + ] + } + }, + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": { + "undici-types": "~7.18.0" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "8af59f7bb64c6bb43be3bbee7b6844a77dced473b136184d799fb476e6985c3f", + "typeScriptVersion": "5.3" +} \ No newline at end of file diff --git a/tools/ui/node_modules/@types/node/path.d.ts b/tools/ui/node_modules/@types/node/path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..08b8a318bb40f2334caf79cefeeba7b72aacdcb6 --- /dev/null +++ b/tools/ui/node_modules/@types/node/path.d.ts @@ -0,0 +1,200 @@ +declare module "path/posix" { + import path = require("path"); + export = path; +} +declare module "path/win32" { + import path = require("path"); + export = path; +} +/** + * The `node:path` module provides utilities for working with file and directory + * paths. It can be accessed using: + * + * ```js + * import path from 'node:path'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/path.js) + */ +declare module "path" { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + interface PlatformPath { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. If the path is a zero-length string, '.' is returned, representing the current working directory. + * + * @param path string path to normalize. + * @throws {TypeError} if `path` is not a string. + */ + normalize(path: string): string; + /** + * Join all arguments together and normalize the resulting path. + * + * @param paths paths to join. + * @throws {TypeError} if any of the path segments is not a string. + */ + join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param paths A sequence of paths or path segments. + * @throws {TypeError} if any of the arguments is not a string. + */ + resolve(...paths: string[]): string; + /** + * The `path.matchesGlob()` method determines if `path` matches the `pattern`. + * @param path The path to glob-match against. + * @param pattern The glob to check the path against. + * @returns Whether or not the `path` matched the `pattern`. + * @throws {TypeError} if `path` or `pattern` are not strings. + * @since v22.5.0 + */ + matchesGlob(path: string, pattern: string): boolean; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * If the given {path} is a zero-length string, `false` will be returned. + * + * @param path path to test. + * @throws {TypeError} if `path` is not a string. + */ + isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to} based on the current working directory. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @throws {TypeError} if either `from` or `to` is not a string. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + dirname(path: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param path the path to evaluate. + * @param suffix optionally, an extension to remove from the result. + * @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. + */ + basename(path: string, suffix?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + extname(path: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: "\\" | "/"; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: ";" | ":"; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param path path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + parse(path: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathObject path to evaluate. + */ + format(pathObject: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + toNamespacedPath(path: string): string; + /** + * Posix specific pathing. + * Same as parent object on posix. + */ + readonly posix: PlatformPath; + /** + * Windows specific pathing. + * Same as parent object on windows + */ + readonly win32: PlatformPath; + } + } + const path: path.PlatformPath; + export = path; +} +declare module "node:path" { + import path = require("path"); + export = path; +} +declare module "node:path/posix" { + import path = require("path/posix"); + export = path; +} +declare module "node:path/win32" { + import path = require("path/win32"); + export = path; +} diff --git a/tools/ui/node_modules/@types/node/perf_hooks.d.ts b/tools/ui/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7393c5245fe765831e381c922072a306bcba9fde --- /dev/null +++ b/tools/ui/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,1042 @@ +/** + * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) + * + * ```js + * import { PerformanceObserver, performance } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/perf_hooks.js) + */ +declare module "perf_hooks" { + import { AsyncResource } from "node:async_hooks"; + type EntryType = + | "dns" // Node.js only + | "function" // Node.js only + | "gc" // Node.js only + | "http2" // Node.js only + | "http" // Node.js only + | "mark" // available on the Web + | "measure" // available on the Web + | "net" // Node.js only + | "node" // Node.js only + | "resource"; // available on the Web + interface NodeGCPerformanceDetail { + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind: number; + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags: number; + } + /** + * The constructor of this class is not exposed to users directly. + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. This value will not + * be meaningful for all Performance Entry types. + * @since v8.5.0 + */ + readonly duration: number; + /** + * The name of the performance entry. + * @since v8.5.0 + */ + readonly name: string; + /** + * The high resolution millisecond timestamp marking the starting time of the + * Performance Entry. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * The type of the performance entry. It may be one of: + * + * * `'node'` (Node.js only) + * * `'mark'` (available on the Web) + * * `'measure'` (available on the Web) + * * `'gc'` (Node.js only) + * * `'function'` (Node.js only) + * * `'http2'` (Node.js only) + * * `'http'` (Node.js only) + * @since v8.5.0 + */ + readonly entryType: EntryType; + toJSON(): any; + } + /** + * Exposes marks created via the `Performance.mark()` method. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMark extends PerformanceEntry { + readonly detail: any; + readonly duration: 0; + readonly entryType: "mark"; + } + /** + * Exposes measures created via the `Performance.measure()` method. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMeasure extends PerformanceEntry { + readonly detail: any; + readonly entryType: "measure"; + } + interface UVMetrics { + /** + * Number of event loop iterations. + */ + readonly loopCount: number; + /** + * Number of events that have been processed by the event handler. + */ + readonly events: number; + /** + * Number of events that were waiting to be processed when the event provider was called. + */ + readonly eventsWaiting: number; + } + // TODO: PerformanceNodeEntry is missing + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + class PerformanceNodeTiming extends PerformanceEntry { + readonly entryType: "node"; + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + * @since v8.5.0 + */ + readonly nodeStart: number; + /** + * This is a wrapper to the `uv_metrics_info` function. + * It returns the current set of event loop metrics. + * + * It is recommended to use this property inside a function whose execution was + * scheduled using `setImmediate` to avoid collecting metrics before finishing all + * operations scheduled during the current loop iteration. + * @since v22.8.0, v20.18.0 + */ + readonly uvMetricsInfo: UVMetrics; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + interface MarkOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * An optional timestamp to be used as the mark time. + * @default `performance.now()` + */ + startTime?: number | undefined; + } + interface MeasureOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown; + /** + * Duration between start and end times. + */ + duration?: number | undefined; + /** + * Timestamp to be used as the end time, or a string identifying a previously recorded mark. + */ + end?: number | string | undefined; + /** + * Timestamp to be used as the start time, or a string identifying a previously recorded mark. + */ + start?: number | string | undefined; + } + interface TimerifyOptions { + /** + * A histogram object created using `perf_hooks.createHistogram()` that will record runtime + * durations in nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + interface Performance { + /** + * If `name` is not provided, removes all `PerformanceMark` objects from the Performance Timeline. + * If `name` is provided, removes only the named mark. + * @since v8.5.0 + */ + clearMarks(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceMeasure` objects from the Performance Timeline. + * If `name` is provided, removes only the named measure. + * @since v16.7.0 + */ + clearMeasures(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceResourceTiming` objects from the Resource Timeline. + * If `name` is provided, removes only the named resource. + * @since v18.2.0, v16.17.0 + */ + clearResourceTimings(name?: string): void; + /** + * This is an alias of `perf_hooks.eventLoopUtilization()`. + * + * _This property is an extension by Node.js. It is not available in Web browsers._ + * @since v14.10.0, v12.19.0 + * @param utilization1 The result of a previous call to + * `eventLoopUtilization()`. + * @param utilization2 The result of a previous call to + * `eventLoopUtilization()` prior to `utilization1`. + */ + eventLoopUtilization( + utilization1?: EventLoopUtilization, + utilization2?: EventLoopUtilization, + ): EventLoopUtilization; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. + * If you are only interested in performance entries of certain types or that have certain names, see + * `performance.getEntriesByType()` and `performance.getEntriesByName()`. + * @since v16.7.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`. + * @param name + * @param type + * @since v16.7.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.entryType` is equal to `type`. + * @param type + * @since v16.7.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + /** + * Creates a new `PerformanceMark` entry in the Performance Timeline. + * A `PerformanceMark` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'mark'`, + * and whose `performanceEntry.duration` is always `0`. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * + * The created `PerformanceMark` entry is put in the global Performance Timeline and can be queried with + * `performance.getEntries`, `performance.getEntriesByName`, and `performance.getEntriesByType`. When the observation is + * performed, the entries should be cleared from the global Performance Timeline manually with `performance.clearMarks`. + * @param name + */ + mark(name: string, options?: MarkOptions): PerformanceMark; + /** + * Creates a new `PerformanceResourceTiming` entry in the Resource Timeline. + * A `PerformanceResourceTiming` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'resource'`. + * Performance resources are used to mark moments in the Resource Timeline. + * @param timingInfo [Fetch Timing Info](https://fetch.spec.whatwg.org/#fetch-timing-info) + * @param requestedUrl The resource url + * @param initiatorType The initiator name, e.g: 'fetch' + * @param global + * @param cacheMode The cache mode must be an empty string ('') or 'local' + * @param bodyInfo [Fetch Response Body Info](https://fetch.spec.whatwg.org/#response-body-info) + * @param responseStatus The response's status code + * @param deliveryType The delivery type. Default: ''. + * @since v18.2.0, v16.17.0 + */ + markResourceTiming( + timingInfo: object, + requestedUrl: string, + initiatorType: string, + global: object, + cacheMode: "" | "local", + bodyInfo: object, + responseStatus: number, + deliveryType?: string, + ): PerformanceResourceTiming; + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + * @return The PerformanceMeasure entry that was created + */ + measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; + measure(name: string, options: MeasureOptions): PerformanceMeasure; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * An instance of the `PerformanceNodeTiming` class that provides performance metrics for specific Node.js operational milestones. + * @since v8.5.0 + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * Returns the current high resolution millisecond timestamp, where 0 represents the start of the current `node` process. + * @since v8.5.0 + */ + now(): number; + /** + * Sets the global performance resource timing buffer size to the specified number of "resource" type performance entry objects. + * + * By default the max buffer size is set to 250. + * @since v18.8.0 + */ + setResourceTimingBufferSize(maxSize: number): void; + /** + * The [`timeOrigin`](https://w3c.github.io/hr-time/#dom-performance-timeorigin) specifies the high resolution millisecond timestamp + * at which the current `node` process began, measured in Unix time. + * @since v8.5.0 + */ + readonly timeOrigin: number; + /** + * This is an alias of `perf_hooks.timerify()`. + * + * _This property is an extension by Node.js. It is not available in Web browsers._ + * @since v8.5.0 + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * An object which is JSON representation of the performance object. It is similar to + * [`window.performance.toJSON`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/toJSON) in browsers. + * @since v16.1.0 + */ + toJSON(): any; + } + class PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is + * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ entryTypes: ['mark', 'measure'] }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType` is equal to `type`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + /** + * @since v8.5.0 + */ + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + /** + * Disconnects the `PerformanceObserver` instance from all notifications. + * @since v8.5.0 + */ + disconnect(): void; + /** + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes` or `options.type`: + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called once asynchronously. `list` contains three items. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: readonly EntryType[]; + buffered?: boolean | undefined; + } + | { + type: EntryType; + buffered?: boolean | undefined; + }, + ): void; + /** + * @since v16.0.0 + * @returns Current list of entries stored in the performance observer, emptying it out. + */ + takeRecords(): PerformanceEntry[]; + } + /** + * Provides detailed network timing data regarding the loading of an application's resources. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceResourceTiming extends PerformanceEntry { + readonly entryType: "resource"; + protected constructor(); + /** + * The high resolution millisecond timestamp at immediately before dispatching the `fetch` + * request. If the resource is not intercepted by a worker the property will always return 0. + * @since v18.2.0, v16.17.0 + */ + readonly workerStart: number; + /** + * The high resolution millisecond timestamp that represents the start time of the fetch which + * initiates the redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectStart: number; + /** + * The high resolution millisecond timestamp that will be created immediately after receiving + * the last byte of the response of the last redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectEnd: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts to fetch the resource. + * @since v18.2.0, v16.17.0 + */ + readonly fetchStart: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts the domain name lookup + * for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after the Node.js finished + * the domain name lookup for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts to + * establish the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js finishes + * establishing the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts the + * handshake process to secure the current connection. + * @since v18.2.0, v16.17.0 + */ + readonly secureConnectionStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js receives the + * first byte of the response from the server. + * @since v18.2.0, v16.17.0 + */ + readonly requestStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js receives the + * last byte of the resource or immediately before the transport connection is closed, whichever comes first. + * @since v18.2.0, v16.17.0 + */ + readonly responseEnd: number; + /** + * A number representing the size (in octets) of the fetched resource. The size includes the response header + * fields plus the response payload body. + * @since v18.2.0, v16.17.0 + */ + readonly transferSize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly encodedBodySize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the message body, after + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly decodedBodySize: number; + /** + * Returns a `object` that is the JSON representation of the `PerformanceResourceTiming` object + * @since v18.2.0, v16.17.0 + */ + toJSON(): any; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + const performance: Performance; + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * The number of samples recorded by the histogram. + * @since v17.4.0, v16.14.0 + */ + readonly count: number; + /** + * The number of samples recorded by the histogram. + * v17.4.0, v16.14.0 + */ + readonly countBigInt: bigint; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold. + * @since v17.4.0, v16.14.0 + */ + readonly exceedsBigInt: bigint; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The maximum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly maxBigInt: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The minimum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly minBigInt: bigint; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + /** + * Returns the value at the given percentile. + * @since v17.4.0, v16.14.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentileBigInt(percentile: number): bigint; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v17.4.0, v16.14.0 + */ + readonly percentilesBigInt: Map; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + /** + * Disables the update interval timer when the histogram is disposed. + * + * ```js + * const { monitorEventLoopDelay } = require('node:perf_hooks'); + * { + * using hist = monitorEventLoopDelay({ resolution: 20 }); + * hist.enable(); + * // The histogram will be disabled when the block is exited. + * } + * ``` + * @since v24.2.0 + */ + [Symbol.dispose](): void; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0, v14.18.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from `other` to this histogram. + * @since v17.4.0, v16.14.0 + */ + add(other: RecordableHistogram): void; + } + interface CreateHistogramOptions { + /** + * The lowest discernible value. Must be an integer value greater than 0. + * @default 1 + */ + lowest?: number | bigint | undefined; + /** + * The highest recordable value. Must be an integer value that is equal to + * or greater than two times `lowest`. + * @default Number.MAX_SAFE_INTEGER + */ + highest?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between `1` and `5`. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a {@link RecordableHistogram `RecordableHistogram`}. + * @since v15.9.0, v14.18.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; + /** + * The `eventLoopUtilization()` function returns an object that contains the + * cumulative duration of time the event loop has been both idle and active as a + * high resolution milliseconds timer. The `utilization` value is the calculated + * Event Loop Utilization (ELU). + * + * If bootstrapping has not yet finished on the main thread the properties have + * the value of `0`. The ELU is immediately available on + * [Worker threads](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html#worker-threads) + * since bootstrap happens within the event loop. + * + * Both `utilization1` and `utilization2` are optional parameters. + * + * If `utilization1` is passed, then the delta between the current call's `active` + * and `idle` times, as well as the corresponding `utilization` value are + * calculated and returned (similar to `process.hrtime()`). + * + * If `utilization1` and `utilization2` are both passed, then the delta is + * calculated between the two arguments. This is a convenience option because, + * unlike `process.hrtime()`, calculating the ELU is more complex than a + * single subtraction. + * + * ELU is similar to CPU utilization, except that it only measures event loop + * statistics and not CPU usage. It represents the percentage of time the event + * loop has spent outside the event loop's event provider (e.g. `epoll_wait`). + * No other CPU idle time is taken into consideration. The following is an example + * of how a mostly idle process will have a high ELU. + * + * ```js + * import { eventLoopUtilization } from 'node:perf_hooks'; + * import { spawnSync } from 'node:child_process'; + * + * setImmediate(() => { + * const elu = eventLoopUtilization(); + * spawnSync('sleep', ['5']); + * console.log(eventLoopUtilization(elu).utilization); + * }); + * ``` + * + * Although the CPU is mostly idle while running this script, the value of `utilization` + * is `1`. This is because the call to `child_process.spawnSync()` blocks the event loop + * from proceeding. + * + * Passing in a user-defined object instead of the result of a previous call to + * `eventLoopUtilization()` will lead to undefined behavior. The return values are not + * guaranteed to reflect any correct state of the event loop. + * @since v24.12.0 + * @param utilization1 The result of a previous call to `eventLoopUtilization()`. + * @param utilization2 The result of a previous call to `eventLoopUtilization()` prior to `utilization1`. + */ + function eventLoopUtilization( + utilization1?: EventLoopUtilization, + utilization2?: EventLoopUtilization, + ): EventLoopUtilization; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * import { monitorEventLoopDelay } from 'node:perf_hooks'; + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Wraps a function within a new function that measures the running time of the + * wrapped function. A `PerformanceObserver` must be subscribed to the `'function'` + * event type in order for the timing details to be accessed. + * + * ```js + * import { timerify, performance, PerformanceObserver } from 'node:perf_hooks'; + * + * function someFunction() { + * console.log('hello world'); + * } + * + * const wrapped = timerify(someFunction); + * + * const obs = new PerformanceObserver((list) => { + * console.log(list.getEntries()[0].duration); + * + * performance.clearMarks(); + * performance.clearMeasures(); + * obs.disconnect(); + * }); + * obs.observe({ entryTypes: ['function'] }); + * + * // A performance timeline entry will be created + * wrapped(); + * ``` + * + * If the wrapped function returns a promise, a finally handler will be attached + * to the promise and the duration will be reported once the finally handler is invoked. + * @since v24.12.0 + */ + function timerify any>(fn: T, options?: TimerifyOptions): T; + import { + performance as _performance, + PerformanceEntry as _PerformanceEntry, + PerformanceMark as _PerformanceMark, + PerformanceMeasure as _PerformanceMeasure, + PerformanceObserver as _PerformanceObserver, + PerformanceObserverEntryList as _PerformanceObserverEntryList, + PerformanceResourceTiming as _PerformanceResourceTiming, + } from "perf_hooks"; + global { + /** + * `PerformanceEntry` is a global reference for `import { PerformanceEntry } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceentry + * @since v19.0.0 + */ + var PerformanceEntry: typeof globalThis extends { + onmessage: any; + PerformanceEntry: infer T; + } ? T + : typeof _PerformanceEntry; + /** + * `PerformanceMark` is a global reference for `import { PerformanceMark } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performancemark + * @since v19.0.0 + */ + var PerformanceMark: typeof globalThis extends { + onmessage: any; + PerformanceMark: infer T; + } ? T + : typeof _PerformanceMark; + /** + * `PerformanceMeasure` is a global reference for `import { PerformanceMeasure } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performancemeasure + * @since v19.0.0 + */ + var PerformanceMeasure: typeof globalThis extends { + onmessage: any; + PerformanceMeasure: infer T; + } ? T + : typeof _PerformanceMeasure; + /** + * `PerformanceObserver` is a global reference for `import { PerformanceObserver } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceobserver + * @since v19.0.0 + */ + var PerformanceObserver: typeof globalThis extends { + onmessage: any; + PerformanceObserver: infer T; + } ? T + : typeof _PerformanceObserver; + /** + * `PerformanceObserverEntryList` is a global reference for `import { PerformanceObserverEntryList } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceobserverentrylist + * @since v19.0.0 + */ + var PerformanceObserverEntryList: typeof globalThis extends { + onmessage: any; + PerformanceObserverEntryList: infer T; + } ? T + : typeof _PerformanceObserverEntryList; + /** + * `PerformanceResourceTiming` is a global reference for `import { PerformanceResourceTiming } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceresourcetiming + * @since v19.0.0 + */ + var PerformanceResourceTiming: typeof globalThis extends { + onmessage: any; + PerformanceResourceTiming: infer T; + } ? T + : typeof _PerformanceResourceTiming; + /** + * `performance` is a global reference for `import { performance } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performance + * @since v16.0.0 + */ + var performance: typeof globalThis extends { + onmessage: any; + performance: infer T; + } ? T + : typeof _performance; + } +} +declare module "node:perf_hooks" { + export * from "perf_hooks"; +} diff --git a/tools/ui/node_modules/@types/node/process.d.ts b/tools/ui/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7b69dd5459c63479d751faf982e4f37b45213673 --- /dev/null +++ b/tools/ui/node_modules/@types/node/process.d.ts @@ -0,0 +1,2102 @@ +declare module "process" { + import { Control, MessageOptions, SendHandle } from "node:child_process"; + import { PathLike } from "node:fs"; + import * as tty from "node:tty"; + import { Worker } from "node:worker_threads"; + + interface BuiltInModule { + "assert": typeof import("assert"); + "node:assert": typeof import("node:assert"); + "assert/strict": typeof import("assert/strict"); + "node:assert/strict": typeof import("node:assert/strict"); + "async_hooks": typeof import("async_hooks"); + "node:async_hooks": typeof import("node:async_hooks"); + "buffer": typeof import("buffer"); + "node:buffer": typeof import("node:buffer"); + "child_process": typeof import("child_process"); + "node:child_process": typeof import("node:child_process"); + "cluster": typeof import("cluster"); + "node:cluster": typeof import("node:cluster"); + "console": typeof import("console"); + "node:console": typeof import("node:console"); + "constants": typeof import("constants"); + "node:constants": typeof import("node:constants"); + "crypto": typeof import("crypto"); + "node:crypto": typeof import("node:crypto"); + "dgram": typeof import("dgram"); + "node:dgram": typeof import("node:dgram"); + "diagnostics_channel": typeof import("diagnostics_channel"); + "node:diagnostics_channel": typeof import("node:diagnostics_channel"); + "dns": typeof import("dns"); + "node:dns": typeof import("node:dns"); + "dns/promises": typeof import("dns/promises"); + "node:dns/promises": typeof import("node:dns/promises"); + "domain": typeof import("domain"); + "node:domain": typeof import("node:domain"); + "events": typeof import("events"); + "node:events": typeof import("node:events"); + "fs": typeof import("fs"); + "node:fs": typeof import("node:fs"); + "fs/promises": typeof import("fs/promises"); + "node:fs/promises": typeof import("node:fs/promises"); + "http": typeof import("http"); + "node:http": typeof import("node:http"); + "http2": typeof import("http2"); + "node:http2": typeof import("node:http2"); + "https": typeof import("https"); + "node:https": typeof import("node:https"); + "inspector": typeof import("inspector"); + "node:inspector": typeof import("node:inspector"); + "inspector/promises": typeof import("inspector/promises"); + "node:inspector/promises": typeof import("node:inspector/promises"); + "module": typeof import("module"); + "node:module": typeof import("node:module"); + "net": typeof import("net"); + "node:net": typeof import("node:net"); + "os": typeof import("os"); + "node:os": typeof import("node:os"); + "path": typeof import("path"); + "node:path": typeof import("node:path"); + "path/posix": typeof import("path/posix"); + "node:path/posix": typeof import("node:path/posix"); + "path/win32": typeof import("path/win32"); + "node:path/win32": typeof import("node:path/win32"); + "perf_hooks": typeof import("perf_hooks"); + "node:perf_hooks": typeof import("node:perf_hooks"); + "process": typeof import("process"); + "node:process": typeof import("node:process"); + "punycode": typeof import("punycode"); + "node:punycode": typeof import("node:punycode"); + "querystring": typeof import("querystring"); + "node:querystring": typeof import("node:querystring"); + "readline": typeof import("readline"); + "node:readline": typeof import("node:readline"); + "readline/promises": typeof import("readline/promises"); + "node:readline/promises": typeof import("node:readline/promises"); + "repl": typeof import("repl"); + "node:repl": typeof import("node:repl"); + "node:sea": typeof import("node:sea"); + "node:sqlite": typeof import("node:sqlite"); + "stream": typeof import("stream"); + "node:stream": typeof import("node:stream"); + "stream/consumers": typeof import("stream/consumers"); + "node:stream/consumers": typeof import("node:stream/consumers"); + "stream/promises": typeof import("stream/promises"); + "node:stream/promises": typeof import("node:stream/promises"); + "stream/web": typeof import("stream/web"); + "node:stream/web": typeof import("node:stream/web"); + "string_decoder": typeof import("string_decoder"); + "node:string_decoder": typeof import("node:string_decoder"); + "node:test": typeof import("node:test"); + "node:test/reporters": typeof import("node:test/reporters"); + "timers": typeof import("timers"); + "node:timers": typeof import("node:timers"); + "timers/promises": typeof import("timers/promises"); + "node:timers/promises": typeof import("node:timers/promises"); + "tls": typeof import("tls"); + "node:tls": typeof import("node:tls"); + "trace_events": typeof import("trace_events"); + "node:trace_events": typeof import("node:trace_events"); + "tty": typeof import("tty"); + "node:tty": typeof import("node:tty"); + "url": typeof import("url"); + "node:url": typeof import("node:url"); + "util": typeof import("util"); + "node:util": typeof import("node:util"); + "sys": typeof import("util"); + "node:sys": typeof import("node:util"); + "util/types": typeof import("util/types"); + "node:util/types": typeof import("node:util/types"); + "v8": typeof import("v8"); + "node:v8": typeof import("node:v8"); + "vm": typeof import("vm"); + "node:vm": typeof import("node:vm"); + "wasi": typeof import("wasi"); + "node:wasi": typeof import("node:wasi"); + "worker_threads": typeof import("worker_threads"); + "node:worker_threads": typeof import("node:worker_threads"); + "zlib": typeof import("zlib"); + "node:zlib": typeof import("node:zlib"); + } + global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + /** + * Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the + * process, including all C++ and JavaScript objects and code. + */ + rss: number; + /** + * Refers to V8's memory usage. + */ + heapTotal: number; + /** + * Refers to V8's memory usage. + */ + heapUsed: number; + external: number; + /** + * Refers to memory allocated for `ArrayBuffer`s and `SharedArrayBuffer`s, including all Node.js Buffers. This is also included + * in the external value. When Node.js is used as an embedded library, this value may be `0` because allocations for `ArrayBuffer`s + * may not be tracked in that case. + */ + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessFeatures { + /** + * A boolean value that is `true` if the current Node.js build is caching builtin modules. + * @since v12.0.0 + */ + readonly cached_builtins: boolean; + /** + * A boolean value that is `true` if the current Node.js build is a debug build. + * @since v0.5.5 + */ + readonly debug: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes the inspector. + * @since v11.10.0 + */ + readonly inspector: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for IPv6. + * + * Since all Node.js builds have IPv6 support, this value is always `true`. + * @since v0.5.3 + * @deprecated This property is always true, and any checks based on it are redundant. + */ + readonly ipv6: boolean; + /** + * A boolean value that is `true` if the current Node.js build supports + * [loading ECMAScript modules using `require()`](https://nodejs.org/docs/latest-v24.x/api/modules.md#loading-ecmascript-modules-using-require). + * @since v22.10.0 + */ + readonly require_module: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for TLS. + * @since v0.5.3 + */ + readonly tls: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for ALPN in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional ALPN support. + * This value is therefore identical to that of `process.features.tls`. + * @since v4.8.0 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_alpn: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for OCSP in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional OCSP support. + * This value is therefore identical to that of `process.features.tls`. + * @since v0.11.13 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_ocsp: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for SNI in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional SNI support. + * This value is therefore identical to that of `process.features.tls`. + * @since v0.5.3 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_sni: boolean; + /** + * A value that is `"strip"` by default, + * `"transform"` if Node.js is run with `--experimental-transform-types`, and `false` if + * Node.js is run with `--no-strip-types`. + * @since v22.10.0 + */ + readonly typescript: "strip" | "transform" | false; + /** + * A boolean value that is `true` if the current Node.js build includes support for libuv. + * + * Since it's not possible to build Node.js without libuv, this value is always `true`. + * @since v0.5.3 + * @deprecated This property is always true, and any checks based on it are redundant. + */ + readonly uv: boolean; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = + | "aix" + | "android" + | "darwin" + | "freebsd" + | "haiku" + | "linux" + | "openbsd" + | "sunos" + | "win32" + | "cygwin" + | "netbsd"; + type Architecture = + | "arm" + | "arm64" + | "ia32" + | "loong64" + | "mips" + | "mipsel" + | "ppc64" + | "riscv64" + | "s390x" + | "x64"; + type Signals = + | "SIGABRT" + | "SIGALRM" + | "SIGBUS" + | "SIGCHLD" + | "SIGCONT" + | "SIGFPE" + | "SIGHUP" + | "SIGILL" + | "SIGINT" + | "SIGIO" + | "SIGIOT" + | "SIGKILL" + | "SIGPIPE" + | "SIGPOLL" + | "SIGPROF" + | "SIGPWR" + | "SIGQUIT" + | "SIGSEGV" + | "SIGSTKFLT" + | "SIGSTOP" + | "SIGSYS" + | "SIGTERM" + | "SIGTRAP" + | "SIGTSTP" + | "SIGTTIN" + | "SIGTTOU" + | "SIGUNUSED" + | "SIGURG" + | "SIGUSR1" + | "SIGUSR2" + | "SIGVTALRM" + | "SIGWINCH" + | "SIGXCPU" + | "SIGXFSZ" + | "SIGBREAK" + | "SIGLOST" + | "SIGINFO"; + type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection"; + type MultipleResolveType = "resolve" | "reject"; + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; + /** + * Most of the time the unhandledRejection will be an Error, but this should not be relied upon + * as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error. + */ + type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: SendHandle) => void; + type SignalsListener = (signal: Signals) => void; + type MultipleResolveListener = ( + type: MultipleResolveType, + promise: Promise, + value: unknown, + ) => void; + type WorkerListener = (worker: Worker) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict {} + interface HRTime { + /** + * This is the legacy version of {@link process.hrtime.bigint()} + * before bigint was introduced in JavaScript. + * + * The `process.hrtime()` method returns the current high-resolution real time in a `[seconds, nanoseconds]` tuple `Array`, + * where `nanoseconds` is the remaining part of the real time that can't be represented in second precision. + * + * `time` is an optional parameter that must be the result of a previous `process.hrtime()` call to diff with the current time. + * If the parameter passed in is not a tuple `Array`, a TypeError will be thrown. + * Passing in a user-defined array instead of the result of a previous call to `process.hrtime()` will lead to undefined behavior. + * + * These times are relative to an arbitrary time in the past, + * and not related to the time of day and therefore not subject to clock drift. + * The primary use is for measuring performance between intervals: + * ```js + * const { hrtime } = require('node:process'); + * const NS_PER_SEC = 1e9; + * const time = hrtime(); + * // [ 1800216, 25 ] + * + * setTimeout(() => { + * const diff = hrtime(time); + * // [ 1, 552 ] + * + * console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`); + * // Benchmark took 1000000552 nanoseconds + * }, 1000); + * ``` + * @since 0.7.6 + * @legacy Use {@link process.hrtime.bigint()} instead. + * @param time The result of a previous call to `process.hrtime()` + */ + (time?: [number, number]): [number, number]; + /** + * The `bigint` version of the {@link process.hrtime()} method returning the current high-resolution real time in nanoseconds as a `bigint`. + * + * Unlike {@link process.hrtime()}, it does not support an additional time argument since the difference can just be computed directly by subtraction of the two `bigint`s. + * ```js + * import { hrtime } from 'node:process'; + * + * const start = hrtime.bigint(); + * // 191051479007711n + * + * setTimeout(() => { + * const end = hrtime.bigint(); + * // 191052633396993n + * + * console.log(`Benchmark took ${end - start} nanoseconds`); + * // Benchmark took 1154389282 nanoseconds + * }, 1000); + * ``` + * @since v10.7.0 + */ + bigint(): bigint; + } + interface ProcessPermission { + /** + * Verifies that the process is able to access the given scope and reference. + * If no reference is provided, a global scope is assumed, for instance, `process.permission.has('fs.read')` + * will check if the process has ALL file system read permissions. + * + * The reference has a meaning based on the provided scope. For example, the reference when the scope is File System means files and folders. + * + * The available scopes are: + * + * * `fs` - All File System + * * `fs.read` - File System read operations + * * `fs.write` - File System write operations + * * `child` - Child process spawning operations + * * `worker` - Worker thread spawning operation + * + * ```js + * // Check if the process has permission to read the README file + * process.permission.has('fs.read', './README.md'); + * // Check if the process has read permission operations + * process.permission.has('fs.read'); + * ``` + * @since v20.0.0 + */ + has(scope: string, reference?: string): boolean; + } + interface ProcessReport { + /** + * Write reports in a compact format, single-line JSON, more easily consumable by log processing systems + * than the default multi-line format designed for human consumption. + * @since v13.12.0, v12.17.0 + */ + compact: boolean; + /** + * Directory where the report is written. + * The default value is the empty string, indicating that reports are written to the current + * working directory of the Node.js process. + */ + directory: string; + /** + * Filename where the report is written. If set to the empty string, the output filename will be comprised + * of a timestamp, PID, and sequence number. The default value is the empty string. + */ + filename: string; + /** + * Returns a JavaScript Object representation of a diagnostic report for the running process. + * The report's JavaScript stack trace is taken from `err`, if present. + */ + getReport(err?: Error): object; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @default false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * If true, a diagnostic report is generated without the environment variables. + * @default false + */ + excludeEnv: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from `err`, if present. + * + * If the value of filename is set to `'stdout'` or `'stderr'`, the report is written + * to the stdout or stderr of the process respectively. + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param err A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string, err?: Error): string; + writeReport(err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'node:process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling `process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. If a [program entry point](https://nodejs.org/docs/latest-v24.x/api/cli.html#program-entry-point) was provided, the second element + * will be the absolute path to it. The remaining elements are additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'node:process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```bash + * node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```bash + * node --icu-data-dir=./foo --require ./bar.js script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ["--icu-data-dir=./foo", "--require", "./bar.js"] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'node:process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'node:process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'node:process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.dlopen()` method allows dynamically loading shared objects. It is primarily used by `require()` to load C++ Addons, and + * should not be used directly, except in special cases. In other words, `require()` should be preferred over `process.dlopen()` + * unless there are specific reasons such as custom dlopen flags or loading from ES modules. + * + * The `flags` argument is an integer that allows to specify dlopen behavior. See the `[os.constants.dlopen](https://nodejs.org/docs/latest-v24.x/api/os.html#dlopen-constants)` + * documentation for details. + * + * An important requirement when calling `process.dlopen()` is that the `module` instance must be passed. Functions exported by the C++ Addon + * are then accessible via `module.exports`. + * + * The example below shows how to load a C++ Addon, named `local.node`, that exports a `foo` function. All the symbols are loaded before the call returns, by passing the `RTLD_NOW` constant. + * In this example the constant is assumed to be available. + * + * ```js + * import { dlopen } from 'node:process'; + * import { constants } from 'node:os'; + * import { fileURLToPath } from 'node:url'; + * + * const module = { exports: {} }; + * dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)), + * constants.dlopen.RTLD_NOW); + * module.exports.foo(); + * ``` + */ + dlopen(module: object, filename: string, flags?: number): void; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string. + * emitWarning('Something happened!'); + * // Emits: (node: 56338) Warning: Something happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string and a type. + * emitWarning('Something Happened!', 'CustomWarning'); + * // Emits: (node:56338) CustomWarning: Something Happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * emitWarning('Something happened!', 'CustomWarning', 'WARN001'); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ```js + * + * In each of the previous examples, an `Error` object is generated internally by `process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'node:process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, it will be passed through to the `'warning'` event handler + * unmodified (and the optional `type`, `code` and `ctor` arguments will be ignored): + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using an Error object. + * const myWarning = new Error('Something happened!'); + * // Use the Error name property to specify the type name + * myWarning.name = 'CustomWarning'; + * myWarning.code = 'WARN001'; + * + * emitWarning(myWarning); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ``` + * + * A `TypeError` is thrown if `warning` is anything other than a string or `Error` object. + * + * While process warnings use `Error` objects, the process warning mechanism is not a replacement for normal error handling mechanisms. + * + * The following additional handling is implemented if the warning `type` is `'DeprecationWarning'`: + * * If the `--throw-deprecation` command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event. + * * If the `--no-deprecation` command-line flag is used, the deprecation warning is suppressed. + * * If the `--trace-deprecation` command-line flag is used, the deprecation warning is printed to `stderr` along with the full stack trace. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```bash + * node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'node:process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'node:process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread's `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner + * unlike the main thread. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'node:process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and `process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()` explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the `process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'node:process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the `process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'node:process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. + */ + exit(code?: number | string | null): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @default undefined + * @since v0.11.8 + */ + exitCode: number | string | null | undefined; + finalization: { + /** + * This function registers a callback to be called when the process emits the `exit` event if the `ref` object was not garbage collected. + * If the object `ref` was garbage collected before the `exit` event is emitted, the callback will be removed from the finalization registry, and it will not be called on process exit. + * + * Inside the callback you can release the resources allocated by the `ref` object. + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, + * this means that there is a possibility that the callback will not be called under special circumstances. + * + * The idea of ​​this function is to help you free up resources when the starts process exiting, but also let the object be garbage collected if it is no longer being used. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + register(ref: T, callback: (ref: T, event: "exit") => void): void; + /** + * This function behaves exactly like the `register`, except that the callback will be called when the process emits the `beforeExit` event if `ref` object was not garbage collected. + * + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, this means that there is a possibility that the callback will not be called under special circumstances. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + registerBeforeExit(ref: T, callback: (ref: T, event: "beforeExit") => void): void; + /** + * This function remove the register of the object from the finalization registry, so the callback will not be called anymore. + * @param ref The reference to the resource that was registered previously. + * @since v22.5.0 + * @experimental + */ + unregister(ref: object): void; + }; + /** + * The `process.getActiveResourcesInfo()` method returns an array of strings containing + * the types of the active resources that are currently keeping the event loop alive. + * + * ```js + * import { getActiveResourcesInfo } from 'node:process'; + * import { setTimeout } from 'node:timers'; + + * console.log('Before:', getActiveResourcesInfo()); + * setTimeout(() => {}, 1000); + * console.log('After:', getActiveResourcesInfo()); + * // Prints: + * // Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ] + * // After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ] + * ``` + * @since v17.3.0, v16.14.0 + */ + getActiveResourcesInfo(): string[]; + /** + * Provides a way to load built-in modules in a globally available function. + * @param id ID of the built-in module being requested. + */ + getBuiltinModule(id: ID): BuiltInModule[ID]; + getBuiltinModule(id: string): object | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid?: () => number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid?: (id: number | string) => void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid?: () => number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid?: (id: number | string) => void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid?: () => number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid?: (id: number | string) => void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid?: () => number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid?: (id: number | string) => void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups?: () => number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups?: (groups: ReadonlyArray) => void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function, `process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. + * @since v20.7.0 + * @experimental + */ + readonly sourceMapsEnabled: boolean; + /** + * This function enables or disables the [Source Map v3](https://sourcemaps.info/spec.html) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options `--enable-source-maps`. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. + * @since v16.6.0, v14.18.0 + * @experimental + */ + setSourceMapsEnabled(value: boolean): void; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'node:process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'node:process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '20.2.0', + * acorn: '8.8.2', + * ada: '2.4.0', + * ares: '1.19.0', + * base64: '0.5.0', + * brotli: '1.0.9', + * cjs_module_lexer: '1.2.2', + * cldr: '43.0', + * icu: '73.1', + * llhttp: '8.1.0', + * modules: '115', + * napi: '8', + * nghttp2: '1.52.0', + * nghttp3: '0.7.0', + * ngtcp2: '0.8.1', + * openssl: '3.0.8+quic', + * simdutf: '3.2.9', + * tz: '2023c', + * undici: '5.22.0', + * unicode: '15.0', + * uv: '1.44.2', + * uvwasi: '0.0.16', + * v8: '11.3.244.8-node.9', + * zlib: '1.2.13' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns a frozen `Object` containing the + * JavaScript representation of the configure options used to compile the current + * Node.js executable. This is the same as the `config.gypi` file that was produced + * when running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'node:process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * Loads the environment configuration from a `.env` file into `process.env`. If + * the file is not found, error will be thrown. + * + * To load a specific .env file by specifying its path, use the following code: + * + * ```js + * import { loadEnvFile } from 'node:process'; + * + * loadEnvFile('./development.env') + * ``` + * @since v20.12.0 + * @param path The path to the .env file + */ + loadEnvFile(path?: PathLike): void; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'node:process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'node:process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.threadCpuUsage()` method returns the user and system CPU time usage of + * the current worker thread, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). + * + * The result of a previous call to `process.threadCpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * @since v23.9.0 + * @param previousValue A previous return value from calling + * `process.threadCpuUsage()` + */ + threadCpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the `process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ` memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, + * `'mipsel'`, `'ppc64'`, `'riscv64'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from 'node:process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: Architecture; + /** + * The `process.platform` property returns a string identifying the operating + * system platform for which the Node.js binary was compiled. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'node:process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module; + memoryUsage: MemoryUsageFn; + /** + * Gets the amount of memory available to the process (in bytes) based on + * limits imposed by the OS. If there is no such constraint, or the constraint + * is unknown, `0` is returned. + * + * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more + * information. + * @since v19.6.0, v18.15.0 + */ + constrainedMemory(): number; + /** + * Gets the amount of free memory that is still available to the process (in bytes). + * See [`uv_get_available_memory`](https://nodejs.org/docs/latest-v24.x/api/process.html#processavailablememory) for more information. + * @since v20.13.0 + */ + availableMemory(): number; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'node:process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'node:process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * The process.noDeprecation property indicates whether the --no-deprecation flag is set on the current Node.js process. + * See the documentation for the ['warning' event](https://nodejs.org/docs/latest/api/process.html#event-warning) and the [emitWarning()](https://nodejs.org/docs/latest/api/process.html#processemitwarningwarning-type-code-ctor) method for more information about this flag's behavior. + */ + noDeprecation?: boolean; + /** + * This API is available through the [--permission](https://nodejs.org/api/cli.html#--permission) flag. + * + * `process.permission` is an object whose methods are used to manage permissions for the current process. + * Additional documentation is available in the [Permission Model](https://nodejs.org/api/permissions.html#permission-model). + * @since v20.0.0 + */ + permission: ProcessPermission; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Hydrogen', + * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the `name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + readonly features: ProcessFeatures; + /** + * The `process.traceProcessWarnings` property indicates whether the `--trace-warnings` flag + * is set on the current Node.js process. This property allows programmatic control over the + * tracing of warnings, enabling or disabling stack traces for warnings at runtime. + * + * ```js + * // Enable trace warnings + * process.traceProcessWarnings = true; + * + * // Emit a warning with a stack trace + * process.emitWarning('Warning with stack trace'); + * + * // Disable trace warnings + * process.traceProcessWarnings = false; + * ``` + * @since v6.10.0 + */ + traceProcessWarnings: boolean; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If the Node.js process was spawned with an IPC channel, the process.channel property is a reference to the IPC channel. + * If no IPC channel exists, this property is undefined. + * @since v7.1.0 + */ + channel?: Control; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be `undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send?( + message: any, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + send?( + message: any, + sendHandle: SendHandle, + callback?: (error: Error | null) => void, + ): boolean; + send?( + message: any, + callback: (error: Error | null) => void, + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel, `process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return `true` so long as the IPC + * channel is connected and will return `false` after `process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides `Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g., `inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'node:process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic reports for the current process. + * Additional documentation is available in the [report documentation](https://nodejs.org/docs/latest-v24.x/api/report.html). + * @since v11.8.0 + */ + report: ProcessReport; + /** + * ```js + * import { resourceUsage } from 'node:process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The initial value of `process.throwDeprecation` indicates whether the `--throw-deprecation` flag is set on the current Node.js process. `process.throwDeprecation` + * is mutable, so whether or not deprecation warnings result in errors may be altered at runtime. See the documentation for the 'warning' event and the emitWarning() + * method for more information. + * + * ```bash + * $ node --throw-deprecation -p "process.throwDeprecation" + * true + * $ node -p "process.throwDeprecation" + * undefined + * $ node + * > process.emitWarning('test', 'DeprecationWarning'); + * undefined + * > (node:26598) DeprecationWarning: test + * > process.throwDeprecation = true; + * true + * > process.emitWarning('test', 'DeprecationWarning'); + * Thrown: + * [DeprecationWarning: test] { name: 'DeprecationWarning' } + * ``` + * @since v0.9.12 + */ + throwDeprecation: boolean; + /** + * The `process.traceDeprecation` property indicates whether the `--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /** + * An object is "refable" if it implements the Node.js "Refable protocol". + * Specifically, this means that the object implements the `Symbol.for('nodejs.ref')` + * and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js + * event loop alive, while "unref'd" objects will not. Historically, this was + * implemented by using `ref()` and `unref()` methods directly on the objects. + * This pattern, however, is being deprecated in favor of the "Refable protocol" + * in order to better support Web Platform API types whose APIs cannot be modified + * to add `ref()` and `unref()` methods but still need to support that behavior. + * @since v22.14.0 + * @experimental + * @param maybeRefable An object that may be "refable". + */ + ref(maybeRefable: any): void; + /** + * An object is "unrefable" if it implements the Node.js "Refable protocol". + * Specifically, this means that the object implements the `Symbol.for('nodejs.ref')` + * and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js + * event loop alive, while "unref'd" objects will not. Historically, this was + * implemented by using `ref()` and `unref()` methods directly on the objects. + * This pattern, however, is being deprecated in favor of the "Refable protocol" + * in order to better support Web Platform API types whose APIs cannot be modified + * to add `ref()` and `unref()` methods but still need to support that behavior. + * @since v22.14.0 + * @experimental + * @param maybeRefable An object that may be "unref'd". + */ + unref(maybeRefable: any): void; + /** + * Replaces the current process with a new process. + * + * This is achieved by using the `execve` POSIX function and therefore no memory or other + * resources from the current process are preserved, except for the standard input, + * standard output and standard error file descriptor. + * + * All other resources are discarded by the system when the processes are swapped, without triggering + * any exit or close events and without running any cleanup handler. + * + * This function will never return, unless an error occurred. + * + * This function is not available on Windows or IBM i. + * @since v22.15.0 + * @experimental + * @param file The name or path of the executable file to run. + * @param args List of string arguments. No argument can contain a null-byte (`\u0000`). + * @param env Environment key-value pairs. + * No key or value can contain a null-byte (`\u0000`). + * **Default:** `process.env`. + */ + execve?(file: string, args?: readonly string[], env?: ProcessEnv): never; + /* EventEmitter */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: "workerMessage", listener: (value: any, source: number) => void): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + addListener(event: "worker", listener: WorkerListener): this; + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "uncaughtExceptionMonitor", error: Error): boolean; + emit(event: "unhandledRejection", reason: unknown, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: unknown, sendHandle: SendHandle): this; + emit(event: "workerMessage", value: any, source: number): this; + emit(event: Signals, signal?: Signals): boolean; + emit( + event: "multipleResolves", + type: MultipleResolveType, + promise: Promise, + value: unknown, + ): this; + emit(event: "worker", listener: WorkerListener): this; + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + on(event: "worker", listener: WorkerListener): this; + on(event: "workerMessage", listener: (value: any, source: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + once(event: "worker", listener: WorkerListener): this; + once(event: "workerMessage", listener: (value: any, source: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: "workerMessage", listener: (value: any, source: number) => void): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependListener(event: "worker", listener: WorkerListener): this; + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: "workerMessage", listener: (value: any, source: number) => void): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependOnceListener(event: "worker", listener: WorkerListener): this; + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: "workerMessage"): ((value: any, source: number) => void)[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + listeners(event: "worker"): WorkerListener[]; + } + } + } + export = process; +} +declare module "node:process" { + import process = require("process"); + export = process; +} diff --git a/tools/ui/node_modules/@types/node/punycode.d.ts b/tools/ui/node_modules/@types/node/punycode.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7ac26c8261b1903fbe7bf88e9209a14ef0138fe9 --- /dev/null +++ b/tools/ui/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,117 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated. **In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * import punycode from 'node:punycode'; + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word, `'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string `'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated Since v7.0.0 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/punycode.js) + */ +declare module "punycode" { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: readonly number[]): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module "node:punycode" { + export * from "punycode"; +} diff --git a/tools/ui/node_modules/@types/node/querystring.d.ts b/tools/ui/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..aaeefe8d3d38c80055964d56a9a3d5fc27e64c22 --- /dev/null +++ b/tools/ui/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,152 @@ +/** + * The `node:querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * import querystring from 'node:querystring'; + * ``` + * + * `querystring` is more performant than `URLSearchParams` but is not a + * standardized API. Use `URLSearchParams` when performance is not critical or + * when compatibility with browser code is desirable. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/querystring.js) + */ +declare module "querystring" { + interface StringifyOptions { + /** + * The function to use when converting URL-unsafe characters to percent-encoding in the query string. + * @default `querystring.escape()` + */ + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + /** + * Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations. + * @default 1000 + */ + maxKeys?: number | undefined; + /** + * The function to use when decoding percent-encoded characters in the query string. + * @default `querystring.unescape()` + */ + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends + NodeJS.Dict< + | string + | number + | boolean + | bigint + | ReadonlyArray + | null + > + {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`: [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative `encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```json + * { + * "foo": "bar", + * "abc": ["xyz", "123"] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given `str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module "node:querystring" { + export * from "querystring"; +} diff --git a/tools/ui/node_modules/@types/node/readline.d.ts b/tools/ui/node_modules/@types/node/readline.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5984dfd9537a41f39d6a3a6c01b84ebeb698276b --- /dev/null +++ b/tools/ui/node_modules/@types/node/readline.d.ts @@ -0,0 +1,600 @@ +/** + * The `node:readline` module provides an interface for reading data from a [Readable](https://nodejs.org/docs/latest-v24.x/api/stream.html#readable-streams) stream + * (such as [`process.stdin`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdin)) one line at a time. + * + * To use the promise-based APIs: + * + * ```js + * import * as readline from 'node:readline/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as readline from 'node:readline'; + * ``` + * + * The following simple example illustrates the basic use of the `node:readline` module. + * + * ```js + * import * as readline from 'node:readline/promises'; + * import { stdin as input, stdout as output } from 'node:process'; + * + * const rl = readline.createInterface({ input, output }); + * + * const answer = await rl.question('What do you think of Node.js? '); + * + * console.log(`Thank you for your valuable feedback: ${answer}`); + * + * rl.close(); + * ``` + * + * Once this code is invoked, the Node.js application will not terminate until the `readline.Interface` is closed because the interface waits for data to be + * received on the `input` stream. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/readline.js) + */ +declare module "readline" { + import { Abortable, EventEmitter } from "node:events"; + import * as promises from "node:readline/promises"; + export { promises }; + export interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + /** + * Instances of the `readline.Interface` class are constructed using the `readline.createInterface()` method. Every instance is associated with a + * single `input` [Readable](https://nodejs.org/docs/latest-v24.x/api/stream.html#readable-streams) stream and a single `output` [Writable](https://nodejs.org/docs/latest-v24.x/api/stream.html#writable-streams) stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + export class Interface extends EventEmitter implements Disposable { + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' '), + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0, v14.17.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output` whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * An error will be thrown if calling `rl.question()` after `rl.close()`. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including `'line'`) from being emitted by the `Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * Alias for `rl.close()`. + * @since v22.15.0 + */ + [Symbol.dispose](): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s `input` _as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + write(data: undefined | null | string | Buffer, key: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + * 8. history + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "history", listener: (history: string[]) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "history", history: string[]): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "history", listener: (history: string[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "history", listener: (history: string[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "history", listener: (history: string[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "history", listener: (history: string[]) => void): this; + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + } + export type ReadLine = Interface; // type forwarded for backwards compatibility + export type Completer = (line: string) => CompleterResult; + export type AsyncCompleter = ( + line: string, + callback: (err?: null | Error, result?: CompleterResult) => void, + ) => void; + export type CompleterResult = [string[], string]; + export interface ReadLineOptions { + /** + * The [`Readable`](https://nodejs.org/docs/latest-v24.x/api/stream.html#readable-streams) stream to listen to + */ + input: NodeJS.ReadableStream; + /** + * The [`Writable`](https://nodejs.org/docs/latest-v24.x/api/stream.html#writable-streams) stream to write readline data to. + */ + output?: NodeJS.WritableStream | undefined; + /** + * An optional function used for Tab autocompletion. + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * `true` if the `input` and `output` streams should be treated like a TTY, + * and have ANSI/VT100 escape codes written to it. + * Default: checking `isTTY` on the `output` stream upon instantiation. + */ + terminal?: boolean | undefined; + /** + * Initial list of history lines. + * This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, + * otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + /** + * Maximum number of history lines retained. + * To disable the history set this value to `0`. + * This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, + * otherwise the history caching mechanism is not initialized at all. + * @default 30 + */ + historySize?: number | undefined; + /** + * If `true`, when a new input line added to the history list duplicates an older one, + * this removes the older line from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + /** + * The prompt string to use. + * @default "> " + */ + prompt?: string | undefined; + /** + * If the delay between `\r` and `\n` exceeds `crlfDelay` milliseconds, + * both `\r` and `\n` will be treated as separate end-of-line input. + * `crlfDelay` will be coerced to a number no less than `100`. + * It can be set to `Infinity`, in which case + * `\r` followed by `\n` will always be considered a single newline + * (which may be reasonable for [reading files](https://nodejs.org/docs/latest-v24.x/api/readline.html#example-read-file-stream-line-by-line) with `\r\n` line delimiter). + * @default 100 + */ + crlfDelay?: number | undefined; + /** + * The duration `readline` will wait for a character + * (when reading an ambiguous key sequence in milliseconds + * one that can both form a complete key sequence using the input read so far + * and can take additional input to complete a longer key sequence). + * @default 500 + */ + escapeCodeTimeout?: number | undefined; + /** + * The number of spaces a tab is equal to (minimum 1). + * @default 8 + */ + tabSize?: number | undefined; + /** + * Allows closing the interface using an AbortSignal. + * Aborting the signal will internally call `close` on the interface. + */ + signal?: AbortSignal | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface` instance. + * + * ```js + * import readline from 'node:readline'; + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without + * waiting for user input, call `process.stdin.unref()`. + * @since v0.1.98 + */ + export function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + export function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the `input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * import readline from 'node:readline'; + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ', + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * import fs from 'node:fs'; + * import readline from 'node:readline'; + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity, + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * import fs from 'node:fs'; + * import readline from 'node:readline'; + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await` flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * import { once } from 'node:events'; + * import { createReadStream } from 'node:fs'; + * import { createInterface } from 'node:readline'; + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + */ + export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + export type Direction = -1 | 0 | 1; + export interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given [TTY](https://nodejs.org/docs/latest-v24.x/api/tty.html) stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given [TTY](https://nodejs.org/docs/latest-v24.x/api/tty.html) stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given [TTY](https://nodejs.org/docs/latest-v24.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given [TTY](https://nodejs.org/docs/latest-v24.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module "node:readline" { + export * from "readline"; +} diff --git a/tools/ui/node_modules/@types/node/readline/promises.d.ts b/tools/ui/node_modules/@types/node/readline/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5bc9a0c2428c06ba24d074ff452f553e3fa19922 --- /dev/null +++ b/tools/ui/node_modules/@types/node/readline/promises.d.ts @@ -0,0 +1,161 @@ +/** + * @since v17.0.0 + */ +declare module "readline/promises" { + import { Abortable } from "node:events"; + import { + CompleterResult, + Direction, + Interface as _Interface, + ReadLineOptions as _ReadLineOptions, + } from "node:readline"; + /** + * Instances of the `readlinePromises.Interface` class are constructed using the `readlinePromises.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v17.0.0 + */ + class Interface extends _Interface { + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * If the question is called after `rl.close()`, it returns a rejected promise. + * + * Example usage: + * + * ```js + * const answer = await rl.question('What is your favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * Using an `AbortSignal` to cancel a question. + * + * ```js + * const signal = AbortSignal.timeout(10_000); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * const answer = await rl.question('What is your favorite food? ', { signal }); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * @since v17.0.0 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @return A promise that is fulfilled with the user's input in response to the `query`. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + /** + * @since v17.0.0 + */ + class Readline { + /** + * @param stream A TTY stream. + */ + constructor( + stream: NodeJS.WritableStream, + options?: { + autoCommit?: boolean | undefined; + }, + ); + /** + * The `rl.clearLine()` method adds to the internal list of pending action an + * action that clears current line of the associated `stream` in a specified + * direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearLine(dir: Direction): this; + /** + * The `rl.clearScreenDown()` method adds to the internal list of pending action an + * action that clears the associated stream from the current position of the + * cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + * @since v17.0.0 + */ + commit(): Promise; + /** + * The `rl.cursorTo()` method adds to the internal list of pending action an action + * that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + cursorTo(x: number, y?: number): this; + /** + * The `rl.moveCursor()` method adds to the internal list of pending action an + * action that moves the cursor _relative_ to its current position in the + * associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback` methods clears the internal list of pending actions without + * sending it to the associated `stream`. + * @since v17.0.0 + * @return this + */ + rollback(): this; + } + type Completer = (line: string) => CompleterResult | Promise; + interface ReadLineOptions extends Omit<_ReadLineOptions, "completer"> { + /** + * An optional function used for Tab autocompletion. + */ + completer?: Completer | undefined; + } + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * + * ```js + * import readlinePromises from 'node:readline/promises'; + * const rl = readlinePromises.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readlinePromises.Interface` instance is created, the most common case + * is to listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * @since v17.0.0 + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module "node:readline/promises" { + export * from "readline/promises"; +} diff --git a/tools/ui/node_modules/@types/node/repl.d.ts b/tools/ui/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..60dc94ad78afa2da51edbbaa3b55a98567100b82 --- /dev/null +++ b/tools/ui/node_modules/@types/node/repl.d.ts @@ -0,0 +1,438 @@ +/** + * The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation + * that is available both as a standalone program or includible in other + * applications. It can be accessed using: + * + * ```js + * import repl from 'node:repl'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/repl.js) + */ +declare module "repl" { + import { AsyncCompleter, Completer, Interface } from "node:readline"; + import { Context } from "node:vm"; + import { InspectOptions } from "node:util"; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * **Default:** an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. See the [custom evaluation functions](https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#custom-evaluation-functions) + * section for more details. + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * @default the REPL instance's `terminal` value + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * @default false + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * @default false + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * @default a wrapper for `util.inspect` + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * @default false + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = ( + this: REPLServer, + evalCmd: string, + context: Context, + file: string, + cb: (err: Error | null, result: any) => void, + ) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + interface REPLServerSetupHistoryOptions { + filePath?: string | undefined; + size?: number | undefined; + removeHistoryDuplicates?: boolean | undefined; + onHistoryFileLoaded?: ((err: Error | null, repl: REPLServer) => void) | undefined; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * import repl from 'node:repl'; + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the `keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * import repl from 'node:repl'; + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * }, + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, a pipe `'|'` is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(historyPath: string, callback: (err: Error | null, repl: this) => void): void; + setupHistory( + historyConfig?: REPLServerSetupHistoryOptions, + callback?: (err: Error | null, repl: this) => void, + ): void; + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: Context): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (context: Context) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (context: Context) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * import repl from 'node:repl'; + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module "node:repl" { + export * from "repl"; +} diff --git a/tools/ui/node_modules/@types/node/sea.d.ts b/tools/ui/node_modules/@types/node/sea.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..870c30452d860de1e20283a632ecf5a4f73f5e22 --- /dev/null +++ b/tools/ui/node_modules/@types/node/sea.d.ts @@ -0,0 +1,162 @@ +/** + * This feature allows the distribution of a Node.js application conveniently to a + * system that does not have Node.js installed. + * + * Node.js supports the creation of [single executable applications](https://github.com/nodejs/single-executable) by allowing + * the injection of a blob prepared by Node.js, which can contain a bundled script, + * into the `node` binary. During start up, the program checks if anything has been + * injected. If the blob is found, it executes the script in the blob. Otherwise + * Node.js operates as it normally does. + * + * The single executable application feature currently only supports running a + * single embedded script using the `CommonJS` module system. + * + * Users can create a single executable application from their bundled script + * with the `node` binary itself and any tool which can inject resources into the + * binary. + * + * Here are the steps for creating a single executable application using one such + * tool, [postject](https://github.com/nodejs/postject): + * + * 1. Create a JavaScript file: + * ```bash + * echo 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js + * ``` + * 2. Create a configuration file building a blob that can be injected into the + * single executable application (see `Generating single executable preparation blobs` for details): + * ```bash + * echo '{ "main": "hello.js", "output": "sea-prep.blob" }' > sea-config.json + * ``` + * 3. Generate the blob to be injected: + * ```bash + * node --experimental-sea-config sea-config.json + * ``` + * 4. Create a copy of the `node` executable and name it according to your needs: + * * On systems other than Windows: + * ```bash + * cp $(command -v node) hello + * ``` + * * On Windows: + * ```text + * node -e "require('fs').copyFileSync(process.execPath, 'hello.exe')" + * ``` + * The `.exe` extension is necessary. + * 5. Remove the signature of the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --remove-signature hello + * ``` + * * On Windows (optional): + * [signtool](https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool) can be used from the installed [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/). + * If this step is + * skipped, ignore any signature-related warning from postject. + * ```powershell + * signtool remove /s hello.exe + * ``` + * 6. Inject the blob into the copied binary by running `postject` with + * the following options: + * * `hello` / `hello.exe` \- The name of the copy of the `node` executable + * created in step 4. + * * `NODE_SEA_BLOB` \- The name of the resource / note / section in the binary + * where the contents of the blob will be stored. + * * `sea-prep.blob` \- The name of the blob created in step 1. + * * `--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2` \- The [fuse](https://www.electronjs.org/docs/latest/tutorial/fuses) used by the Node.js project to detect if a file has been + * injected. + * * `--macho-segment-name NODE_SEA` (only needed on macOS) - The name of the + * segment in the binary where the contents of the blob will be + * stored. + * To summarize, here is the required command for each platform: + * * On Linux: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - PowerShell: + * ```powershell + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ` + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - Command Prompt: + * ```text + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ^ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On macOS: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \ + * --macho-segment-name NODE_SEA + * ``` + * 7. Sign the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --sign - hello + * ``` + * * On Windows (optional): + * A certificate needs to be present for this to work. However, the unsigned + * binary would still be runnable. + * ```powershell + * signtool sign /fd SHA256 hello.exe + * ``` + * 8. Run the binary: + * * On systems other than Windows + * ```console + * $ ./hello world + * Hello, world! + * ``` + * * On Windows + * ```console + * $ .\hello.exe world + * Hello, world! + * ``` + * @since v19.7.0, v18.16.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v24.x/src/node_sea.cc) + */ +declare module "node:sea" { + type AssetKey = string; + /** + * @since v20.12.0 + * @return Whether this script is running inside a single-executable application. + */ + function isSea(): boolean; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAsset(key: AssetKey): ArrayBuffer; + function getAsset(key: AssetKey, encoding: string): string; + /** + * Similar to `sea.getAsset()`, but returns the result in a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob). + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAssetAsBlob(key: AssetKey, options?: { + type: string; + }): Blob; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * + * Unlike `sea.getRawAsset()` or `sea.getAssetAsBlob()`, this method does not + * return a copy. Instead, it returns the raw asset bundled inside the executable. + * + * For now, users should avoid writing to the returned array buffer. If the + * injected section is not marked as writable or not aligned properly, + * writes to the returned array buffer is likely to result in a crash. + * @since v20.12.0 + */ + function getRawAsset(key: AssetKey): ArrayBuffer; + /** + * This method can be used to retrieve an array of all the keys of assets + * embedded into the single-executable application. + * An error is thrown when not running inside a single-executable application. + * @since v24.8.0 + * @returns An array containing all the keys of the assets + * embedded in the executable. If no assets are embedded, returns an empty array. + */ + function getAssetKeys(): string[]; +} diff --git a/tools/ui/node_modules/@types/node/sqlite.d.ts b/tools/ui/node_modules/@types/node/sqlite.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..43112d4164aca1bcedf1b9d5ca3dc209fbcdbe29 --- /dev/null +++ b/tools/ui/node_modules/@types/node/sqlite.d.ts @@ -0,0 +1,1040 @@ +/** + * The `node:sqlite` module facilitates working with SQLite databases. + * To access it: + * + * ```js + * import sqlite from 'node:sqlite'; + * ``` + * + * This module is only available under the `node:` scheme. + * + * The following example shows the basic usage of the `node:sqlite` module to open + * an in-memory database, write data to the database, and then read the data back. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * const database = new DatabaseSync(':memory:'); + * + * // Execute SQL statements from strings. + * database.exec(` + * CREATE TABLE data( + * key INTEGER PRIMARY KEY, + * value TEXT + * ) STRICT + * `); + * // Create a prepared statement to insert data into the database. + * const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); + * // Execute the prepared statement with bound values. + * insert.run(1, 'hello'); + * insert.run(2, 'world'); + * // Create a prepared statement to read data from the database. + * const query = database.prepare('SELECT * FROM data ORDER BY key'); + * // Execute the prepared statement and log the result set. + * console.log(query.all()); + * // Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ] + * ``` + * @since v22.5.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/sqlite.js) + */ +declare module "node:sqlite" { + import { PathLike } from "node:fs"; + type SQLInputValue = null | number | bigint | string | NodeJS.ArrayBufferView; + type SQLOutputValue = null | number | bigint | string | NodeJS.NonSharedUint8Array; + interface DatabaseSyncOptions { + /** + * If `true`, the database is opened by the constructor. When + * this value is `false`, the database must be opened via the `open()` method. + * @since v22.5.0 + * @default true + */ + open?: boolean | undefined; + /** + * If `true`, foreign key constraints + * are enabled. This is recommended but can be disabled for compatibility with + * legacy database schemas. The enforcement of foreign key constraints can be + * enabled and disabled after opening the database using + * [`PRAGMA foreign_keys`](https://www.sqlite.org/pragma.html#pragma_foreign_keys). + * @since v22.10.0 + * @default true + */ + enableForeignKeyConstraints?: boolean | undefined; + /** + * If `true`, SQLite will accept + * [double-quoted string literals](https://www.sqlite.org/quirks.html#dblquote). + * This is not recommended but can be + * enabled for compatibility with legacy database schemas. + * @since v22.10.0 + * @default false + */ + enableDoubleQuotedStringLiterals?: boolean | undefined; + /** + * If `true`, the database is opened in read-only mode. + * If the database does not exist, opening it will fail. + * @since v22.12.0 + * @default false + */ + readOnly?: boolean | undefined; + /** + * If `true`, the `loadExtension` SQL function + * and the `loadExtension()` method are enabled. + * You can call `enableLoadExtension(false)` later to disable this feature. + * @since v22.13.0 + * @default false + */ + allowExtension?: boolean | undefined; + /** + * The [busy timeout](https://sqlite.org/c3ref/busy_timeout.html) in milliseconds. This is the maximum amount of + * time that SQLite will wait for a database lock to be released before + * returning an error. + * @since v24.0.0 + * @default 0 + */ + timeout?: number | undefined; + /** + * If `true`, integer fields are read as JavaScript `BigInt` values. If `false`, + * integer fields are read as JavaScript numbers. + * @since v24.4.0 + * @default false + */ + readBigInts?: boolean | undefined; + /** + * If `true`, query results are returned as arrays instead of objects. + * @since v24.4.0 + * @default false + */ + returnArrays?: boolean | undefined; + /** + * If `true`, allows binding named parameters without the prefix + * character (e.g., `foo` instead of `:foo`). + * @since v24.4.40 + * @default true + */ + allowBareNamedParameters?: boolean | undefined; + /** + * If `true`, unknown named parameters are ignored when binding. + * If `false`, an exception is thrown for unknown named parameters. + * @since v24.4.40 + * @default false + */ + allowUnknownNamedParameters?: boolean | undefined; + /** + * If `true`, enables the defensive flag. When the defensive flag is enabled, + * language features that allow ordinary SQL to deliberately corrupt the database + * file are disabled. The defensive flag can also be set using `enableDefensive()`. + * @since v24.12.0 + * @default true + */ + defensive?: boolean | undefined; + } + interface CreateSessionOptions { + /** + * A specific table to track changes for. By default, changes to all tables are tracked. + * @since v22.12.0 + */ + table?: string | undefined; + /** + * Name of the database to track. This is useful when multiple databases have been added using + * [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html). + * @since v22.12.0 + * @default 'main' + */ + db?: string | undefined; + } + interface ApplyChangesetOptions { + /** + * Skip changes that, when targeted table name is supplied to this function, return a truthy value. + * By default, all changes are attempted. + * @since v22.12.0 + */ + filter?: ((tableName: string) => boolean) | undefined; + /** + * A function that determines how to handle conflicts. The function receives one argument, + * which can be one of the following values: + * + * * `SQLITE_CHANGESET_DATA`: A `DELETE` or `UPDATE` change does not contain the expected "before" values. + * * `SQLITE_CHANGESET_NOTFOUND`: A row matching the primary key of the `DELETE` or `UPDATE` change does not exist. + * * `SQLITE_CHANGESET_CONFLICT`: An `INSERT` change results in a duplicate primary key. + * * `SQLITE_CHANGESET_FOREIGN_KEY`: Applying a change would result in a foreign key violation. + * * `SQLITE_CHANGESET_CONSTRAINT`: Applying a change results in a `UNIQUE`, `CHECK`, or `NOT NULL` constraint + * violation. + * + * The function should return one of the following values: + * + * * `SQLITE_CHANGESET_OMIT`: Omit conflicting changes. + * * `SQLITE_CHANGESET_REPLACE`: Replace existing values with conflicting changes (only valid with + `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT` conflicts). + * * `SQLITE_CHANGESET_ABORT`: Abort on conflict and roll back the database. + * + * When an error is thrown in the conflict handler or when any other value is returned from the handler, + * applying the changeset is aborted and the database is rolled back. + * + * **Default**: A function that returns `SQLITE_CHANGESET_ABORT`. + * @since v22.12.0 + */ + onConflict?: ((conflictType: number) => number) | undefined; + } + interface FunctionOptions { + /** + * If `true`, the [`SQLITE_DETERMINISTIC`](https://www.sqlite.org/c3ref/c_deterministic.html) flag is + * set on the created function. + * @default false + */ + deterministic?: boolean | undefined; + /** + * If `true`, the [`SQLITE_DIRECTONLY`](https://www.sqlite.org/c3ref/c_directonly.html) flag is set on + * the created function. + * @default false + */ + directOnly?: boolean | undefined; + /** + * If `true`, integer arguments to `function` + * are converted to `BigInt`s. If `false`, integer arguments are passed as + * JavaScript numbers. + * @default false + */ + useBigIntArguments?: boolean | undefined; + /** + * If `true`, `function` may be invoked with any number of + * arguments (between zero and + * [`SQLITE_MAX_FUNCTION_ARG`](https://www.sqlite.org/limits.html#max_function_arg)). If `false`, + * `function` must be invoked with exactly `function.length` arguments. + * @default false + */ + varargs?: boolean | undefined; + } + interface AggregateOptions extends FunctionOptions { + /** + * The identity value for the aggregation function. This value is used when the aggregation + * function is initialized. When a `Function` is passed the identity will be its return value. + */ + start: T | (() => T); + /** + * The function to call for each row in the aggregation. The + * function receives the current state and the row value. The return value of + * this function should be the new state. + */ + step: (accumulator: T, ...args: SQLOutputValue[]) => T; + /** + * The function to call to get the result of the + * aggregation. The function receives the final state and should return the + * result of the aggregation. + */ + result?: ((accumulator: T) => SQLInputValue) | undefined; + /** + * When this function is provided, the `aggregate` method will work as a window function. + * The function receives the current state and the dropped row value. The return value of this function should be the + * new state. + */ + inverse?: ((accumulator: T, ...args: SQLOutputValue[]) => T) | undefined; + } + /** + * This class represents a single [connection](https://www.sqlite.org/c3ref/sqlite3.html) to a SQLite database. All APIs + * exposed by this class execute synchronously. + * @since v22.5.0 + */ + class DatabaseSync implements Disposable { + /** + * Constructs a new `DatabaseSync` instance. + * @param path The path of the database. + * A SQLite database can be stored in a file or completely [in memory](https://www.sqlite.org/inmemorydb.html). + * To use a file-backed database, the path should be a file path. + * To use an in-memory database, the path should be the special name `':memory:'`. + * @param options Configuration options for the database connection. + */ + constructor(path: PathLike, options?: DatabaseSyncOptions); + /** + * Registers a new aggregate function with the SQLite database. This method is a wrapper around + * [`sqlite3_create_window_function()`](https://www.sqlite.org/c3ref/create_function.html). + * + * When used as a window function, the `result` function will be called multiple times. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * + * const db = new DatabaseSync(':memory:'); + * db.exec(` + * CREATE TABLE t3(x, y); + * INSERT INTO t3 VALUES ('a', 4), + * ('b', 5), + * ('c', 3), + * ('d', 8), + * ('e', 1); + * `); + * + * db.aggregate('sumint', { + * start: 0, + * step: (acc, value) => acc + value, + * }); + * + * db.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 } + * ``` + * @since v24.0.0 + * @param name The name of the SQLite function to create. + * @param options Function configuration settings. + */ + aggregate(name: string, options: AggregateOptions): void; + aggregate(name: string, options: AggregateOptions): void; + /** + * Closes the database connection. An exception is thrown if the database is not + * open. This method is a wrapper around [`sqlite3_close_v2()`](https://www.sqlite.org/c3ref/close.html). + * @since v22.5.0 + */ + close(): void; + /** + * Loads a shared library into the database connection. This method is a wrapper + * around [`sqlite3_load_extension()`](https://www.sqlite.org/c3ref/load_extension.html). It is required to enable the + * `allowExtension` option when constructing the `DatabaseSync` instance. + * @since v22.13.0 + * @param path The path to the shared library to load. + */ + loadExtension(path: string): void; + /** + * Enables or disables the `loadExtension` SQL function, and the `loadExtension()` + * method. When `allowExtension` is `false` when constructing, you cannot enable + * loading extensions for security reasons. + * @since v22.13.0 + * @param allow Whether to allow loading extensions. + */ + enableLoadExtension(allow: boolean): void; + /** + * Enables or disables the defensive flag. When the defensive flag is active, + * language features that allow ordinary SQL to deliberately corrupt the + * database file are disabled. + * See [`SQLITE_DBCONFIG_DEFENSIVE`](https://www.sqlite.org/c3ref/c_dbconfig_defensive.html#sqlitedbconfigdefensive) + * in the SQLite documentation for details. + * @since v24.12.0 + * @param active Whether to set the defensive flag. + */ + enableDefensive(active: boolean): void; + /** + * This method is a wrapper around [`sqlite3_db_filename()`](https://sqlite.org/c3ref/db_filename.html) + * @since v24.0.0 + * @param dbName Name of the database. This can be `'main'` (the default primary database) or any other + * database that has been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) **Default:** `'main'`. + * @returns The location of the database file. When using an in-memory database, + * this method returns null. + */ + location(dbName?: string): string | null; + /** + * This method allows one or more SQL statements to be executed without returning + * any results. This method is useful when executing SQL statements read from a + * file. This method is a wrapper around [`sqlite3_exec()`](https://www.sqlite.org/c3ref/exec.html). + * @since v22.5.0 + * @param sql A SQL string to execute. + */ + exec(sql: string): void; + /** + * This method is used to create SQLite user-defined functions. This method is a + * wrapper around [`sqlite3_create_function_v2()`](https://www.sqlite.org/c3ref/create_function.html). + * @since v22.13.0 + * @param name The name of the SQLite function to create. + * @param options Optional configuration settings for the function. + * @param func The JavaScript function to call when the SQLite + * function is invoked. The return value of this function should be a valid + * SQLite data type: see + * [Type conversion between JavaScript and SQLite](https://nodejs.org/docs/latest-v24.x/api/sqlite.html#type-conversion-between-javascript-and-sqlite). + * The result defaults to `NULL` if the return value is `undefined`. + */ + function( + name: string, + options: FunctionOptions, + func: (...args: SQLOutputValue[]) => SQLInputValue, + ): void; + function(name: string, func: (...args: SQLOutputValue[]) => SQLInputValue): void; + /** + * Sets an authorizer callback that SQLite will invoke whenever it attempts to + * access data or modify the database schema through prepared statements. + * This can be used to implement security policies, audit access, or restrict certain operations. + * This method is a wrapper around [`sqlite3_set_authorizer()`](https://sqlite.org/c3ref/set_authorizer.html). + * + * When invoked, the callback receives five arguments: + * + * * `actionCode` {number} The type of operation being performed (e.g., + * `SQLITE_INSERT`, `SQLITE_UPDATE`, `SQLITE_SELECT`). + * * `arg1` {string|null} The first argument (context-dependent, often a table name). + * * `arg2` {string|null} The second argument (context-dependent, often a column name). + * * `dbName` {string|null} The name of the database. + * * `triggerOrView` {string|null} The name of the trigger or view causing the access. + * + * The callback must return one of the following constants: + * + * * `SQLITE_OK` - Allow the operation. + * * `SQLITE_DENY` - Deny the operation (causes an error). + * * `SQLITE_IGNORE` - Ignore the operation (silently skip). + * + * ```js + * import { DatabaseSync, constants } from 'node:sqlite'; + * const db = new DatabaseSync(':memory:'); + * + * // Set up an authorizer that denies all table creation + * db.setAuthorizer((actionCode) => { + * if (actionCode === constants.SQLITE_CREATE_TABLE) { + * return constants.SQLITE_DENY; + * } + * return constants.SQLITE_OK; + * }); + * + * // This will work + * db.prepare('SELECT 1').get(); + * + * // This will throw an error due to authorization denial + * try { + * db.exec('CREATE TABLE blocked (id INTEGER)'); + * } catch (err) { + * console.log('Operation blocked:', err.message); + * } + * ``` + * @since v24.10.0 + * @param callback The authorizer function to set, or `null` to + * clear the current authorizer. + */ + setAuthorizer( + callback: + | (( + actionCode: number, + arg1: string | null, + arg2: string | null, + dbName: string | null, + triggerOrView: string | null, + ) => number) + | null, + ): void; + /** + * Whether the database is currently open or not. + * @since v22.15.0 + */ + readonly isOpen: boolean; + /** + * Whether the database is currently within a transaction. This method + * is a wrapper around [`sqlite3_get_autocommit()`](https://sqlite.org/c3ref/get_autocommit.html). + * @since v24.0.0 + */ + readonly isTransaction: boolean; + /** + * Opens the database specified in the `path` argument of the `DatabaseSync`constructor. This method should only be used when the database is not opened via + * the constructor. An exception is thrown if the database is already open. + * @since v22.5.0 + */ + open(): void; + /** + * Compiles a SQL statement into a [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This method is a wrapper + * around [`sqlite3_prepare_v2()`](https://www.sqlite.org/c3ref/prepare.html). + * @since v22.5.0 + * @param sql A SQL string to compile to a prepared statement. + * @return The prepared statement. + */ + prepare(sql: string): StatementSync; + /** + * Creates a new {@link SQLTagStore}, which is a Least Recently Used (LRU) cache + * for storing prepared statements. This allows for the efficient reuse of + * prepared statements by tagging them with a unique identifier. + * + * When a tagged SQL literal is executed, the `SQLTagStore` checks if a prepared + * statement for the corresponding SQL query string already exists in the cache. + * If it does, the cached statement is used. If not, a new prepared statement is + * created, executed, and then stored in the cache for future use. This mechanism + * helps to avoid the overhead of repeatedly parsing and preparing the same SQL + * statements. + * + * Tagged statements bind the placeholder values from the template literal as + * parameters to the underlying prepared statement. For example: + * + * ```js + * sqlTagStore.get`SELECT ${value}`; + * ``` + * + * is equivalent to: + * + * ```js + * db.prepare('SELECT ?').get(value); + * ``` + * + * However, in the first example, the tag store will cache the underlying prepared + * statement for future use. + * + * > **Note:** The `${value}` syntax in tagged statements _binds_ a parameter to + * > the prepared statement. This differs from its behavior in _untagged_ template + * > literals, where it performs string interpolation. + * > + * > ```js + * > // This a safe example of binding a parameter to a tagged statement. + * > sqlTagStore.run`INSERT INTO t1 (id) VALUES (${id})`; + * > + * > // This is an *unsafe* example of an untagged template string. + * > // `id` is interpolated into the query text as a string. + * > // This can lead to SQL injection and data corruption. + * > db.run(`INSERT INTO t1 (id) VALUES (${id})`); + * > ``` + * + * The tag store will match a statement from the cache if the query strings + * (including the positions of any bound placeholders) are identical. + * + * ```js + * // The following statements will match in the cache: + * sqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`; + * sqlTagStore.get`SELECT * FROM t1 WHERE id = ${12345} AND active = 1`; + * + * // The following statements will not match, as the query strings + * // and bound placeholders differ: + * sqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`; + * sqlTagStore.get`SELECT * FROM t1 WHERE id = 12345 AND active = 1`; + * + * // The following statements will not match, as matches are case-sensitive: + * sqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`; + * sqlTagStore.get`select * from t1 where id = ${id} and active = 1`; + * ``` + * + * The only way of binding parameters in tagged statements is with the `${value}` + * syntax. Do not add parameter binding placeholders (`?` etc.) to the SQL query + * string itself. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * + * const db = new DatabaseSync(':memory:'); + * const sql = db.createTagStore(); + * + * db.exec('CREATE TABLE users (id INT, name TEXT)'); + * + * // Using the 'run' method to insert data. + * // The tagged literal is used to identify the prepared statement. + * sql.run`INSERT INTO users VALUES (1, 'Alice')`; + * sql.run`INSERT INTO users VALUES (2, 'Bob')`; + * + * // Using the 'get' method to retrieve a single row. + * const name = 'Alice'; + * const user = sql.get`SELECT * FROM users WHERE name = ${name}`; + * console.log(user); // { id: 1, name: 'Alice' } + * + * // Using the 'all' method to retrieve all rows. + * const allUsers = sql.all`SELECT * FROM users ORDER BY id`; + * console.log(allUsers); + * // [ + * // { id: 1, name: 'Alice' }, + * // { id: 2, name: 'Bob' } + * // ] + * ``` + * @since v24.9.0 + * @param maxSize The maximum number of prepared statements to cache. **Default**: `1000`. + * @returns A new SQL tag store for caching prepared statements. + */ + createTagStore(maxSize?: number): SQLTagStore; + /** + * Creates and attaches a session to the database. This method is a wrapper around + * [`sqlite3session_create()`](https://www.sqlite.org/session/sqlite3session_create.html) and + * [`sqlite3session_attach()`](https://www.sqlite.org/session/sqlite3session_attach.html). + * @param options The configuration options for the session. + * @returns A session handle. + * @since v22.12.0 + */ + createSession(options?: CreateSessionOptions): Session; + /** + * An exception is thrown if the database is not + * open. This method is a wrapper around + * [`sqlite3changeset_apply()`](https://www.sqlite.org/session/sqlite3changeset_apply.html). + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * + * const sourceDb = new DatabaseSync(':memory:'); + * const targetDb = new DatabaseSync(':memory:'); + * + * sourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)'); + * targetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)'); + * + * const session = sourceDb.createSession(); + * + * const insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); + * insert.run(1, 'hello'); + * insert.run(2, 'world'); + * + * const changeset = session.changeset(); + * targetDb.applyChangeset(changeset); + * // Now that the changeset has been applied, targetDb contains the same data as sourceDb. + * ``` + * @param changeset A binary changeset or patchset. + * @param options The configuration options for how the changes will be applied. + * @returns Whether the changeset was applied successfully without being aborted. + * @since v22.12.0 + */ + applyChangeset(changeset: Uint8Array, options?: ApplyChangesetOptions): boolean; + /** + * Closes the database connection. If the database connection is already closed + * then this is a no-op. + * @since v22.15.0 + */ + [Symbol.dispose](): void; + } + /** + * @since v22.12.0 + */ + interface Session { + /** + * Retrieves a changeset containing all changes since the changeset was created. Can be called multiple times. + * An exception is thrown if the database or the session is not open. This method is a wrapper around + * [`sqlite3session_changeset()`](https://www.sqlite.org/session/sqlite3session_changeset.html). + * @returns Binary changeset that can be applied to other databases. + * @since v22.12.0 + */ + changeset(): NodeJS.NonSharedUint8Array; + /** + * Similar to the method above, but generates a more compact patchset. See + * [Changesets and Patchsets](https://www.sqlite.org/sessionintro.html#changesets_and_patchsets) + * in the documentation of SQLite. An exception is thrown if the database or the session is not open. This method is a + * wrapper around + * [`sqlite3session_patchset()`](https://www.sqlite.org/session/sqlite3session_patchset.html). + * @returns Binary patchset that can be applied to other databases. + * @since v22.12.0 + */ + patchset(): NodeJS.NonSharedUint8Array; + /** + * Closes the session. An exception is thrown if the database or the session is not open. This method is a + * wrapper around + * [`sqlite3session_delete()`](https://www.sqlite.org/session/sqlite3session_delete.html). + */ + close(): void; + /** + * Closes the session. If the session is already closed, does nothing. + * @since v24.9.0 + */ + [Symbol.dispose](): void; + } + /** + * This class represents a single LRU (Least Recently Used) cache for storing + * prepared statements. + * + * Instances of this class are created via the `database.createTagStore()` + * method, not by using a constructor. The store caches prepared statements based + * on the provided SQL query string. When the same query is seen again, the store + * retrieves the cached statement and safely applies the new values through + * parameter binding, thereby preventing attacks like SQL injection. + * + * The cache has a maxSize that defaults to 1000 statements, but a custom size can + * be provided (e.g., `database.createTagStore(100)`). All APIs exposed by this + * class execute synchronously. + * @since v24.9.0 + */ + interface SQLTagStore { + /** + * Executes the given SQL query and returns all resulting rows as an array of + * objects. + * + * This function is intended to be used as a template literal tag, not to be + * called directly. + * @since v24.9.0 + * @param stringElements Template literal elements containing the SQL + * query. + * @param boundParameters Parameter values to be bound to placeholders in the template string. + * @returns An array of objects representing the rows returned by the query. + */ + all( + stringElements: TemplateStringsArray, + ...boundParameters: SQLInputValue[] + ): Record[]; + /** + * Executes the given SQL query and returns the first resulting row as an object. + * + * This function is intended to be used as a template literal tag, not to be + * called directly. + * @since v24.9.0 + * @param stringElements Template literal elements containing the SQL + * query. + * @param boundParameters Parameter values to be bound to placeholders in the template string. + * @returns An object representing the first row returned by + * the query, or `undefined` if no rows are returned. + */ + get( + stringElements: TemplateStringsArray, + ...boundParameters: SQLInputValue[] + ): Record | undefined; + /** + * Executes the given SQL query and returns an iterator over the resulting rows. + * + * This function is intended to be used as a template literal tag, not to be + * called directly. + * @since v24.9.0 + * @param stringElements Template literal elements containing the SQL + * query. + * @param boundParameters Parameter values to be bound to placeholders in the template string. + * @returns An iterator that yields objects representing the rows returned by the query. + */ + iterate( + stringElements: TemplateStringsArray, + ...boundParameters: SQLInputValue[] + ): NodeJS.Iterator>; + /** + * Executes the given SQL query, which is expected to not return any rows (e.g., INSERT, UPDATE, DELETE). + * + * This function is intended to be used as a template literal tag, not to be + * called directly. + * @since v24.9.0 + * @param stringElements Template literal elements containing the SQL + * query. + * @param boundParameters Parameter values to be bound to placeholders in the template string. + * @returns An object containing information about the execution, including `changes` and `lastInsertRowid`. + */ + run(stringElements: TemplateStringsArray, ...boundParameters: SQLInputValue[]): StatementResultingChanges; + /** + * A read-only property that returns the number of prepared statements currently in the cache. + * @since v24.9.0 + */ + readonly size: number; + /** + * A read-only property that returns the maximum number of prepared statements the cache can hold. + * @since v24.9.0 + */ + readonly capacity: number; + /** + * A read-only property that returns the `DatabaseSync` object associated with this `SQLTagStore`. + * @since v24.9.0 + */ + readonly db: DatabaseSync; + /** + * Resets the LRU cache, clearing all stored prepared statements. + * @since v24.9.0 + */ + clear(): void; + } + interface StatementColumnMetadata { + /** + * The unaliased name of the column in the origin + * table, or `null` if the column is the result of an expression or subquery. + * This property is the result of [`sqlite3_column_origin_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + column: string | null; + /** + * The unaliased name of the origin database, or + * `null` if the column is the result of an expression or subquery. This + * property is the result of [`sqlite3_column_database_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + database: string | null; + /** + * The name assigned to the column in the result set of a + * `SELECT` statement. This property is the result of + * [`sqlite3_column_name()`](https://www.sqlite.org/c3ref/column_name.html). + */ + name: string; + /** + * The unaliased name of the origin table, or `null` if + * the column is the result of an expression or subquery. This property is the + * result of [`sqlite3_column_table_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + table: string | null; + /** + * The declared data type of the column, or `null` if the + * column is the result of an expression or subquery. This property is the + * result of [`sqlite3_column_decltype()`](https://www.sqlite.org/c3ref/column_decltype.html). + */ + type: string | null; + } + interface StatementResultingChanges { + /** + * The number of rows modified, inserted, or deleted by the most recently completed `INSERT`, `UPDATE`, or `DELETE` statement. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_changes64()`](https://www.sqlite.org/c3ref/changes.html). + */ + changes: number | bigint; + /** + * The most recently inserted rowid. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_last_insert_rowid()`](https://www.sqlite.org/c3ref/last_insert_rowid.html). + */ + lastInsertRowid: number | bigint; + } + /** + * This class represents a single [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This class cannot be + * instantiated via its constructor. Instead, instances are created via the`database.prepare()` method. All APIs exposed by this class execute + * synchronously. + * + * A prepared statement is an efficient binary representation of the SQL used to + * create it. Prepared statements are parameterizable, and can be invoked multiple + * times with different bound values. Parameters also offer protection against [SQL injection](https://en.wikipedia.org/wiki/SQL_injection) attacks. For these reasons, prepared statements are + * preferred + * over hand-crafted SQL strings when handling user input. + * @since v22.5.0 + */ + class StatementSync { + private constructor(); + /** + * This method executes a prepared statement and returns all results as an array of + * objects. If the prepared statement does not return any results, this method + * returns an empty array. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An array of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of + * the row. + */ + all(...anonymousParameters: SQLInputValue[]): Record[]; + all( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): Record[]; + /** + * This method is used to retrieve information about the columns returned by the + * prepared statement. + * @since v23.11.0 + * @returns An array of objects. Each object corresponds to a column + * in the prepared statement, and contains the following properties: + */ + columns(): StatementColumnMetadata[]; + /** + * The source SQL text of the prepared statement with parameter + * placeholders replaced by the values that were used during the most recent + * execution of this prepared statement. This property is a wrapper around + * [`sqlite3_expanded_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + */ + readonly expandedSQL: string; + /** + * This method executes a prepared statement and returns the first result as an + * object. If the prepared statement does not return any results, this method + * returns `undefined`. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An object corresponding to the first row returned by executing the prepared statement. The keys and values of the object correspond to the column names and values of the row. If no + * rows were returned from the database then this method returns `undefined`. + */ + get(...anonymousParameters: SQLInputValue[]): Record | undefined; + get( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): Record | undefined; + /** + * This method executes a prepared statement and returns an iterator of + * objects. If the prepared statement does not return any results, this method + * returns an empty iterator. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.13.0 + * @param namedParameters An optional object used to bind named parameters. + * The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @returns An iterable iterator of objects. Each object corresponds to a row + * returned by executing the prepared statement. The keys and values of each + * object correspond to the column names and values of the row. + */ + iterate(...anonymousParameters: SQLInputValue[]): NodeJS.Iterator>; + iterate( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): NodeJS.Iterator>; + /** + * This method executes a prepared statement and returns an object summarizing the + * resulting changes. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + */ + run(...anonymousParameters: SQLInputValue[]): StatementResultingChanges; + run( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): StatementResultingChanges; + /** + * The names of SQLite parameters begin with a prefix character. By default,`node:sqlite` requires that this prefix character is present when binding + * parameters. However, with the exception of dollar sign character, these + * prefix characters also require extra quoting when used in object keys. + * + * To improve ergonomics, this method can be used to also allow bare named + * parameters, which do not require the prefix character in JavaScript code. There + * are several caveats to be aware of when enabling bare named parameters: + * + * * The prefix character is still required in SQL. + * * The prefix character is still allowed in JavaScript. In fact, prefixed names + * will have slightly better binding performance. + * * Using ambiguous named parameters, such as `$k` and `@k`, in the same prepared + * statement will result in an exception as it cannot be determined how to bind + * a bare name. + * @since v22.5.0 + * @param enabled Enables or disables support for binding named parameters without the prefix character. + */ + setAllowBareNamedParameters(enabled: boolean): void; + /** + * By default, if an unknown name is encountered while binding parameters, an + * exception is thrown. This method allows unknown named parameters to be ignored. + * @since v22.15.0 + * @param enabled Enables or disables support for unknown named parameters. + */ + setAllowUnknownNamedParameters(enabled: boolean): void; + /** + * When enabled, query results returned by the `all()`, `get()`, and `iterate()` methods will be returned as arrays instead + * of objects. + * @since v24.0.0 + * @param enabled Enables or disables the return of query results as arrays. + */ + setReturnArrays(enabled: boolean): void; + /** + * When reading from the database, SQLite `INTEGER`s are mapped to JavaScript + * numbers by default. However, SQLite `INTEGER`s can store values larger than + * JavaScript numbers are capable of representing. In such cases, this method can + * be used to read `INTEGER` data using JavaScript `BigInt`s. This method has no + * impact on database write operations where numbers and `BigInt`s are both + * supported at all times. + * @since v22.5.0 + * @param enabled Enables or disables the use of `BigInt`s when reading `INTEGER` fields from the database. + */ + setReadBigInts(enabled: boolean): void; + /** + * The source SQL text of the prepared statement. This property is a + * wrapper around [`sqlite3_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + */ + readonly sourceSQL: string; + } + interface BackupOptions { + /** + * Name of the source database. This can be `'main'` (the default primary database) or any other + * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) + * @default 'main' + */ + source?: string | undefined; + /** + * Name of the target database. This can be `'main'` (the default primary database) or any other + * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) + * @default 'main' + */ + target?: string | undefined; + /** + * Number of pages to be transmitted in each batch of the backup. + * @default 100 + */ + rate?: number | undefined; + /** + * An optional callback function that will be called after each backup step. The argument passed + * to this callback is an `Object` with `remainingPages` and `totalPages` properties, describing the current progress + * of the backup operation. + */ + progress?: ((progressInfo: BackupProgressInfo) => void) | undefined; + } + interface BackupProgressInfo { + totalPages: number; + remainingPages: number; + } + /** + * This method makes a database backup. This method abstracts the + * [`sqlite3_backup_init()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupinit), + * [`sqlite3_backup_step()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupstep) + * and [`sqlite3_backup_finish()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupfinish) functions. + * + * The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same + * `DatabaseSync` - object will be reflected in the backup right away. However, mutations from other connections will cause + * the backup process to restart. + * + * ```js + * import { backup, DatabaseSync } from 'node:sqlite'; + * + * const sourceDb = new DatabaseSync('source.db'); + * const totalPagesTransferred = await backup(sourceDb, 'backup.db', { + * rate: 1, // Copy one page at a time. + * progress: ({ totalPages, remainingPages }) => { + * console.log('Backup in progress', { totalPages, remainingPages }); + * }, + * }); + * + * console.log('Backup completed', totalPagesTransferred); + * ``` + * @since v23.8.0 + * @param sourceDb The database to backup. The source database must be open. + * @param path The path where the backup will be created. If the file already exists, + * the contents will be overwritten. + * @param options Optional configuration for the backup. The + * following properties are supported: + * @returns A promise that fulfills with the total number of backed-up pages upon completion, or rejects if an + * error occurs. + */ + function backup(sourceDb: DatabaseSync, path: PathLike, options?: BackupOptions): Promise; + /** + * @since v22.13.0 + */ + namespace constants { + /** + * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is present in the database, but one or more other (non primary-key) fields modified by the update do not contain the expected "before" values. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_DATA: number; + /** + * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is not present in the database. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_NOTFOUND: number; + /** + * This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_CONFLICT: number; + /** + * If foreign key handling is enabled, and applying a changeset leaves the database in a state containing foreign key violations, the conflict handler is invoked with this constant exactly once before the changeset is committed. If the conflict handler returns `SQLITE_CHANGESET_OMIT`, the changes, including those that caused the foreign key constraint violation, are committed. Or, if it returns `SQLITE_CHANGESET_ABORT`, the changeset is rolled back. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_FOREIGN_KEY: number; + /** + * Conflicting changes are omitted. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_OMIT: number; + /** + * Conflicting changes replace existing values. Note that this value can only be returned when the type of conflict is either `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT`. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_REPLACE: number; + /** + * Abort when a change encounters a conflict and roll back database. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_ABORT: number; + /** + * Deny the operation and cause an error to be returned. + * @since v24.10.0 + */ + const SQLITE_DENY: number; + /** + * Ignore the operation and continue as if it had never been requested. + * @since 24.10.0 + */ + const SQLITE_IGNORE: number; + /** + * Allow the operation to proceed normally. + * @since v24.10.0 + */ + const SQLITE_OK: number; + const SQLITE_CREATE_INDEX: number; + const SQLITE_CREATE_TABLE: number; + const SQLITE_CREATE_TEMP_INDEX: number; + const SQLITE_CREATE_TEMP_TABLE: number; + const SQLITE_CREATE_TEMP_TRIGGER: number; + const SQLITE_CREATE_TEMP_VIEW: number; + const SQLITE_CREATE_TRIGGER: number; + const SQLITE_CREATE_VIEW: number; + const SQLITE_DELETE: number; + const SQLITE_DROP_INDEX: number; + const SQLITE_DROP_TABLE: number; + const SQLITE_DROP_TEMP_INDEX: number; + const SQLITE_DROP_TEMP_TABLE: number; + const SQLITE_DROP_TEMP_TRIGGER: number; + const SQLITE_DROP_TEMP_VIEW: number; + const SQLITE_DROP_TRIGGER: number; + const SQLITE_DROP_VIEW: number; + const SQLITE_INSERT: number; + const SQLITE_PRAGMA: number; + const SQLITE_READ: number; + const SQLITE_SELECT: number; + const SQLITE_TRANSACTION: number; + const SQLITE_UPDATE: number; + const SQLITE_ATTACH: number; + const SQLITE_DETACH: number; + const SQLITE_ALTER_TABLE: number; + const SQLITE_REINDEX: number; + const SQLITE_ANALYZE: number; + const SQLITE_CREATE_VTABLE: number; + const SQLITE_DROP_VTABLE: number; + const SQLITE_FUNCTION: number; + const SQLITE_SAVEPOINT: number; + const SQLITE_COPY: number; + const SQLITE_RECURSIVE: number; + } +} diff --git a/tools/ui/node_modules/@types/node/stream.d.ts b/tools/ui/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0aec9a2ae97ba4f5d2d88315f6d21c4c1ee26382 --- /dev/null +++ b/tools/ui/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1706 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `node:stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a [request to an HTTP server](https://nodejs.org/docs/latest-v24.x/api/http.html#class-httpincomingmessage) + * and [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of [`EventEmitter`](https://nodejs.org/docs/latest-v24.x/api/events.html#class-eventemitter). + * + * To access the `node:stream` module: + * + * ```js + * import stream from 'node:stream'; + * ``` + * + * The `node:stream` module is useful for creating new types of stream instances. + * It is usually not necessary to use the `node:stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/stream.js) + */ +declare module "stream" { + import { Abortable, EventEmitter } from "node:events"; + import { Blob as NodeBlob } from "node:buffer"; + import * as streamPromises from "node:stream/promises"; + import * as streamWeb from "node:stream/web"; + + type ComposeFnParam = (source: any) => void; + + class Stream extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + }, + ): T; + compose( + stream: T | ComposeFnParam | Iterable | AsyncIterable, + options?: { signal: AbortSignal }, + ): T; + } + namespace Stream { + export { Stream, streamPromises as promises }; + } + namespace Stream { + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?: ((this: T, callback: (error?: Error | null) => void) => void) | undefined; + destroy?: ((this: T, error: Error | null, callback: (error?: Error | null) => void) => void) | undefined; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?: ((this: T, size: number) => void) | undefined; + } + interface ArrayOptions { + /** + * The maximum concurrent invocations of `fn` to call on the stream at once. + * @default 1 + */ + concurrency?: number | undefined; + /** Allows destroying the stream if the signal is aborted. */ + signal?: AbortSignal | undefined; + } + /** + * @since v0.9.4 + */ + class Readable extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + * @since v12.3.0, v10.17.0 + * @param iterable Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed. + * @param options Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + */ + static fromWeb( + readableStream: streamWeb.ReadableStream, + options?: Pick, + ): Readable; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + */ + static toWeb( + streamReadable: Readable, + options?: { + strategy?: streamWeb.QueuingStrategy | undefined; + }, + ): streamWeb.ReadableStream; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call {@link read}, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0, v14.18.0 + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding` property can be set using the {@link setEncoding} method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when [`'end'`](https://nodejs.org/docs/latest-v24.x/api/stream.html#event-end) event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the [Three states](https://nodejs.org/docs/latest-v24.x/api/stream.html#three-states) section. + * @since v9.4.0 + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method reads data out of the internal buffer and + * returns it. If no data is available to be read, `null` is returned. By default, + * the data is returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If + * `size` bytes are not available to be read, `null` will be returned _unless_ the + * stream has ended, in which case all of the data remaining in the internal buffer + * will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the `size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as `Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer` objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling `readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the `Readable`. + * This is used primarily by the mechanism that underlies the `readable.pipe()` method. + * In most typical cases, there will be no reason to use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * import fs from 'node:fs'; + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * import { StringDecoder } from 'node:string_decoder'; + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.includes('\n\n')) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * return; + * } + * // Still reading the header. + * header += str; + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must + * be a {string}, {Buffer}, {TypedArray}, {DataView} or `null`. For object mode streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `node:stream` module API as it is currently defined. (See `Compatibility` for more + * information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the `readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * import { OldReader } from './old-api-module.js'; + * import { Readable } from 'node:stream'; + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + /** + * The iterator created by this method gives users the option to cancel the destruction + * of the stream if the `for await...of` loop is exited by `return`, `break`, or `throw`, + * or if the iterator should destroy the stream if the stream emitted an error during iteration. + * @since v16.3.0 + * @param options.destroyOnReturn When set to `false`, calling `return` on the async iterator, + * or exiting a `for await...of` iteration using a `break`, `return`, or `throw` will not destroy the stream. + * **Default: `true`**. + */ + iterator(options?: { destroyOnReturn?: boolean }): NodeJS.AsyncIterator; + /** + * This method allows mapping over the stream. The *fn* function will be called for every chunk in the stream. + * If the *fn* function returns a promise - that promise will be `await`ed before being passed to the result stream. + * @since v17.4.0, v16.14.0 + * @param fn a function to map over every chunk in the stream. Async or not. + * @returns a stream mapped with the function *fn*. + */ + map(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method allows filtering the stream. For each chunk in the stream the *fn* function will be called + * and if it returns a truthy value, the chunk will be passed to the result stream. + * If the *fn* function returns a promise - that promise will be `await`ed. + * @since v17.4.0, v16.14.0 + * @param fn a function to filter chunks from the stream. Async or not. + * @returns a stream filtered with the predicate *fn*. + */ + filter( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Readable; + /** + * This method allows iterating a stream. For each chunk in the stream the *fn* function will be called. + * If the *fn* function returns a promise - that promise will be `await`ed. + * + * This method is different from `for await...of` loops in that it can optionally process chunks concurrently. + * In addition, a `forEach` iteration can only be stopped by having passed a `signal` option + * and aborting the related AbortController while `for await...of` can be stopped with `break` or `return`. + * In either case the stream will be destroyed. + * + * This method is different from listening to the `'data'` event in that it uses the `readable` event + * in the underlying machinary and can limit the number of concurrent *fn* calls. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise for when the stream has finished. + */ + forEach( + fn: (data: any, options?: Pick) => void | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method allows easily obtaining the contents of a stream. + * + * As this method reads the entire stream into memory, it negates the benefits of streams. It's intended + * for interoperability and convenience, not as the primary way to consume streams. + * @since v17.5.0 + * @returns a promise containing an array with the contents of the stream. + */ + toArray(options?: Pick): Promise; + /** + * This method is similar to `Array.prototype.some` and calls *fn* on each chunk in the stream + * until the awaited return value is `true` (or any truthy value). Once an *fn* call on a chunk + * `await`ed return value is truthy, the stream is destroyed and the promise is fulfilled with `true`. + * If none of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `false`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for at least one of the chunks. + */ + some( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.find` and calls *fn* on each chunk in the stream + * to find a chunk with a truthy value for *fn*. Once an *fn* call's awaited return value is truthy, + * the stream is destroyed and the promise is fulfilled with value for which *fn* returned a truthy value. + * If all of the *fn* calls on the chunks return a falsy value, the promise is fulfilled with `undefined`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to the first chunk for which *fn* evaluated with a truthy value, + * or `undefined` if no element was found. + */ + find( + fn: (data: any, options?: Pick) => data is T, + options?: ArrayOptions, + ): Promise; + find( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.every` and calls *fn* on each chunk in the stream + * to check if all awaited return values are truthy value for *fn*. Once an *fn* call on a chunk + * `await`ed return value is falsy, the stream is destroyed and the promise is fulfilled with `false`. + * If all of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `true`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for every one of the chunks. + */ + every( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method returns a new stream by applying the given callback to each chunk of the stream + * and then flattening the result. + * + * It is possible to return a stream or another iterable or async iterable from *fn* and the result streams + * will be merged (flattened) into the returned stream. + * @since v17.5.0 + * @param fn a function to map over every chunk in the stream. May be async. May be a stream or generator. + * @returns a stream flat-mapped with the function *fn*. + */ + flatMap(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method returns a new stream with the first *limit* chunks dropped from the start. + * @since v17.5.0 + * @param limit the number of chunks to drop from the readable. + * @returns a stream with *limit* chunks dropped from the start. + */ + drop(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with the first *limit* chunks. + * @since v17.5.0 + * @param limit the number of chunks to take from the readable. + * @returns a stream with *limit* chunks taken. + */ + take(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with chunks of the underlying stream paired with a counter + * in the form `[index, chunk]`. The first index value is `0` and it increases by 1 for each chunk produced. + * @since v17.5.0 + * @returns a stream of indexed pairs. + */ + asIndexedPairs(options?: Pick): Readable; + /** + * This method calls *fn* on each chunk of the stream in order, passing it the result from the calculation + * on the previous element. It returns a promise for the final value of the reduction. + * + * If no *initial* value is supplied the first chunk of the stream is used as the initial value. + * If the stream is empty, the promise is rejected with a `TypeError` with the `ERR_INVALID_ARGS` code property. + * + * The reducer function iterates the stream element-by-element which means that there is no *concurrency* parameter + * or parallelism. To perform a reduce concurrently, you can extract the async function to `readable.map` method. + * @since v17.5.0 + * @param fn a reducer function to call over every chunk in the stream. Async or not. + * @param initial the initial value to use in the reduction. + * @returns a promise for the final value of the reduction. + */ + reduce( + fn: (previous: any, data: any, options?: Pick) => T, + initial?: undefined, + options?: Pick, + ): Promise; + reduce( + fn: (previous: T, data: any, options?: Pick) => T, + initial: T, + options?: Pick, + ): Promise; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()` will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): this; + /** + * @returns `AsyncIterator` to fully consume the stream. + * @since v10.0.0 + */ + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + /** + * Calls `readable.destroy()` with an `AbortError` and returns + * a promise that fulfills when the stream is finished. + * @since v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "pause"): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?: + | (( + this: T, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ) => void) + | undefined; + writev?: + | (( + this: T, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ) => void) + | undefined; + final?: ((this: T, callback: (error?: Error | null) => void) => void) | undefined; + } + /** + * @since v0.9.4 + */ + class Writable extends Stream implements NodeJS.WritableStream { + /** + * A utility method for creating a `Writable` from a web `WritableStream`. + * @since v17.0.0 + */ + static fromWeb( + writableStream: streamWeb.WritableStream, + options?: Pick, + ): Writable; + /** + * A utility method for creating a web `WritableStream` from a `Writable`. + * @since v17.0.0 + */ + static toWeb(streamWritable: Writable): streamWeb.WritableStream; + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored, or ended. + * @since v11.4.0 + */ + readonly writable: boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'finish'`. + * @since v18.0.0, v16.17.0 + */ + readonly writableAborted: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + /** + * Is `true` if the stream's buffer has been full and stream will emit `'drain'`. + * @since v15.2.0, v14.17.0 + */ + readonly writableNeedDrain: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the `highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * Once `write()` returns false, do not write more chunks + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + /** + * Writes data to the stream, with an explicit encoding for string data. + * @see {@link Writable.write} for full details. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param encoding The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * import fs from 'node:fs'; + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param cb Callback for when the stream is finished. + */ + end(cb?: () => void): this; + /** + * Signals that no more data will be written, with one final chunk of data. + * @see {@link Writable.end} for full details. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param cb Callback for when the stream is finished. + */ + end(chunk: any, cb?: () => void): this; + /** + * Signals that no more data will be written, with one final chunk of data. + * @see {@link Writable.end} for full details. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param cb Callback for when the stream is finished. + */ + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()` buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing `writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, defer calls to `writable.uncork()` using `process.nextTick()`. Doing so allows batching of all `writable.write()` calls that occur within a given Node.js event + * loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to `write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Calls `writable.destroy()` with an `AbortError` and returns + * a promise that fulfills when the stream is finished. + * @since v22.4.0, v20.16.0 + */ + [Symbol.asyncDispose](): Promise; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + } + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends Stream implements NodeJS.ReadWriteStream { + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `true`. + * + * This can be changed manually to change the half-open behavior of an existing + * `Duplex` stream instance, but must be changed before the `'end'` event is emitted. + * @since v0.9.4 + */ + allowHalfOpen: boolean; + constructor(opts?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from( + src: + | Stream + | NodeBlob + | ArrayBuffer + | string + | Iterable + | AsyncIterable + | AsyncGeneratorFunction + | Promise + | Object, + ): Duplex; + /** + * A utility method for creating a web `ReadableStream` and `WritableStream` from a `Duplex`. + * @since v17.0.0 + */ + static toWeb(streamDuplex: Duplex): { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }; + /** + * A utility method for creating a `Duplex` from a web `ReadableStream` and `WritableStream`. + * @since v17.0.0 + */ + static fromWeb( + duplexStream: { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }, + options?: Pick< + DuplexOptions, + "allowHalfOpen" | "decodeStrings" | "encoding" | "highWaterMark" | "objectMode" | "signal" + >, + ): Duplex; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. drain + * 4. end + * 5. error + * 6. finish + * 7. pause + * 8. pipe + * 9. readable + * 10. resume + * 11. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pause"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pause", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pause", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface Duplex extends Readable, Writable {} + /** + * The utility function `duplexPair` returns an Array with two items, + * each being a `Duplex` stream connected to the other side: + * + * ```js + * const [ sideA, sideB ] = duplexPair(); + * ``` + * + * Whatever is written to one stream is made readable on the other. It provides + * behavior analogous to a network connection, where the data written by the client + * becomes readable by the server, and vice-versa. + * + * The Duplex streams are symmetrical; one or the other may be used without any + * difference in behavior. + * @param options A value to pass to both {@link Duplex} constructors, + * to set options such as buffering. + * @since v22.6.0 + */ + function duplexPair(options?: DuplexOptions): [Duplex, Duplex]; + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + transform?: + | ((this: T, chunk: any, encoding: BufferEncoding, callback: TransformCallback) => void) + | undefined; + flush?: ((this: T, callback: TransformCallback) => void) | undefined; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where `stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * A stream to attach a signal to. + * + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed `AbortSignal` will behave the same way as calling `.destroy(new AbortError())` on the + * stream, and `controller.error(new AbortError())` for webstreams. + * + * ```js + * import fs from 'node:fs'; + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * + * Or using an `AbortSignal` with a ReadableStream: + * + * ```js + * const controller = new AbortController(); + * const rs = new ReadableStream({ + * start(controller) { + * controller.enqueue('hello'); + * controller.enqueue('world'); + * controller.close(); + * }, + * }); + * + * addAbortSignal(controller.signal, rs); + * + * finished(rs, (err) => { + * if (err) { + * if (err.name === 'AbortError') { + * // The operation was cancelled + * } + * } + * }); + * + * const reader = rs.getReader(); + * + * reader.read().then(({ value, done }) => { + * console.log(value); // hello + * console.log(done); // false + * controller.abort(); + * }); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream A stream to attach a signal to. + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + /** + * Returns the default highWaterMark used by streams. + * Defaults to `65536` (64 KiB), or `16` for `objectMode`. + * @since v19.9.0 + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v19.9.0 + * @param value highWaterMark value + */ + function setDefaultHighWaterMark(objectMode: boolean, value: number): void; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A readable and/or writable stream/webstream. + * + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * import { finished } from 'node:stream'; + * import fs from 'node:fs'; + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'` or `'finish'`. + * + * The `finished` API provides [`promise version`](https://nodejs.org/docs/latest-v24.x/api/stream.html#streamfinishedstream-options). + * + * `stream.finished()` leaves dangling event listeners (in particular `'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @returns A cleanup function which removes all registered listeners. + */ + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options: FinishedOptions, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + namespace finished { + function __promisify__( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + } + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + | NodeJS.ReadWriteStream + | (( + source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable + : S, + ) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

; + type PipelineDestination, P> = S extends + PipelineTransformSource ? + | NodeJS.WritableStream + | PipelineDestinationIterableFunction + | PipelineDestinationPromiseFunction + : never; + type PipelineCallback> = S extends + PipelineDestinationPromiseFunction ? (err: NodeJS.ErrnoException | null, value: P) => void + : (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = S extends + PipelineDestinationPromiseFunction ? Promise

: Promise; + interface PipelineOptions { + signal?: AbortSignal | undefined; + end?: boolean | undefined; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * import { pipeline } from 'node:stream'; + * import fs from 'node:fs'; + * import zlib from 'node:zlib'; + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * }, + * ); + * ``` + * + * The `pipeline` API provides a [`promise version`](https://nodejs.org/docs/latest-v24.x/api/stream.html#streampipelinesource-transforms-destination-options). + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. If the last + * stream is readable, dangling event listeners will be removed so that the last + * stream can be consumed later. + * + * `stream.pipeline()` closes all the streams when an error is raised. + * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior + * once it would destroy the socket without sending the expected response. + * See the example below: + * + * ```js + * import fs from 'node:fs'; + * import http from 'node:http'; + * import { pipeline } from 'node:stream'; + * + * const server = http.createServer((req, res) => { + * const fileStream = fs.createReadStream('./fileNotExist.txt'); + * pipeline(fileStream, res, (err) => { + * if (err) { + * console.log(err); // No such file + * // this message can't be sent once `pipeline` already destroyed the socket + * return res.end('error!!!'); + * } + * }); + * }); + * ``` + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline( + streams: ReadonlyArray, + callback: (err: NodeJS.ErrnoException | null) => void, + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array< + NodeJS.ReadWriteStream | NodeJS.WritableStream | ((err: NodeJS.ErrnoException | null) => void) + > + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; + } + // TODO: this interface never existed; remove in next major + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + // TODO: these should all take webstream arguments + /** + * Returns whether the stream has encountered an error. + * @since v17.3.0, v16.14.0 + */ + function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; + /** + * Returns whether the stream is readable. + * @since v17.4.0, v16.14.0 + * @returns Only returns `null` if `stream` is not a valid `Readable`, `Duplex` or `ReadableStream`. + */ + function isReadable(stream: Readable | NodeJS.ReadableStream): boolean | null; + /** + * Returns whether the stream is writable. + * @since v20.0.0 + * @returns Only returns `null` if `stream` is not a valid `Writable`, `Duplex` or `WritableStream`. + */ + function isWritable(stream: Writable | NodeJS.WritableStream): boolean | null; + } + export = Stream; +} +declare module "node:stream" { + import stream = require("stream"); + export = stream; +} diff --git a/tools/ui/node_modules/@types/node/stream/consumers.d.ts b/tools/ui/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..05db0257d276a573e5302b37fff774a62cedba22 --- /dev/null +++ b/tools/ui/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,38 @@ +/** + * The utility consumer functions provide common options for consuming + * streams. + * @since v16.7.0 + */ +declare module "stream/consumers" { + import { Blob as NodeBlob, NonSharedBuffer } from "node:buffer"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + /** + * @since v16.7.0 + * @returns Fulfills with an `ArrayBuffer` containing the full contents of the stream. + */ + function arrayBuffer(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with a `Blob` containing the full contents of the stream. + */ + function blob(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with a `Buffer` containing the full contents of the stream. + */ + function buffer(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with the contents of the stream parsed as a + * UTF-8 encoded string that is then passed through `JSON.parse()`. + */ + function json(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with the contents of the stream parsed as a UTF-8 encoded string. + */ + function text(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; +} +declare module "node:stream/consumers" { + export * from "stream/consumers"; +} diff --git a/tools/ui/node_modules/@types/node/stream/promises.d.ts b/tools/ui/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d54c14c60fa3590259439e2d02b995710966a664 --- /dev/null +++ b/tools/ui/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,90 @@ +declare module "stream/promises" { + import { + FinishedOptions as _FinishedOptions, + PipelineDestination, + PipelineOptions, + PipelinePromise, + PipelineSource, + PipelineTransform, + } from "node:stream"; + interface FinishedOptions extends _FinishedOptions { + /** + * If true, removes the listeners registered by this function before the promise is fulfilled. + * @default false + */ + cleanup?: boolean | undefined; + } + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module "node:stream/promises" { + export * from "stream/promises"; +} diff --git a/tools/ui/node_modules/@types/node/stream/web.d.ts b/tools/ui/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fc88e13fff057beccdb095aba975e35eda67fd22 --- /dev/null +++ b/tools/ui/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,573 @@ +type _ByteLengthQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ByteLengthQueuingStrategy; +type _CountQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").CountQueuingStrategy; +type _QueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").QueuingStrategy; +type _ReadableByteStreamController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableByteStreamController; +type _ReadableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStream; +type _ReadableStreamBYOBReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBReader; +type _ReadableStreamBYOBRequest = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBRequest; +type _ReadableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultController; +type _ReadableStreamDefaultReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultReader; +type _TextDecoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextDecoderStream; +type _TextEncoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextEncoderStream; +type _TransformStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStream; +type _TransformStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStreamDefaultController; +type _WritableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStream; +type _WritableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultController; +type _WritableStreamDefaultWriter = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultWriter; + +declare module "stream/web" { + // stub module, pending copy&paste from .d.ts or manual impl + // copy from lib.dom.d.ts + interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream + * through a transform stream (or any other { writable, readable } + * pair). It simply pipes the stream into the writable side of the + * supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + */ + writable: WritableStream; + } + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. + * The way in which the piping process behaves under various error + * conditions can be customized with a number of passed options. It + * returns a promise that fulfills when the piping process completes + * successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate + * as follows: + * + * An error in this source readable stream will abort destination, + * unless preventAbort is truthy. The returned promise will be rejected + * with the source's error, or with any error that occurs during + * aborting the destination. + * + * An error in destination will cancel this source readable stream, + * unless preventCancel is truthy. The returned promise will be rejected + * with the destination's error, or with any error that occurs during + * canceling the source. + * + * When this source readable stream closes, destination will be closed, + * unless preventClose is truthy. The returned promise will be fulfilled + * once this process completes, unless an error is encountered while + * closing the destination, in which case it will be rejected with that + * error. + * + * If destination starts out closed or closing, this source readable + * stream will be canceled, unless preventCancel is true. The returned + * promise will be rejected with an error indicating piping to a closed + * stream failed, or with any error that occurs during canceling the + * source. + * + * The signal option can be set to an AbortSignal to allow aborting an + * ongoing pipe operation via the corresponding AbortController. In this + * case, this source readable stream will be canceled, and destination + * aborted, unless the respective options preventCancel or preventAbort + * are set. + */ + preventClose?: boolean; + signal?: AbortSignal; + } + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + type ReadableStreamController = ReadableStreamDefaultController; + interface ReadableStreamReadValueResult { + done: false; + value: T; + } + interface ReadableStreamReadDoneResult { + done: true; + value: T | undefined; + } + type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; + interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; + } + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerCancelCallback { + (reason: any): void | PromiseLike; + } + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; + } + interface UnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: undefined; + } + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; + } + interface ReadableStreamAsyncIterator extends NodeJS.AsyncIterator { + [Symbol.asyncIterator](): ReadableStreamAsyncIterator; + } + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + getReader(): ReadableStreamDefaultReader; + getReader(options?: ReadableStreamGetReaderOptions): ReadableStreamReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): ReadableStreamAsyncIterator; + [Symbol.asyncIterator](): ReadableStreamAsyncIterator; + } + const ReadableStream: { + prototype: ReadableStream; + from(iterable: Iterable | AsyncIterable): ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + type ReadableStreamReaderMode = "byob"; + interface ReadableStreamGetReaderOptions { + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode?: ReadableStreamReaderMode; + } + type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ + interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + options?: { + min?: number; + }, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new(stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; + }; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ + interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + readonly view: ArrayBufferView | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBufferView): void; + } + const ReadableStreamBYOBRequest: { + prototype: ReadableStreamBYOBRequest; + new(): ReadableStreamBYOBRequest; + }; + interface ReadableByteStreamController { + readonly byobRequest: ReadableStreamBYOBRequest | null; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; + } + const ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new(): ReadableByteStreamController; + }; + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: R): void; + error(e?: any): void; + } + const ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new(): ReadableStreamDefaultController; + }; + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + cancel?: TransformerCancelCallback; + writableType?: undefined; + } + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const TransformStream: { + prototype: TransformStream; + new( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ): TransformStream; + }; + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk: O): void; + error(reason?: any): void; + terminate(): void; + } + const TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new(): TransformStreamDefaultController; + }; + /** + * This Streams API interface provides a standard abstraction for writing + * streaming data to a destination, known as a sink. This object comes with + * built-in back pressure and queuing. + */ + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + const WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + /** + * This Streams API interface is the object returned by + * WritableStream.getWriter() and once created locks the < writer to the + * WritableStream ensuring that no other streams can write to the underlying + * sink. + */ + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk: W): Promise; + } + const WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(stream: WritableStream): WritableStreamDefaultWriter; + }; + /** + * This Streams API interface represents a controller allowing control of a + * WritableStream's state. When constructing a WritableStream, the + * underlying sink is given a corresponding WritableStreamDefaultController + * instance to manipulate. + */ + interface WritableStreamDefaultController { + error(e?: any): void; + } + const WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; + }; + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + interface QueuingStrategySize { + (chunk: T): number; + } + interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water + * mark. + * + * Note that the provided high water mark will not be validated ahead of + * time. Instead, if it is negative, NaN, or not a number, the resulting + * ByteLengthQueuingStrategy will cause the corresponding stream + * constructor to throw. + */ + highWaterMark: number; + } + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(init: QueuingStrategyInit): CountQueuingStrategy; + }; + interface TextEncoderStream { + /** Returns "utf-8". */ + readonly encoding: "utf-8"; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextEncoderStream: { + prototype: TextEncoderStream; + new(): TextEncoderStream; + }; + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + type BufferSource = ArrayBufferView | ArrayBuffer; + interface TextDecoderStream { + /** Returns encoding's name, lower cased. */ + readonly encoding: string; + /** Returns `true` if error mode is "fatal", and `false` otherwise. */ + readonly fatal: boolean; + /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ + readonly ignoreBOM: boolean; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextDecoderStream: { + prototype: TextDecoderStream; + new(encoding?: string, options?: TextDecoderOptions): TextDecoderStream; + }; + type CompressionFormat = "brotli" | "deflate" | "deflate-raw" | "gzip"; + class CompressionStream { + constructor(format: CompressionFormat); + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + class DecompressionStream { + constructor(format: CompressionFormat); + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + + global { + interface ByteLengthQueuingStrategy extends _ByteLengthQueuingStrategy {} + /** + * `ByteLengthQueuingStrategy` class is a global reference for `import { ByteLengthQueuingStrategy } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-bytelengthqueuingstrategy + * @since v18.0.0 + */ + var ByteLengthQueuingStrategy: typeof globalThis extends { onmessage: any; ByteLengthQueuingStrategy: infer T } + ? T + : typeof import("stream/web").ByteLengthQueuingStrategy; + + interface CountQueuingStrategy extends _CountQueuingStrategy {} + /** + * `CountQueuingStrategy` class is a global reference for `import { CountQueuingStrategy } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-countqueuingstrategy + * @since v18.0.0 + */ + var CountQueuingStrategy: typeof globalThis extends { onmessage: any; CountQueuingStrategy: infer T } ? T + : typeof import("stream/web").CountQueuingStrategy; + + interface QueuingStrategy extends _QueuingStrategy {} + + interface ReadableByteStreamController extends _ReadableByteStreamController {} + /** + * `ReadableByteStreamController` class is a global reference for `import { ReadableByteStreamController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablebytestreamcontroller + * @since v18.0.0 + */ + var ReadableByteStreamController: typeof globalThis extends + { onmessage: any; ReadableByteStreamController: infer T } ? T + : typeof import("stream/web").ReadableByteStreamController; + + interface ReadableStream extends _ReadableStream {} + /** + * `ReadableStream` class is a global reference for `import { ReadableStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestream + * @since v18.0.0 + */ + var ReadableStream: typeof globalThis extends { onmessage: any; ReadableStream: infer T } ? T + : typeof import("stream/web").ReadableStream; + + interface ReadableStreamBYOBReader extends _ReadableStreamBYOBReader {} + /** + * `ReadableStreamBYOBReader` class is a global reference for `import { ReadableStreamBYOBReader } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreambyobreader + * @since v18.0.0 + */ + var ReadableStreamBYOBReader: typeof globalThis extends { onmessage: any; ReadableStreamBYOBReader: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBReader; + + interface ReadableStreamBYOBRequest extends _ReadableStreamBYOBRequest {} + /** + * `ReadableStreamBYOBRequest` class is a global reference for `import { ReadableStreamBYOBRequest } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreambyobrequest + * @since v18.0.0 + */ + var ReadableStreamBYOBRequest: typeof globalThis extends { onmessage: any; ReadableStreamBYOBRequest: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBRequest; + + interface ReadableStreamDefaultController extends _ReadableStreamDefaultController {} + /** + * `ReadableStreamDefaultController` class is a global reference for `import { ReadableStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreamdefaultcontroller + * @since v18.0.0 + */ + var ReadableStreamDefaultController: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultController: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultController; + + interface ReadableStreamDefaultReader extends _ReadableStreamDefaultReader {} + /** + * `ReadableStreamDefaultReader` class is a global reference for `import { ReadableStreamDefaultReader } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreamdefaultreader + * @since v18.0.0 + */ + var ReadableStreamDefaultReader: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultReader: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultReader; + + interface TextDecoderStream extends _TextDecoderStream {} + /** + * `TextDecoderStream` class is a global reference for `import { TextDecoderStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-textdecoderstream + * @since v18.0.0 + */ + var TextDecoderStream: typeof globalThis extends { onmessage: any; TextDecoderStream: infer T } ? T + : typeof import("stream/web").TextDecoderStream; + + interface TextEncoderStream extends _TextEncoderStream {} + /** + * `TextEncoderStream` class is a global reference for `import { TextEncoderStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-textencoderstream + * @since v18.0.0 + */ + var TextEncoderStream: typeof globalThis extends { onmessage: any; TextEncoderStream: infer T } ? T + : typeof import("stream/web").TextEncoderStream; + + interface TransformStream extends _TransformStream {} + /** + * `TransformStream` class is a global reference for `import { TransformStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-transformstream + * @since v18.0.0 + */ + var TransformStream: typeof globalThis extends { onmessage: any; TransformStream: infer T } ? T + : typeof import("stream/web").TransformStream; + + interface TransformStreamDefaultController extends _TransformStreamDefaultController {} + /** + * `TransformStreamDefaultController` class is a global reference for `import { TransformStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-transformstreamdefaultcontroller + * @since v18.0.0 + */ + var TransformStreamDefaultController: typeof globalThis extends + { onmessage: any; TransformStreamDefaultController: infer T } ? T + : typeof import("stream/web").TransformStreamDefaultController; + + interface WritableStream extends _WritableStream {} + /** + * `WritableStream` class is a global reference for `import { WritableStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestream + * @since v18.0.0 + */ + var WritableStream: typeof globalThis extends { onmessage: any; WritableStream: infer T } ? T + : typeof import("stream/web").WritableStream; + + interface WritableStreamDefaultController extends _WritableStreamDefaultController {} + /** + * `WritableStreamDefaultController` class is a global reference for `import { WritableStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestreamdefaultcontroller + * @since v18.0.0 + */ + var WritableStreamDefaultController: typeof globalThis extends + { onmessage: any; WritableStreamDefaultController: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultController; + + interface WritableStreamDefaultWriter extends _WritableStreamDefaultWriter {} + /** + * `WritableStreamDefaultWriter` class is a global reference for `import { WritableStreamDefaultWriter } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestreamdefaultwriter + * @since v18.0.0 + */ + var WritableStreamDefaultWriter: typeof globalThis extends + { onmessage: any; WritableStreamDefaultWriter: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultWriter; + } +} +declare module "node:stream/web" { + export * from "stream/web"; +} diff --git a/tools/ui/node_modules/@types/node/string_decoder.d.ts b/tools/ui/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bcd64d5a32fd72ddd550140163dfcdf9b65b0af5 --- /dev/null +++ b/tools/ui/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `node:string_decoder` module provides an API for decoding `Buffer` objects + * into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); // Prints: ¢ + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); // Prints: € + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/string_decoder.js) + */ +declare module "string_decoder" { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer The bytes to decode. + */ + write(buffer: string | NodeJS.ArrayBufferView): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer The bytes to decode. + */ + end(buffer?: string | NodeJS.ArrayBufferView): string; + } +} +declare module "node:string_decoder" { + export * from "string_decoder"; +} diff --git a/tools/ui/node_modules/@types/node/test.d.ts b/tools/ui/node_modules/@types/node/test.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..848f4ca1c5687a2bea7d38c0f23a2874a751f77a --- /dev/null +++ b/tools/ui/node_modules/@types/node/test.d.ts @@ -0,0 +1,2349 @@ +/** + * The `node:test` module facilitates the creation of JavaScript tests. + * To access it: + * + * ```js + * import test from 'node:test'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'node:test'; + * ``` + * + * Tests created via the `test` module consist of a single function that is + * processed in one of three ways: + * + * 1. A synchronous function that is considered failing if it throws an exception, + * and is considered passing otherwise. + * 2. A function that returns a `Promise` that is considered failing if the `Promise` rejects, and is considered passing if the `Promise` fulfills. + * 3. A function that receives a callback function. If the callback receives any + * truthy value as its first argument, the test is considered failing. If a + * falsy value is passed as the first argument to the callback, the test is + * considered passing. If the test function receives a callback function and + * also returns a `Promise`, the test will fail. + * + * The following example illustrates how tests are written using the `test` module. + * + * ```js + * test('synchronous passing test', (t) => { + * // This test passes because it does not throw an exception. + * assert.strictEqual(1, 1); + * }); + * + * test('synchronous failing test', (t) => { + * // This test fails because it throws an exception. + * assert.strictEqual(1, 2); + * }); + * + * test('asynchronous passing test', async (t) => { + * // This test passes because the Promise returned by the async + * // function is settled and not rejected. + * assert.strictEqual(1, 1); + * }); + * + * test('asynchronous failing test', async (t) => { + * // This test fails because the Promise returned by the async + * // function is rejected. + * assert.strictEqual(1, 2); + * }); + * + * test('failing test using Promises', (t) => { + * // Promises can be used directly as well. + * return new Promise((resolve, reject) => { + * setImmediate(() => { + * reject(new Error('this will cause the test to fail')); + * }); + * }); + * }); + * + * test('callback passing test', (t, done) => { + * // done() is the callback function. When the setImmediate() runs, it invokes + * // done() with no arguments. + * setImmediate(done); + * }); + * + * test('callback failing test', (t, done) => { + * // When the setImmediate() runs, done() is invoked with an Error object and + * // the test fails. + * setImmediate(() => { + * done(new Error('callback failure')); + * }); + * }); + * ``` + * + * If any tests fail, the process exit code is set to `1`. + * @since v18.0.0, v16.17.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/test.js) + */ +declare module "node:test" { + import { AssertMethodNames } from "node:assert"; + import { Readable } from "node:stream"; + import { URL } from "node:url"; + import TestFn = test.TestFn; + import TestOptions = test.TestOptions; + /** + * The `test()` function is the value imported from the `test` module. Each + * invocation of this function results in reporting the test to the `TestsStream`. + * + * The `TestContext` object passed to the `fn` argument can be used to perform + * actions related to the current test. Examples include skipping the test, adding + * additional diagnostic information, or creating subtests. + * + * `test()` returns a `Promise` that fulfills once the test completes. + * if `test()` is called within a suite, it fulfills immediately. + * The return value can usually be discarded for top level tests. + * However, the return value from subtests should be used to prevent the parent + * test from finishing first and cancelling the subtest + * as shown in the following example. + * + * ```js + * test('top level test', async (t) => { + * // The setTimeout() in the following subtest would cause it to outlive its + * // parent test if 'await' is removed on the next line. Once the parent test + * // completes, it will cancel any outstanding subtests. + * await t.test('longer running subtest', async (t) => { + * return new Promise((resolve, reject) => { + * setTimeout(resolve, 1000); + * }); + * }); + * }); + * ``` + * + * The `timeout` option can be used to fail the test if it takes longer than `timeout` milliseconds to complete. However, it is not a reliable mechanism for + * canceling tests because a running test might block the application thread and + * thus prevent the scheduled cancellation. + * @since v18.0.0, v16.17.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within a suite. + */ + function test(name?: string, fn?: TestFn): Promise; + function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function test(options?: TestOptions, fn?: TestFn): Promise; + function test(fn?: TestFn): Promise; + namespace test { + export { test }; + export { suite as describe, test as it }; + } + namespace test { + /** + * **Note:** `shard` is used to horizontally parallelize test running across + * machines or processes, ideal for large-scale executions across varied + * environments. It's incompatible with `watch` mode, tailored for rapid + * code iteration by automatically rerunning tests on file changes. + * + * ```js + * import { tap } from 'node:test/reporters'; + * import { run } from 'node:test'; + * import process from 'node:process'; + * import path from 'node:path'; + * + * run({ files: [path.resolve('./tests/test.js')] }) + * .compose(tap) + * .pipe(process.stdout); + * ``` + * @since v18.9.0, v16.19.0 + * @param options Configuration options for running tests. + */ + function run(options?: RunOptions): TestsStream; + /** + * The `suite()` function is imported from the `node:test` module. + * @param name The name of the suite, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the suite. This supports the same options as {@link test}. + * @param fn The suite function declaring nested tests and suites. The first argument to this function is a {@link SuiteContext} object. + * @return Immediately fulfilled with `undefined`. + * @since v20.13.0 + */ + function suite(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function suite(name?: string, fn?: SuiteFn): Promise; + function suite(options?: TestOptions, fn?: SuiteFn): Promise; + function suite(fn?: SuiteFn): Promise; + namespace suite { + /** + * Shorthand for skipping a suite. This is the same as calling {@link suite} with `options.skip` set to `true`. + * @since v20.13.0 + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`. This is the same as calling {@link suite} with `options.todo` set to `true`. + * @since v20.13.0 + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`. This is the same as calling {@link suite} with `options.only` set to `true`. + * @since v20.13.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + } + /** + * Shorthand for skipping a test. This is the same as calling {@link test} with `options.skip` set to `true`. + * @since v20.2.0 + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`. This is the same as calling {@link test} with `options.todo` set to `true`. + * @since v20.2.0 + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`. This is the same as calling {@link test} with `options.only` set to `true`. + * @since v20.2.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + /** + * The type of a function passed to {@link test}. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => void | Promise; + /** + * The type of a suite test function. The argument to this function is a {@link SuiteContext} object. + */ + type SuiteFn = (s: SuiteContext) => void | Promise; + interface TestShard { + /** + * A positive integer between 1 and `total` that specifies the index of the shard to run. + */ + index: number; + /** + * A positive integer that specifies the total number of shards to split the test files to. + */ + total: number; + } + interface RunOptions { + /** + * If a number is provided, then that many tests would run asynchronously (they are still managed by the single-threaded event loop). + * If `true`, it would run `os.availableParallelism() - 1` test files in parallel. If `false`, it would only run one test file at a time. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * Specifies the current working directory to be used by the test runner. + * Serves as the base path for resolving files according to the + * [test runner execution model](https://nodejs.org/docs/latest-v24.x/api/test.html#test-runner-execution-model). + * @since v23.0.0 + * @default process.cwd() + */ + cwd?: string | undefined; + /** + * An array containing the list of files to run. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v24.x/api/test.html#test-runner-execution-model). + */ + files?: readonly string[] | undefined; + /** + * Configures the test runner to exit the process once all known + * tests have finished executing even if the event loop would + * otherwise remain active. + * @default false + */ + forceExit?: boolean | undefined; + /** + * An array containing the list of glob patterns to match test files. + * This option cannot be used together with `files`. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v24.x/api/test.html#test-runner-execution-model). + * @since v22.6.0 + */ + globPatterns?: readonly string[] | undefined; + /** + * Sets inspector port of test child process. + * This can be a number, or a function that takes no arguments and returns a + * number. If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. This option is ignored + * if the `isolation` option is set to `'none'` as no child processes are + * spawned. + * @default undefined + */ + inspectPort?: number | (() => number) | undefined; + /** + * Configures the type of test isolation. If set to + * `'process'`, each test file is run in a separate child process. If set to + * `'none'`, all test files run in the current process. + * @default 'process' + * @since v22.8.0 + */ + isolation?: "process" | "none" | undefined; + /** + * If truthy, the test context will only run tests that have the `only` option set + */ + only?: boolean | undefined; + /** + * A function that accepts the `TestsStream` instance and can be used to setup listeners before any tests are run. + * @default undefined + */ + setup?: ((reporter: TestsStream) => void | Promise) | undefined; + /** + * An array of CLI flags to pass to the `node` executable when + * spawning the subprocesses. This option has no effect when `isolation` is `'none`'. + * @since v22.10.0 + * @default [] + */ + execArgv?: readonly string[] | undefined; + /** + * An array of CLI flags to pass to each test file when spawning the + * subprocesses. This option has no effect when `isolation` is `'none'`. + * @since v22.10.0 + * @default [] + */ + argv?: readonly string[] | undefined; + /** + * Allows aborting an in-progress test execution. + */ + signal?: AbortSignal | undefined; + /** + * If provided, only run tests whose name matches the provided pattern. + * Strings are interpreted as JavaScript regular expressions. + * @default undefined + */ + testNamePatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * A String, RegExp or a RegExp Array, that can be used to exclude running tests whose + * name matches the provided pattern. Test name patterns are interpreted as JavaScript + * regular expressions. For each test that is executed, any corresponding test hooks, + * such as `beforeEach()`, are also run. + * @default undefined + * @since v22.1.0 + */ + testSkipPatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * The number of milliseconds after which the test execution will fail. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + /** + * Whether to run in watch mode or not. + * @default false + */ + watch?: boolean | undefined; + /** + * Running tests in a specific shard. + * @default undefined + */ + shard?: TestShard | undefined; + /** + * A file path where the test runner will + * store the state of the tests to allow rerunning only the failed tests on a next run. + * @since v24.7.0 + * @default undefined + */ + rerunFailuresFilePath?: string | undefined; + /** + * enable [code coverage](https://nodejs.org/docs/latest-v24.x/api/test.html#collecting-code-coverage) collection. + * @since v22.10.0 + * @default false + */ + coverage?: boolean | undefined; + /** + * Excludes specific files from code coverage + * using a glob pattern, which can match both absolute and relative file paths. + * This property is only applicable when `coverage` was set to `true`. + * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided, + * files must meet **both** criteria to be included in the coverage report. + * @since v22.10.0 + * @default undefined + */ + coverageExcludeGlobs?: string | readonly string[] | undefined; + /** + * Includes specific files in code coverage + * using a glob pattern, which can match both absolute and relative file paths. + * This property is only applicable when `coverage` was set to `true`. + * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided, + * files must meet **both** criteria to be included in the coverage report. + * @since v22.10.0 + * @default undefined + */ + coverageIncludeGlobs?: string | readonly string[] | undefined; + /** + * Require a minimum percent of covered lines. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + lineCoverage?: number | undefined; + /** + * Require a minimum percent of covered branches. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + branchCoverage?: number | undefined; + /** + * Require a minimum percent of covered functions. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + functionCoverage?: number | undefined; + } + /** + * A successful call to `run()` will return a new `TestsStream` object, streaming a series of events representing the execution of the tests. + * + * Some of the events are guaranteed to be emitted in the same order as the tests are defined, while others are emitted in the order that the tests execute. + * @since v18.9.0, v16.19.0 + */ + interface TestsStream extends Readable { + addListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + addListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + addListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + addListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + addListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + addListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + addListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + addListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + addListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + addListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + addListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + addListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + addListener(event: "test:watch:drained", listener: () => void): this; + addListener(event: "test:watch:restarted", listener: () => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: "test:coverage", data: EventData.TestCoverage): boolean; + emit(event: "test:complete", data: EventData.TestComplete): boolean; + emit(event: "test:dequeue", data: EventData.TestDequeue): boolean; + emit(event: "test:diagnostic", data: EventData.TestDiagnostic): boolean; + emit(event: "test:enqueue", data: EventData.TestEnqueue): boolean; + emit(event: "test:fail", data: EventData.TestFail): boolean; + emit(event: "test:pass", data: EventData.TestPass): boolean; + emit(event: "test:plan", data: EventData.TestPlan): boolean; + emit(event: "test:start", data: EventData.TestStart): boolean; + emit(event: "test:stderr", data: EventData.TestStderr): boolean; + emit(event: "test:stdout", data: EventData.TestStdout): boolean; + emit(event: "test:summary", data: EventData.TestSummary): boolean; + emit(event: "test:watch:drained"): boolean; + emit(event: "test:watch:restarted"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + on(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + on(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + on(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + on(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + on(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + on(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + on(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + on(event: "test:start", listener: (data: EventData.TestStart) => void): this; + on(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + on(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + on(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + on(event: "test:watch:drained", listener: () => void): this; + on(event: "test:watch:restarted", listener: () => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + once(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + once(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + once(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + once(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + once(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + once(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + once(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + once(event: "test:start", listener: (data: EventData.TestStart) => void): this; + once(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + once(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + once(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + once(event: "test:watch:drained", listener: () => void): this; + once(event: "test:watch:restarted", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + prependListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + prependListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + prependListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + prependListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + prependListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + prependListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + prependListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + prependListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + prependListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + prependListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + prependListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + prependListener(event: "test:watch:drained", listener: () => void): this; + prependListener(event: "test:watch:restarted", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + prependOnceListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + prependOnceListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + prependOnceListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + prependOnceListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + prependOnceListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + prependOnceListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + prependOnceListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + prependOnceListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + prependOnceListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + prependOnceListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + prependOnceListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + prependOnceListener(event: "test:watch:drained", listener: () => void): this; + prependOnceListener(event: "test:watch:restarted", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } + namespace EventData { + interface Error extends globalThis.Error { + cause: globalThis.Error; + } + interface LocationInfo { + /** + * The column number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + column?: number; + /** + * The path of the test file, `undefined` if test was run through the REPL. + */ + file?: string; + /** + * The line number where the test is defined, or `undefined` if the test was run through the REPL. + */ + line?: number; + } + interface TestDiagnostic extends LocationInfo { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The severity level of the diagnostic message. + * Possible values are: + * * `'info'`: Informational messages. + * * `'warn'`: Warnings. + * * `'error'`: Errors. + */ + level: "info" | "warn" | "error"; + } + interface TestCoverage { + /** + * An object containing the coverage report. + */ + summary: { + /** + * An array of coverage reports for individual files. + */ + files: Array<{ + /** + * The absolute path of the file. + */ + path: string; + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + /** + * An array of functions representing function coverage. + */ + functions: Array<{ + /** + * The name of the function. + */ + name: string; + /** + * The line number where the function is defined. + */ + line: number; + /** + * The number of times the function was called. + */ + count: number; + }>; + /** + * An array of branches representing branch coverage. + */ + branches: Array<{ + /** + * The line number where the branch is defined. + */ + line: number; + /** + * The number of times the branch was taken. + */ + count: number; + }>; + /** + * An array of lines representing line numbers and the number of times they were covered. + */ + lines: Array<{ + /** + * The line number. + */ + line: number; + /** + * The number of times the line was covered. + */ + count: number; + }>; + }>; + /** + * An object containing whether or not the coverage for + * each coverage type. + * @since v22.9.0 + */ + thresholds: { + /** + * The function coverage threshold. + */ + function: number; + /** + * The branch coverage threshold. + */ + branch: number; + /** + * The line coverage threshold. + */ + line: number; + }; + /** + * An object containing a summary of coverage for all files. + */ + totals: { + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + }; + /** + * The working directory when code coverage began. This + * is useful for displaying relative path names in case + * the tests changed the working directory of the Node.js process. + */ + workingDirectory: string; + }; + /** + * The nesting level of the test. + */ + nesting: number; + } + interface TestComplete extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * Whether the test passed or not. + */ + passed: boolean; + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test if it did not pass. + */ + error?: Error; + /** + * The type of the test, used to denote whether this is a suite. + */ + type?: "suite" | "test"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestDequeue extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; + } + interface TestEnqueue extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; + } + interface TestFail extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test. + */ + error: Error; + /** + * The type of the test, used to denote whether this is a suite. + * @since v20.0.0, v19.9.0, v18.17.0 + */ + type?: "suite" | "test"; + /** + * The attempt number of the test run, + * present only when using the `--test-rerun-failures` flag. + * @since v24.7.0 + */ + attempt?: number; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestPass extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The type of the test, used to denote whether this is a suite. + * @since 20.0.0, 19.9.0, 18.17.0 + */ + type?: "suite" | "test"; + /** + * The attempt number of the test run, + * present only when using the `--test-rerun-failures` flag. + * @since v24.7.0 + */ + attempt?: number; + /** + * The attempt number the test passed on, + * present only when using the `--test-rerun-failures` flag. + * @since v24.7.0 + */ + passed_on_attempt?: number; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestPlan extends LocationInfo { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; + } + interface TestStart extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + } + interface TestStderr { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stderr`. + */ + message: string; + } + interface TestStdout { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stdout`. + */ + message: string; + } + interface TestSummary { + /** + * An object containing the counts of various test results. + */ + counts: { + /** + * The total number of cancelled tests. + */ + cancelled: number; + /** + * The total number of passed tests. + */ + passed: number; + /** + * The total number of skipped tests. + */ + skipped: number; + /** + * The total number of suites run. + */ + suites: number; + /** + * The total number of tests run, excluding suites. + */ + tests: number; + /** + * The total number of TODO tests. + */ + todo: number; + /** + * The total number of top level tests and suites. + */ + topLevel: number; + }; + /** + * The duration of the test run in milliseconds. + */ + duration_ms: number; + /** + * The path of the test file that generated the + * summary. If the summary corresponds to multiple files, this value is + * `undefined`. + */ + file: string | undefined; + /** + * Indicates whether or not the test run is considered + * successful or not. If any error condition occurs, such as a failing test or + * unmet coverage threshold, this value will be set to `false`. + */ + success: boolean; + } + } + /** + * An instance of `TestContext` is passed to each test function in order to + * interact with the test runner. However, the `TestContext` constructor is not + * exposed as part of the API. + * @since v18.0.0, v16.17.0 + */ + interface TestContext { + /** + * An object containing assertion methods bound to the test context. + * The top-level functions from the `node:assert` module are exposed here for the purpose of creating test plans. + * + * **Note:** Some of the functions from `node:assert` contain type assertions. If these are called via the + * TestContext `assert` object, then the context parameter in the test's function signature **must be explicitly typed** + * (ie. the parameter must have a type annotation), otherwise an error will be raised by the TypeScript compiler: + * ```ts + * import { test, type TestContext } from 'node:test'; + * + * // The test function's context parameter must have a type annotation. + * test('example', (t: TestContext) => { + * t.assert.deepStrictEqual(actual, expected); + * }); + * + * // Omitting the type annotation will result in a compilation error. + * test('example', t => { + * t.assert.deepStrictEqual(actual, expected); // Error: 't' needs an explicit type annotation. + * }); + * ``` + * @since v22.2.0, v20.15.0 + */ + readonly assert: TestContextAssert; + readonly attempt: number; + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v20.1.0, v18.17.0 + */ + before(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running before each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to write diagnostics to the output. Any diagnostic + * information is included at the end of the test's results. This function does + * not return a value. + * + * ```js + * test('top level test', (t) => { + * t.diagnostic('A diagnostic message'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Message to be reported. + */ + diagnostic(message: string): void; + /** + * The absolute path of the test file that created the current test. If a test file imports + * additional modules that generate tests, the imported tests will return the path of the root test file. + * @since v22.6.0 + */ + readonly filePath: string | undefined; + /** + * The name of the test and each of its ancestors, separated by `>`. + * @since v22.3.0 + */ + readonly fullName: string; + /** + * The name of the test. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * This function is used to set the number of assertions and subtests that are expected to run + * within the test. If the number of assertions and subtests that run does not match the + * expected count, the test will fail. + * + * > Note: To make sure assertions are tracked, `t.assert` must be used instead of `assert` directly. + * + * ```js + * test('top level test', (t) => { + * t.plan(2); + * t.assert.ok('some relevant assertion here'); + * t.test('subtest', () => {}); + * }); + * ``` + * + * When working with asynchronous code, the `plan` function can be used to ensure that the + * correct number of assertions are run: + * + * ```js + * test('planning with streams', (t, done) => { + * function* generate() { + * yield 'a'; + * yield 'b'; + * yield 'c'; + * } + * const expected = ['a', 'b', 'c']; + * t.plan(expected.length); + * const stream = Readable.from(generate()); + * stream.on('data', (chunk) => { + * t.assert.strictEqual(chunk, expected.shift()); + * }); + * + * stream.on('end', () => { + * done(); + * }); + * }); + * ``` + * + * When using the `wait` option, you can control how long the test will wait for the expected assertions. + * For example, setting a maximum wait time ensures that the test will wait for asynchronous assertions + * to complete within the specified timeframe: + * + * ```js + * test('plan with wait: 2000 waits for async assertions', (t) => { + * t.plan(1, { wait: 2000 }); // Waits for up to 2 seconds for the assertion to complete. + * + * const asyncActivity = () => { + * setTimeout(() => { + * * t.assert.ok(true, 'Async assertion completed within the wait time'); + * }, 1000); // Completes after 1 second, within the 2-second wait time. + * }; + * + * asyncActivity(); // The test will pass because the assertion is completed in time. + * }); + * ``` + * + * Note: If a `wait` timeout is specified, it begins counting down only after the test function finishes executing. + * @since v22.2.0 + */ + plan(count: number, options?: TestContextPlanOptions): void; + /** + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that + * have the `only` option set. Otherwise, all tests are run. If Node.js was not + * started with the `--test-only` command-line option, this function is a + * no-op. + * + * ```js + * test('top level test', (t) => { + * // The test context can be set to run subtests with the 'only' option. + * t.runOnly(true); + * return Promise.all([ + * t.test('this subtest is now skipped'), + * t.test('this subtest is run', { only: true }), + * ]); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param shouldRunOnlyTests Whether or not to run `only` tests. + */ + runOnly(shouldRunOnlyTests: boolean): void; + /** + * ```js + * test('top level test', async (t) => { + * await fetch('some/uri', { signal: t.signal }); + * }); + * ``` + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + /** + * This function causes the test's output to indicate the test as skipped. If `message` is provided, it is included in the output. Calling `skip()` does + * not terminate execution of the test function. This function does not return a + * value. + * + * ```js + * test('top level test', (t) => { + * // Make sure to return here as well if the test contains additional logic. + * t.skip('this is skipped'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional skip message. + */ + skip(message?: string): void; + /** + * This function adds a `TODO` directive to the test's output. If `message` is + * provided, it is included in the output. Calling `todo()` does not terminate + * execution of the test function. This function does not return a value. + * + * ```js + * test('top level test', (t) => { + * // This test is marked as `TODO` + * t.todo('this is a todo'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional `TODO` message. + */ + todo(message?: string): void; + /** + * This function is used to create subtests under the current test. This function behaves in + * the same fashion as the top level {@link test} function. + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. This first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + /** + * This method polls a `condition` function until that function either returns + * successfully or the operation times out. + * @since v22.14.0 + * @param condition An assertion function that is invoked + * periodically until it completes successfully or the defined polling timeout + * elapses. Successful completion is defined as not throwing or rejecting. This + * function does not accept any arguments, and is allowed to return any value. + * @param options An optional configuration object for the polling operation. + * @returns Fulfilled with the value returned by `condition`. + */ + waitFor(condition: () => T, options?: TestContextWaitForOptions): Promise>; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; + } + interface TestContextAssert extends Pick { + /** + * This function serializes `value` and writes it to the file specified by `path`. + * + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.fileSnapshot({ value1: 1, value2: 2 }, './snapshots/snapshot.json'); + * }); + * ``` + * + * This function differs from `context.assert.snapshot()` in the following ways: + * + * * The snapshot file path is explicitly provided by the user. + * * Each snapshot file is limited to a single snapshot value. + * * No additional escaping is performed by the test runner. + * + * These differences allow snapshot files to better support features such as syntax + * highlighting. + * @since v22.14.0 + * @param value A value to serialize to a string. If Node.js was started with + * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--test-update-snapshots) + * flag, the serialized value is written to + * `path`. Otherwise, the serialized value is compared to the contents of the + * existing snapshot file. + * @param path The file where the serialized `value` is written. + * @param options Optional configuration options. + */ + fileSnapshot(value: any, path: string, options?: AssertSnapshotOptions): void; + /** + * This function implements assertions for snapshot testing. + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.snapshot({ value1: 1, value2: 2 }); + * }); + * + * test('snapshot test with custom serialization', (t) => { + * t.assert.snapshot({ value3: 3, value4: 4 }, { + * serializers: [(value) => JSON.stringify(value)] + * }); + * }); + * ``` + * @since v22.3.0 + * @param value A value to serialize to a string. If Node.js was started with + * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--test-update-snapshots) + * flag, the serialized value is written to + * the snapshot file. Otherwise, the serialized value is compared to the + * corresponding value in the existing snapshot file. + */ + snapshot(value: any, options?: AssertSnapshotOptions): void; + /** + * A custom assertion function registered with `assert.register()`. + */ + [name: string]: (...args: any[]) => void; + } + interface AssertSnapshotOptions { + /** + * An array of synchronous functions used to serialize `value` into a string. + * `value` is passed as the only argument to the first serializer function. + * The return value of each serializer is passed as input to the next serializer. + * Once all serializers have run, the resulting value is coerced to a string. + * + * If no serializers are provided, the test runner's default serializers are used. + */ + serializers?: ReadonlyArray<(value: any) => any> | undefined; + } + interface TestContextPlanOptions { + /** + * The wait time for the plan: + * * If `true`, the plan waits indefinitely for all assertions and subtests to run. + * * If `false`, the plan performs an immediate check after the test function completes, + * without waiting for any pending assertions or subtests. + * Any assertions or subtests that complete after this check will not be counted towards the plan. + * * If a number, it specifies the maximum wait time in milliseconds + * before timing out while waiting for expected assertions and subtests to be matched. + * If the timeout is reached, the test will fail. + * @default false + */ + wait?: boolean | number | undefined; + } + interface TestContextWaitForOptions { + /** + * The number of milliseconds to wait after an unsuccessful + * invocation of `condition` before trying again. + * @default 50 + */ + interval?: number | undefined; + /** + * The poll timeout in milliseconds. If `condition` has not + * succeeded by the time this elapses, an error occurs. + * @default 1000 + */ + timeout?: number | undefined; + } + /** + * An instance of `SuiteContext` is passed to each suite function in order to + * interact with the test runner. However, the `SuiteContext` constructor is not + * exposed as part of the API. + * @since v18.7.0, v16.17.0 + */ + interface SuiteContext { + /** + * The absolute path of the test file that created the current suite. If a test file imports + * additional modules that generate suites, the imported suites will return the path of the root test file. + * @since v22.6.0 + */ + readonly filePath: string | undefined; + /** + * The name of the suite and each of its ancestors, separated by `>`. + * @since v22.3.0, v20.16.0 + */ + readonly fullName: string; + /** + * The name of the suite. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + } + interface TestOptions { + /** + * If a number is provided, then that many tests would run in parallel. + * If truthy, it would run (number of cpu cores - 1) tests in parallel. + * For subtests, it will be `Infinity` tests in parallel. + * If falsy, it would only run one test at a time. + * If unspecified, subtests inherit this value from their parent. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * If truthy, and the test context is configured to run `only` tests, then this test will be + * run. Otherwise, the test is skipped. + * @default false + */ + only?: boolean | undefined; + /** + * Allows aborting an in-progress test. + * @since v18.8.0 + */ + signal?: AbortSignal | undefined; + /** + * If truthy, the test is skipped. If a string is provided, that string is displayed in the + * test results as the reason for skipping the test. + * @default false + */ + skip?: boolean | string | undefined; + /** + * A number of milliseconds the test will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + * @since v18.7.0 + */ + timeout?: number | undefined; + /** + * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in + * the test results as the reason why the test is `TODO`. + * @default false + */ + todo?: boolean | string | undefined; + /** + * The number of assertions and subtests expected to be run in the test. + * If the number of assertions run in the test does not match the number + * specified in the plan, the test will fail. + * @default undefined + * @since v22.2.0 + */ + plan?: number | undefined; + } + /** + * This function creates a hook that runs before executing a suite. + * + * ```js + * describe('tests', async () => { + * before(() => console.log('about to run some test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function before(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after executing a suite. + * + * ```js + * describe('tests', async () => { + * after(() => console.log('finished running tests')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function after(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs before each test in the current suite. + * + * ```js + * describe('tests', async () => { + * beforeEach(() => console.log('about to run a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after each test in the current suite. + * The `afterEach()` hook is run even if the test fails. + * + * ```js + * describe('tests', async () => { + * afterEach(() => console.log('finished running a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + /** + * The hook function. The first argument is the context in which the hook is called. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type HookFn = (c: TestContext | SuiteContext, done: (result?: any) => void) => any; + /** + * The hook function. The first argument is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type TestContextHookFn = (t: TestContext, done: (result?: any) => void) => any; + /** + * Configuration options for hooks. + * @since v18.8.0 + */ + interface HookOptions { + /** + * Allows aborting an in-progress hook. + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + } + interface MockFunctionOptions { + /** + * The number of times that the mock will use the behavior of `implementation`. + * Once the mock function has been called `times` times, + * it will automatically restore the behavior of `original`. + * This value must be an integer greater than zero. + * @default Infinity + */ + times?: number | undefined; + } + interface MockMethodOptions extends MockFunctionOptions { + /** + * If `true`, `object[methodName]` is treated as a getter. + * This option cannot be used with the `setter` option. + */ + getter?: boolean | undefined; + /** + * If `true`, `object[methodName]` is treated as a setter. + * This option cannot be used with the `getter` option. + */ + setter?: boolean | undefined; + } + type Mock = F & { + mock: MockFunctionContext; + }; + interface MockModuleOptions { + /** + * If false, each call to `require()` or `import()` generates a new mock module. + * If true, subsequent calls will return the same module mock, and the mock module is inserted into the CommonJS cache. + * @default false + */ + cache?: boolean | undefined; + /** + * The value to use as the mocked module's default export. + * + * If this value is not provided, ESM mocks do not include a default export. + * If the mock is a CommonJS or builtin module, this setting is used as the value of `module.exports`. + * If this value is not provided, CJS and builtin mocks use an empty object as the value of `module.exports`. + */ + defaultExport?: any; + /** + * An object whose keys and values are used to create the named exports of the mock module. + * + * If the mock is a CommonJS or builtin module, these values are copied onto `module.exports`. + * Therefore, if a mock is created with both named exports and a non-object default export, + * the mock will throw an exception when used as a CJS or builtin module. + */ + namedExports?: object | undefined; + } + /** + * The `MockTracker` class is used to manage mocking functionality. The test runner + * module provides a top level `mock` export which is a `MockTracker` instance. + * Each test also provides its own `MockTracker` instance via the test context's `mock` property. + * @since v19.1.0, v18.13.0 + */ + interface MockTracker { + /** + * This function is used to create a mock function. + * + * The following example creates a mock function that increments a counter by one + * on each invocation. The `times` option is used to modify the mock behavior such + * that the first two invocations add two to the counter instead of one. + * + * ```js + * test('mocks a counting function', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne, addTwo, { times: 2 }); + * + * assert.strictEqual(fn(), 2); + * assert.strictEqual(fn(), 4); + * assert.strictEqual(fn(), 5); + * assert.strictEqual(fn(), 6); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param original An optional function to create a mock on. + * @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and + * then restore the behavior of `original`. + * @param options Optional configuration options for the mock function. + * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked function. + */ + fn undefined>( + original?: F, + options?: MockFunctionOptions, + ): Mock; + fn undefined, Implementation extends Function = F>( + original?: F, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock; + /** + * This function is used to create a mock on an existing object method. The + * following example demonstrates how a mock is created on an existing object + * method. + * + * ```js + * test('spies on an object method', (t) => { + * const number = { + * value: 5, + * subtract(a) { + * return this.value - a; + * }, + * }; + * + * t.mock.method(number, 'subtract'); + * assert.strictEqual(number.subtract.mock.calls.length, 0); + * assert.strictEqual(number.subtract(3), 2); + * assert.strictEqual(number.subtract.mock.calls.length, 1); + * + * const call = number.subtract.mock.calls[0]; + * + * assert.deepStrictEqual(call.arguments, [3]); + * assert.strictEqual(call.result, 2); + * assert.strictEqual(call.error, undefined); + * assert.strictEqual(call.target, undefined); + * assert.strictEqual(call.this, number); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param object The object whose method is being mocked. + * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown. + * @param implementation An optional function used as the mock implementation for `object[methodName]`. + * @param options Optional configuration options for the mock method. + * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked method. + */ + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation: Implementation, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method( + object: MockedObject, + methodName: keyof MockedObject, + options: MockMethodOptions, + ): Mock; + method( + object: MockedObject, + methodName: keyof MockedObject, + implementation: Function, + options: MockMethodOptions, + ): Mock; + /** + * This function is syntax sugar for `MockTracker.method` with `options.getter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<() => MockedObject[MethodName]>; + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<(() => MockedObject[MethodName]) | Implementation>; + /** + * This function is syntax sugar for `MockTracker.method` with `options.setter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<(value: MockedObject[MethodName]) => void>; + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; + /** + * This function is used to mock the exports of ECMAScript modules, CommonJS modules, JSON modules, and + * Node.js builtin modules. Any references to the original module prior to mocking are not impacted. In + * order to enable module mocking, Node.js must be started with the + * [`--experimental-test-module-mocks`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--experimental-test-module-mocks) + * command-line flag. + * + * The following example demonstrates how a mock is created for a module. + * + * ```js + * test('mocks a builtin module in both module systems', async (t) => { + * // Create a mock of 'node:readline' with a named export named 'fn', which + * // does not exist in the original 'node:readline' module. + * const mock = t.mock.module('node:readline', { + * namedExports: { fn() { return 42; } }, + * }); + * + * let esmImpl = await import('node:readline'); + * let cjsImpl = require('node:readline'); + * + * // cursorTo() is an export of the original 'node:readline' module. + * assert.strictEqual(esmImpl.cursorTo, undefined); + * assert.strictEqual(cjsImpl.cursorTo, undefined); + * assert.strictEqual(esmImpl.fn(), 42); + * assert.strictEqual(cjsImpl.fn(), 42); + * + * mock.restore(); + * + * // The mock is restored, so the original builtin module is returned. + * esmImpl = await import('node:readline'); + * cjsImpl = require('node:readline'); + * + * assert.strictEqual(typeof esmImpl.cursorTo, 'function'); + * assert.strictEqual(typeof cjsImpl.cursorTo, 'function'); + * assert.strictEqual(esmImpl.fn, undefined); + * assert.strictEqual(cjsImpl.fn, undefined); + * }); + * ``` + * @since v22.3.0 + * @experimental + * @param specifier A string identifying the module to mock. + * @param options Optional configuration options for the mock module. + */ + module(specifier: string | URL, options?: MockModuleOptions): MockModuleContext; + /** + * Creates a mock for a property value on an object. This allows you to track and control access to a specific property, + * including how many times it is read (getter) or written (setter), and to restore the original value after mocking. + * + * ```js + * test('mocks a property value', (t) => { + * const obj = { foo: 42 }; + * const prop = t.mock.property(obj, 'foo', 100); + * + * assert.strictEqual(obj.foo, 100); + * assert.strictEqual(prop.mock.accessCount(), 1); + * assert.strictEqual(prop.mock.accesses[0].type, 'get'); + * assert.strictEqual(prop.mock.accesses[0].value, 100); + * + * obj.foo = 200; + * assert.strictEqual(prop.mock.accessCount(), 2); + * assert.strictEqual(prop.mock.accesses[1].type, 'set'); + * assert.strictEqual(prop.mock.accesses[1].value, 200); + * + * prop.mock.restore(); + * assert.strictEqual(obj.foo, 42); + * }); + * ``` + * @since v24.3.0 + * @param object The object whose value is being mocked. + * @param propertyName The identifier of the property on `object` to mock. + * @param value An optional value used as the mock value + * for `object[propertyName]`. **Default:** The original property value. + * @returns A proxy to the mocked object. The mocked object contains a + * special `mock` property, which is an instance of [`MockPropertyContext`][], and + * can be used for inspecting and changing the behavior of the mocked property. + */ + property< + MockedObject extends object, + PropertyName extends keyof MockedObject, + >( + object: MockedObject, + property: PropertyName, + value?: MockedObject[PropertyName], + ): MockedObject & { mock: MockPropertyContext }; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker` and disassociates the mocks from the `MockTracker` instance. Once disassociated, the mocks can still be used, but the `MockTracker` instance can no longer be + * used to reset their behavior or + * otherwise interact with them. + * + * After each test completes, this function is called on the test context's `MockTracker`. If the global `MockTracker` is used extensively, calling this + * function manually is recommended. + * @since v19.1.0, v18.13.0 + */ + reset(): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does + * not disassociate the mocks from the `MockTracker` instance. + * @since v19.1.0, v18.13.0 + */ + restoreAll(): void; + readonly timers: MockTimers; + } + const mock: MockTracker; + interface MockFunctionCall< + F extends Function, + ReturnType = F extends (...args: any) => infer T ? T + : F extends abstract new(...args: any) => infer T ? T + : unknown, + Args = F extends (...args: infer Y) => any ? Y + : F extends abstract new(...args: infer Y) => any ? Y + : unknown[], + > { + /** + * An array of the arguments passed to the mock function. + */ + arguments: Args; + /** + * If the mocked function threw then this property contains the thrown value. + */ + error: unknown | undefined; + /** + * The value returned by the mocked function. + * + * If the mocked function threw, it will be `undefined`. + */ + result: ReturnType | undefined; + /** + * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation. + */ + stack: Error; + /** + * If the mocked function is a constructor, this field contains the class being constructed. + * Otherwise this will be `undefined`. + */ + target: F extends abstract new(...args: any) => any ? F : undefined; + /** + * The mocked function's `this` value. + */ + this: unknown; + } + /** + * The `MockFunctionContext` class is used to inspect or manipulate the behavior of + * mocks created via the `MockTracker` APIs. + * @since v19.1.0, v18.13.0 + */ + interface MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the + * mock. Each entry in the array is an object with the following properties. + * @since v19.1.0, v18.13.0 + */ + readonly calls: MockFunctionCall[]; + /** + * This function returns the number of times that this mock has been invoked. This + * function is more efficient than checking `ctx.calls.length` because `ctx.calls` is a getter that creates a copy of the internal call tracking array. + * @since v19.1.0, v18.13.0 + * @return The number of times that this mock has been invoked. + */ + callCount(): number; + /** + * This function is used to change the behavior of an existing mock. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, and then changes the mock implementation to a different function. + * + * ```js + * test('changes a mock behavior', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementation(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 5); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: F): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onCall` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, changes the mock implementation to a different function for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementationOnce(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 4); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. + * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. + */ + mockImplementationOnce(implementation: F, onCall?: number): void; + /** + * Resets the call history of the mock function. + * @since v19.3.0, v18.13.0 + */ + resetCalls(): void; + /** + * Resets the implementation of the mock function to its original behavior. The + * mock can still be used after calling this function. + * @since v19.1.0, v18.13.0 + */ + restore(): void; + } + /** + * @since v22.3.0 + * @experimental + */ + interface MockModuleContext { + /** + * Resets the implementation of the mock module. + * @since v22.3.0 + */ + restore(): void; + } + /** + * @since v24.3.0 + */ + class MockPropertyContext { + /** + * A getter that returns a copy of the internal array used to track accesses (get/set) to + * the mocked property. Each entry in the array is an object with the following properties: + */ + readonly accesses: Array<{ + type: "get" | "set"; + value: PropertyType; + stack: Error; + }>; + /** + * This function returns the number of times that the property was accessed. + * This function is more efficient than checking `ctx.accesses.length` because + * `ctx.accesses` is a getter that creates a copy of the internal access tracking array. + * @returns The number of times that the property was accessed (read or written). + */ + accessCount(): number; + /** + * This function is used to change the value returned by the mocked property getter. + * @param value The new value to be set as the mocked property value. + */ + mockImplementation(value: PropertyType): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onAccess` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.property()`, calls the + * mock property, changes the mock implementation to a different value for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * const obj = { foo: 1 }; + * + * const prop = t.mock.property(obj, 'foo', 5); + * + * assert.strictEqual(obj.foo, 5); + * prop.mock.mockImplementationOnce(25); + * assert.strictEqual(obj.foo, 25); + * assert.strictEqual(obj.foo, 5); + * }); + * ``` + * @param value The value to be used as the mock's + * implementation for the invocation number specified by `onAccess`. + * @param onAccess The invocation number that will use `value`. If + * the specified invocation has already occurred then an exception is thrown. + * **Default:** The number of the next invocation. + */ + mockImplementationOnce(value: PropertyType, onAccess?: number): void; + /** + * Resets the access history of the mocked property. + */ + resetAccesses(): void; + /** + * Resets the implementation of the mock property to its original behavior. The + * mock can still be used after calling this function. + */ + restore(): void; + } + interface MockTimersOptions { + apis: ReadonlyArray<"setInterval" | "setTimeout" | "setImmediate" | "Date">; + now?: number | Date | undefined; + } + /** + * Mocking timers is a technique commonly used in software testing to simulate and + * control the behavior of timers, such as `setInterval` and `setTimeout`, + * without actually waiting for the specified time intervals. + * + * The MockTimers API also allows for mocking of the `Date` constructor and + * `setImmediate`/`clearImmediate` functions. + * + * The `MockTracker` provides a top-level `timers` export + * which is a `MockTimers` instance. + * @since v20.4.0 + */ + interface MockTimers { + /** + * Enables timer mocking for the specified timers. + * + * **Note:** When you enable mocking for a specific timer, its associated + * clear function will also be implicitly mocked. + * + * **Note:** Mocking `Date` will affect the behavior of the mocked timers + * as they use the same internal clock. + * + * Example usage without setting initial time: + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1234 }); + * ``` + * + * The above example enables mocking for the `Date` constructor, `setInterval` timer and + * implicitly mocks the `clearInterval` function. Only the `Date` constructor from `globalThis`, + * `setInterval` and `clearInterval` functions from `node:timers`, `node:timers/promises`, and `globalThis` will be mocked. + * + * Example usage with initial time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: 1000 }); + * ``` + * + * Example usage with initial Date object as time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: new Date() }); + * ``` + * + * Alternatively, if you call `mock.timers.enable()` without any parameters: + * + * All timers (`'setInterval'`, `'clearInterval'`, `'Date'`, `'setImmediate'`, `'clearImmediate'`, `'setTimeout'`, and `'clearTimeout'`) + * will be mocked. + * + * The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout` functions from `node:timers`, `node:timers/promises`, + * and `globalThis` will be mocked. + * The `Date` constructor from `globalThis` will be mocked. + * + * If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is `January 1st, 1970, 00:00:00 UTC`. You can + * set an initial date by passing a now property to the `.enable()` method. This value will be used as the initial date for the mocked Date + * object. It can either be a positive integer, or another Date object. + * @since v20.4.0 + */ + enable(options?: MockTimersOptions): void; + /** + * Sets the current Unix timestamp that will be used as reference for any mocked + * `Date` objects. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('runAll functions following the given order', (context) => { + * const now = Date.now(); + * const setTime = 1000; + * // Date.now is not mocked + * assert.deepStrictEqual(Date.now(), now); + * + * context.mock.timers.enable({ apis: ['Date'] }); + * context.mock.timers.setTime(setTime); + * // Date.now is now 1000 + * assert.strictEqual(Date.now(), setTime); + * }); + * ``` + * @since v21.2.0, v20.11.0 + */ + setTime(milliseconds: number): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTimers` instance and disassociates the mocks + * from the `MockTracker` instance. + * + * **Note:** After each test completes, this function is called on + * the test context's `MockTracker`. + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.reset(); + * ``` + * @since v20.4.0 + */ + reset(): void; + /** + * Advances time for all mocked timers. + * + * **Note:** This diverges from how `setTimeout` in Node.js behaves and accepts + * only positive numbers. In Node.js, `setTimeout` with negative numbers is + * only supported for web compatibility reasons. + * + * The following example mocks a `setTimeout` function and + * by using `.tick` advances in + * time triggering all pending timers. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Alternativelly, the `.tick` function can be called many times + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * const nineSecs = 9000; + * setTimeout(fn, nineSecs); + * + * const twoSeconds = 3000; + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Advancing time using `.tick` will also advance the time for any `Date` object + * created after the mock was enabled (if `Date` was also set to be mocked). + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * assert.strictEqual(Date.now(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * assert.strictEqual(fn.mock.callCount(), 1); + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * @since v20.4.0 + */ + tick(milliseconds: number): void; + /** + * Triggers all pending mocked timers immediately. If the `Date` object is also + * mocked, it will also advance the `Date` object to the furthest timer's time. + * + * The example below triggers all pending timers immediately, + * causing them to execute without any delay. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('runAll functions following the given order', (context) => { + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * const results = []; + * setTimeout(() => results.push(1), 9999); + * + * // Notice that if both timers have the same timeout, + * // the order of execution is guaranteed + * setTimeout(() => results.push(3), 8888); + * setTimeout(() => results.push(2), 8888); + * + * assert.deepStrictEqual(results, []); + * + * context.mock.timers.runAll(); + * assert.deepStrictEqual(results, [3, 2, 1]); + * // The Date object is also advanced to the furthest timer's time + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * + * **Note:** The `runAll()` function is specifically designed for + * triggering timers in the context of timer mocking. + * It does not have any effect on real-time system + * clocks or actual timers outside of the mocking environment. + * @since v20.4.0 + */ + runAll(): void; + /** + * Calls {@link MockTimers.reset()}. + */ + [Symbol.dispose](): void; + } + /** + * An object whose methods are used to configure available assertions on the + * `TestContext` objects in the current process. The methods from `node:assert` + * and snapshot testing functions are available by default. + * + * It is possible to apply the same configuration to all files by placing common + * configuration code in a module + * preloaded with `--require` or `--import`. + * @since v22.14.0 + */ + namespace assert { + /** + * Defines a new assertion function with the provided name and function. If an + * assertion already exists with the same name, it is overwritten. + * @since v22.14.0 + */ + function register(name: string, fn: (this: TestContext, ...args: any[]) => void): void; + } + /** + * @since v22.3.0 + */ + namespace snapshot { + /** + * This function is used to customize the default serialization mechanism used by the test runner. + * + * By default, the test runner performs serialization by calling `JSON.stringify(value, null, 2)` on the provided value. + * `JSON.stringify()` does have limitations regarding circular structures and supported data types. + * If a more robust serialization mechanism is required, this function should be used to specify a list of custom serializers. + * + * Serializers are called in order, with the output of the previous serializer passed as input to the next. + * The final result must be a string value. + * @since v22.3.0 + * @param serializers An array of synchronous functions used as the default serializers for snapshot tests. + */ + function setDefaultSnapshotSerializers(serializers: ReadonlyArray<(value: any) => any>): void; + /** + * This function is used to set a custom resolver for the location of the snapshot file used for snapshot testing. + * By default, the snapshot filename is the same as the entry point filename with `.snapshot` appended. + * @since v22.3.0 + * @param fn A function used to compute the location of the snapshot file. + * The function receives the path of the test file as its only argument. If the + * test is not associated with a file (for example in the REPL), the input is + * undefined. `fn()` must return a string specifying the location of the snapshot file. + */ + function setResolveSnapshotPath(fn: (path: string | undefined) => string): void; + } + } + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + export = test; +} + +/** + * The `node:test/reporters` module exposes the builtin-reporters for `node:test`. + * To access it: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * @since v19.9.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/test/reporters.js) + */ +declare module "node:test/reporters" { + import { Transform, TransformOptions } from "node:stream"; + import { EventData } from "node:test"; + + type TestEvent = + | { type: "test:coverage"; data: EventData.TestCoverage } + | { type: "test:complete"; data: EventData.TestComplete } + | { type: "test:dequeue"; data: EventData.TestDequeue } + | { type: "test:diagnostic"; data: EventData.TestDiagnostic } + | { type: "test:enqueue"; data: EventData.TestEnqueue } + | { type: "test:fail"; data: EventData.TestFail } + | { type: "test:pass"; data: EventData.TestPass } + | { type: "test:plan"; data: EventData.TestPlan } + | { type: "test:start"; data: EventData.TestStart } + | { type: "test:stderr"; data: EventData.TestStderr } + | { type: "test:stdout"; data: EventData.TestStdout } + | { type: "test:summary"; data: EventData.TestSummary } + | { type: "test:watch:drained"; data: undefined } + | { type: "test:watch:restarted"; data: undefined }; + type TestEventGenerator = AsyncGenerator; + + interface ReporterConstructorWrapper Transform> { + new(...args: ConstructorParameters): InstanceType; + (...args: ConstructorParameters): InstanceType; + } + + /** + * The `dot` reporter outputs the test results in a compact format, + * where each passing test is represented by a `.`, + * and each failing test is represented by a `X`. + * @since v20.0.0 + */ + function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>; + /** + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + * @since v20.0.0 + */ + function tap(source: TestEventGenerator): AsyncGenerator; + class SpecReporter extends Transform { + constructor(); + } + /** + * The `spec` reporter outputs the test results in a human-readable format. + * @since v20.0.0 + */ + const spec: ReporterConstructorWrapper; + /** + * The `junit` reporter outputs test results in a jUnit XML format. + * @since v21.0.0 + */ + function junit(source: TestEventGenerator): AsyncGenerator; + class LcovReporter extends Transform { + constructor(opts?: Omit); + } + /** + * The `lcov` reporter outputs test coverage when used with the + * [`--experimental-test-coverage`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--experimental-test-coverage) flag. + * @since v22.0.0 + */ + const lcov: ReporterConstructorWrapper; + + export { dot, junit, lcov, spec, tap, TestEvent }; +} diff --git a/tools/ui/node_modules/@types/node/timers.d.ts b/tools/ui/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..30a91c0644e9b8992ba8aaa16efd24d8ef61668b --- /dev/null +++ b/tools/ui/node_modules/@types/node/timers.d.ts @@ -0,0 +1,285 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to import `node:timers` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/timers.js) + */ +declare module "timers" { + import { Abortable } from "node:events"; + import * as promises from "node:timers/promises"; + export interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + global { + namespace NodeJS { + /** + * This object is created internally and is returned from `setImmediate()`. It + * can be passed to `clearImmediate()` in order to cancel the scheduled + * actions. + * + * By default, when an immediate is scheduled, the Node.js event loop will continue + * running as long as the immediate is active. The `Immediate` object returned by + * `setImmediate()` exports both `immediate.ref()` and `immediate.unref()` + * functions that can be used to control this default behavior. + */ + interface Immediate extends RefCounted, Disposable { + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the + * `Immediate` is active. Calling `immediate.ref()` multiple times will have no + * effect. + * + * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary + * to call `immediate.ref()` unless `immediate.unref()` had been called previously. + * @since v9.7.0 + * @returns a reference to `immediate` + */ + ref(): this; + /** + * When called, the active `Immediate` object will not require the Node.js event + * loop to remain active. If there is no other activity keeping the event loop + * running, the process may exit before the `Immediate` object's callback is + * invoked. Calling `immediate.unref()` multiple times will have no effect. + * @since v9.7.0 + * @returns a reference to `immediate` + */ + unref(): this; + /** + * Cancels the immediate. This is similar to calling `clearImmediate()`. + * @since v20.5.0, v18.18.0 + */ + [Symbol.dispose](): void; + _onImmediate(...args: any[]): void; + } + // Legacy interface used in Node.js v9 and prior + // TODO: remove in a future major version bump + /** @deprecated Use `NodeJS.Timeout` instead. */ + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + /** + * This object is created internally and is returned from `setTimeout()` and + * `setInterval()`. It can be passed to either `clearTimeout()` or + * `clearInterval()` in order to cancel the scheduled actions. + * + * By default, when a timer is scheduled using either `setTimeout()` or + * `setInterval()`, the Node.js event loop will continue running as long as the + * timer is active. Each of the `Timeout` objects returned by these functions + * export both `timeout.ref()` and `timeout.unref()` functions that can be used to + * control this default behavior. + */ + interface Timeout extends RefCounted, Disposable, Timer { + /** + * Cancels the timeout. + * @since v0.9.1 + * @legacy Use `clearTimeout()` instead. + * @returns a reference to `timeout` + */ + close(): this; + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the + * `Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. + * + * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary + * to call `timeout.ref()` unless `timeout.unref()` had been called previously. + * @since v0.9.1 + * @returns a reference to `timeout` + */ + ref(): this; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @returns a reference to `timeout` + */ + refresh(): this; + /** + * When called, the active `Timeout` object will not require the Node.js event loop + * to remain active. If there is no other activity keeping the event loop running, + * the process may exit before the `Timeout` object's callback is invoked. Calling + * `timeout.unref()` multiple times will have no effect. + * @since v0.9.1 + * @returns a reference to `timeout` + */ + unref(): this; + /** + * Coerce a `Timeout` to a primitive. The primitive can be used to + * clear the `Timeout`. The primitive can only be used in the + * same thread where the timeout was created. Therefore, to use it + * across `worker_threads` it must first be passed to the correct + * thread. This allows enhanced compatibility with browser + * `setTimeout()` and `setInterval()` implementations. + * @since v14.9.0, v12.19.0 + */ + [Symbol.toPrimitive](): number; + /** + * Cancels the timeout. + * @since v20.5.0, v18.18.0 + */ + [Symbol.dispose](): void; + _onTimeout(...args: any[]): void; + } + } + /** + * Schedules the "immediate" execution of the `callback` after I/O events' + * callbacks. + * + * When multiple calls to `setImmediate()` are made, the `callback` functions are + * queued for execution in the order in which they are created. The entire callback + * queue is processed every event loop iteration. If an immediate timer is queued + * from inside an executing callback, that timer will not be triggered until the + * next event loop iteration. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setImmediate()`. + * @since v0.9.1 + * @param callback The function to call at the end of this turn of + * the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout) + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearImmediate()` + */ + function setImmediate( + callback: (...args: TArgs) => void, + ...args: TArgs + ): NodeJS.Immediate; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setImmediate(callback: (_: void) => void): NodeJS.Immediate; + namespace setImmediate { + import __promisify__ = promises.setImmediate; + export { __promisify__ }; + } + /** + * Schedules repeated execution of `callback` every `delay` milliseconds. + * + * When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay` + * will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setInterval()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param delay The number of milliseconds to wait before calling the + * `callback`. **Default:** `1`. + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearInterval()` + */ + function setInterval( + callback: (...args: TArgs) => void, + delay?: number, + ...args: TArgs + ): NodeJS.Timeout; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setInterval(callback: (_: void) => void, delay?: number): NodeJS.Timeout; + /** + * Schedules execution of a one-time `callback` after `delay` milliseconds. + * + * The `callback` will likely not be invoked in precisely `delay` milliseconds. + * Node.js makes no guarantees about the exact timing of when callbacks will fire, + * nor of their ordering. The callback will be called as close as possible to the + * time specified. + * + * When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay` + * will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setTimeout()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param delay The number of milliseconds to wait before calling the + * `callback`. **Default:** `1`. + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearTimeout()` + */ + function setTimeout( + callback: (...args: TArgs) => void, + delay?: number, + ...args: TArgs + ): NodeJS.Timeout; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setTimeout(callback: (_: void) => void, delay?: number): NodeJS.Timeout; + namespace setTimeout { + import __promisify__ = promises.setTimeout; + export { __promisify__ }; + } + /** + * Cancels an `Immediate` object created by `setImmediate()`. + * @since v0.9.1 + * @param immediate An `Immediate` object as returned by `setImmediate()`. + */ + function clearImmediate(immediate: NodeJS.Immediate | undefined): void; + /** + * Cancels a `Timeout` object created by `setInterval()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by `setInterval()` + * or the primitive of the `Timeout` object as a string or a number. + */ + function clearInterval(timeout: NodeJS.Timeout | string | number | undefined): void; + /** + * Cancels a `Timeout` object created by `setTimeout()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by `setTimeout()` + * or the primitive of the `Timeout` object as a string or a number. + */ + function clearTimeout(timeout: NodeJS.Timeout | string | number | undefined): void; + /** + * The `queueMicrotask()` method queues a microtask to invoke `callback`. If + * `callback` throws an exception, the `process` object `'uncaughtException'` + * event will be emitted. + * + * The microtask queue is managed by V8 and may be used in a similar manner to + * the `process.nextTick()` queue, which is managed by Node.js. The + * `process.nextTick()` queue is always processed before the microtask queue + * within each turn of the Node.js event loop. + * @since v11.0.0 + * @param callback Function to be queued. + */ + function queueMicrotask(callback: () => void): void; + } + import clearImmediate = globalThis.clearImmediate; + import clearInterval = globalThis.clearInterval; + import clearTimeout = globalThis.clearTimeout; + import setImmediate = globalThis.setImmediate; + import setInterval = globalThis.setInterval; + import setTimeout = globalThis.setTimeout; + export { clearImmediate, clearInterval, clearTimeout, promises, setImmediate, setInterval, setTimeout }; +} +declare module "node:timers" { + export * from "timers"; +} diff --git a/tools/ui/node_modules/@types/node/timers/promises.d.ts b/tools/ui/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7ad2b297badc85c50997b6bb926423510b5e7780 --- /dev/null +++ b/tools/ui/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,108 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via + * `require('node:timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'node:timers/promises'; + * ``` + * @since v15.0.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/timers/promises.js) + */ +declare module "timers/promises" { + import { TimerOptions } from "node:timers"; + /** + * ```js + * import { + * setTimeout, + * } from 'node:timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param delay The number of milliseconds to wait before fulfilling the + * promise. **Default:** `1`. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'node:timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * If `ref` is `true`, you need to call `next()` of async iterator explicitly + * or implicitly to keep the event loop alive. + * + * ```js + * import { + * setInterval, + * } from 'node:timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + * @param delay The number of milliseconds to wait between iterations. + * **Default:** `1`. + * @param value A value with which the iterator returns. + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): NodeJS.AsyncIterator; + interface Scheduler { + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification + * being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.wait(delay, options)` is roughly equivalent + * to calling `timersPromises.setTimeout(delay, undefined, options)` except that + * the `ref` option is not supported. + * + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * @since v17.3.0, v16.14.0 + * @experimental + * @param delay The number of milliseconds to wait before resolving the + * promise. + */ + wait(delay: number, options?: { signal?: AbortSignal }): Promise; + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification + * being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.yield()` is equivalent to calling + * `timersPromises.setImmediate()` with no arguments. + * @since v17.3.0, v16.14.0 + * @experimental + */ + yield(): Promise; + } + const scheduler: Scheduler; +} +declare module "node:timers/promises" { + export * from "timers/promises"; +} diff --git a/tools/ui/node_modules/@types/node/tls.d.ts b/tools/ui/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..658c0135e85498cedfe245f8597d178418d3d017 --- /dev/null +++ b/tools/ui/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1279 @@ +/** + * The `node:tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * import tls from 'node:tls'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/tls.js) + */ +declare module "tls" { + import { NonSharedBuffer } from "node:buffer"; + import { X509Certificate } from "node:crypto"; + import * as net from "node:net"; + import * as stream from "stream"; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate extends NodeJS.Dict { + /** + * Country code. + */ + C?: string | string[]; + /** + * Street. + */ + ST?: string | string[]; + /** + * Locality. + */ + L?: string | string[]; + /** + * Organization. + */ + O?: string | string[]; + /** + * Organizational unit. + */ + OU?: string | string[]; + /** + * Common name. + */ + CN?: string | string[]; + } + interface PeerCertificate { + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ + raw: NonSharedBuffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: NonSharedBuffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve, if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; + } + interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions); + /** + * This property is `true` if the peer certificate was signed by one of the CAs + * specified when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: true; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * String containing the server name requested via SNI (Server Name Indication) TLS extension. + */ + servername: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example, a TLSv1.2 protocol with AES256-SHA cipher: + * + * ```json + * { + * "name": "AES256-SHA", + * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", + * "version": "SSLv3" + * } + * ``` + * + * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): NonSharedBuffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): NonSharedBuffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): NonSharedBuffer | undefined; + /** + * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): NonSharedBuffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void, + ): undefined | boolean; + /** + * The `tlsSocket.setKeyCert()` method sets the private key and certificate to use for the socket. + * This is mainly useful if you wish to select a server certificate from a TLS server's `ALPNCallback`. + * @since v22.5.0, v20.17.0 + * @param context An object containing at least `key` and `cert` properties from the {@link createSecureContext()} `options`, + * or a TLS context object created with {@link createSecureContext()} itself. + */ + setKeyCert(context: SecureContextOptions | SecureContext): void; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by + * OpenSSL's `SSL_trace()` function, the format is undocumented, can change + * without notice, and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * /* + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): NonSharedBuffer; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this; + addListener(event: "secure", listener: () => void): this; + addListener(event: "secureConnect", listener: () => void): this; + addListener(event: "session", listener: (session: NonSharedBuffer) => void): this; + addListener(event: "keylog", listener: (line: NonSharedBuffer) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: NonSharedBuffer): boolean; + emit(event: "secure"): boolean; + emit(event: "secureConnect"): boolean; + emit(event: "session", session: NonSharedBuffer): boolean; + emit(event: "keylog", line: NonSharedBuffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this; + on(event: "secure", listener: () => void): this; + on(event: "secureConnect", listener: () => void): this; + on(event: "session", listener: (session: NonSharedBuffer) => void): this; + on(event: "keylog", listener: (line: NonSharedBuffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this; + once(event: "secure", listener: () => void): this; + once(event: "secureConnect", listener: () => void): this; + once(event: "session", listener: (session: NonSharedBuffer) => void): this; + once(event: "keylog", listener: (line: NonSharedBuffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this; + prependListener(event: "secure", listener: () => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + prependListener(event: "session", listener: (session: NonSharedBuffer) => void): this; + prependListener(event: "keylog", listener: (line: NonSharedBuffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this; + prependOnceListener(event: "secure", listener: () => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + prependOnceListener(event: "session", listener: (session: NonSharedBuffer) => void): this; + prependOnceListener(event: "keylog", listener: (line: NonSharedBuffer) => void): this; + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: readonly string[] | NodeJS.ArrayBufferView | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication. + */ + requestOCSP?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?: ((socket: TLSSocket, identity: string) => NodeJS.ArrayBufferView | null) | undefined; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: NodeJS.ArrayBufferView; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?: ((hint: string | null) => PSKCallbackNegotation | null) | undefined; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created + * with {@link createSecureContext} itself. + */ + addContext(hostname: string, context: SecureContextOptions | SecureContext): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): NonSharedBuffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit( + event: "newSession", + sessionId: NonSharedBuffer, + sessionData: NonSharedBuffer, + callback: () => void, + ): boolean; + emit( + event: "OCSPRequest", + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ): boolean; + emit( + event: "resumeSession", + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + emit(event: "keylog", line: NonSharedBuffer, tlsSocket: TLSSocket): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + on( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + on(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + once(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: NonSharedBuffer, + issuer: NonSharedBuffer, + callback: (err: Error | null, resp: Buffer | null) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: ( + sessionId: NonSharedBuffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this; + } + type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; + interface SecureContextOptions { + /** + * If set, this will be called when a client opens a connection using the ALPN extension. + * One argument will be passed to the callback: an object containing `servername` and `protocols` fields, + * respectively containing the server name from the SNI extension (if any) and an array of + * ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`, + * which will be returned to the client as the selected ALPN protocol, or `undefined`, + * to reject the connection with a fatal alert. If a string is returned that does not match one of + * the client's ALPN protocols, an error will be thrown. + * This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error. + */ + ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined; + /** + * Treat intermediate (non-self-signed) + * certificates in the trust CA certificate list as trusted. + * @since v22.9.0, v20.18.0 + */ + allowPartialTrustChain?: boolean | undefined; + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + * @deprecated + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. + * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + * ECDHE-based perfect forward secrecy will still be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + * @deprecated + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + * @deprecated + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as + * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. + * + * This function can be overwritten by providing an alternative function as the `options.checkServerIdentity` option that is passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * + * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name + * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use + * a custom `options.checkServerIdentity` function that implements the desired behavior. + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `node:cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * import tls from 'node:tls'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ], + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * import tls from 'node:tls'; + * import fs from 'node:fs'; + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect( + port: number, + host?: string, + options?: ConnectionOptions, + secureConnectListener?: () => void, + ): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * `{@link createServer}` sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * `{@link createServer}` uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as `server.addContext()`, + * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. + * + * A key is _required_ for ciphers that use certificates. Either `key` or `pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * + * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto' `option. When set to `'auto'`, well-known DHE parameters of sufficient strength + * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can + * be used to create custom parameters. The key length must be greater than or + * equal to 1024 bits or else an error will be thrown. Although 1024 bits is + * permissible, use 2048 bits or larger for stronger security. + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array containing the CA certificates from various sources, depending on `type`: + * + * * `"default"`: return the CA certificates that will be used by the Node.js TLS clients by default. + * * When `--use-bundled-ca` is enabled (default), or `--use-openssl-ca` is not enabled, + * this would include CA certificates from the bundled Mozilla CA store. + * * When `--use-system-ca` is enabled, this would also include certificates from the system's + * trusted store. + * * When `NODE_EXTRA_CA_CERTS` is used, this would also include certificates loaded from the specified + * file. + * * `"system"`: return the CA certificates that are loaded from the system's trusted store, according + * to rules set by `--use-system-ca`. This can be used to get the certificates from the system + * when `--use-system-ca` is not enabled. + * * `"bundled"`: return the CA certificates from the bundled Mozilla CA store. This would be the same + * as `tls.rootCertificates`. + * * `"extra"`: return the CA certificates loaded from `NODE_EXTRA_CA_CERTS`. It's an empty array if + * `NODE_EXTRA_CA_CERTS` is not set. + * @since v22.15.0 + * @param type The type of CA certificates that will be returned. Valid values + * are `"default"`, `"system"`, `"bundled"` and `"extra"`. + * **Default:** `"default"`. + * @returns An array of PEM-encoded certificates. The array may contain duplicates + * if the same certificate is repeatedly stored in multiple sources. + */ + function getCACertificates(type?: "default" | "system" | "bundled" | "extra"): string[]; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of `{@link createSecureContext}`. + * + * Not all supported ciphers are enabled by default. See + * [Modifying the default TLS cipher suite](https://nodejs.org/docs/latest-v24.x/api/tls.html#modifying-the-default-tls-cipher-suite). + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * Sets the default CA certificates used by Node.js TLS clients. If the provided + * certificates are parsed successfully, they will become the default CA + * certificate list returned by {@link getCACertificates} and used + * by subsequent TLS connections that don't specify their own CA certificates. + * The certificates will be deduplicated before being set as the default. + * + * This function only affects the current Node.js thread. Previous + * sessions cached by the HTTPS agent won't be affected by this change, so + * this method should be called before any unwanted cachable TLS connections are + * made. + * + * To use system CA certificates as the default: + * + * ```js + * import tls from 'node:tls'; + * tls.setDefaultCACertificates(tls.getCACertificates('system')); + * ``` + * + * This function completely replaces the default CA certificate list. To add additional + * certificates to the existing defaults, get the current certificates and append to them: + * + * ```js + * import tls from 'node:tls'; + * const currentCerts = tls.getCACertificates('default'); + * const additionalCerts = ['-----BEGIN CERTIFICATE-----\n...']; + * tls.setDefaultCACertificates([...currentCerts, ...additionalCerts]); + * ``` + * @since v24.5.0 + * @param certs An array of CA certificates in PEM format. + */ + function setDefaultCACertificates(certs: ReadonlyArray): void; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is `'auto'`. See `{@link createSecureContext()}` for further + * information. + * @since v0.11.13 + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the `maxVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.3'`, unless + * changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using + * `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the highest maximum is used. + * @since v11.4.0 + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the `minVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.2'`, unless + * changed using CLI options. Using `--tls-min-v1.0` sets the default to + * `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using + * `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the lowest minimum is used. + * @since v11.4.0 + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the `ciphers` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported OpenSSL ciphers. + * Defaults to the content of `crypto.constants.defaultCoreCipherList`, unless + * changed using CLI options using `--tls-default-ciphers`. + * @since v19.8.0 + */ + let DEFAULT_CIPHERS: string; + /** + * An immutable array of strings representing the root certificates (in PEM format) + * from the bundled Mozilla CA store as supplied by the current Node.js version. + * + * The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store + * that is fixed at release time. It is identical on all supported platforms. + * @since v12.3.0 + */ + const rootCertificates: readonly string[]; +} +declare module "node:tls" { + export * from "tls"; +} diff --git a/tools/ui/node_modules/@types/node/trace_events.d.ts b/tools/ui/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..56e46209657d33396b88e836b4e3d2cb5a28d77f --- /dev/null +++ b/tools/ui/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,197 @@ +/** + * The `node:trace_events` module provides a mechanism to centralize tracing information + * generated by V8, Node.js core, and userspace code. + * + * Tracing can be enabled with the `--trace-event-categories` command-line flag + * or by using the `trace_events` module. The `--trace-event-categories` flag + * accepts a list of comma-separated category names. + * + * The available categories are: + * + * * `node`: An empty placeholder. + * * `node.async_hooks`: Enables capture of detailed [`async_hooks`](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html) trace data. + * The [`async_hooks`](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html) events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. + * * `node.console`: Enables capture of `console.time()` and `console.count()` output. + * * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.threadpoolwork.async`: Enables capture of trace data for threadpool asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.net.native`: Enables capture of trace data for network. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.fs_dir.sync`: Enables capture of trace data for file system sync directory methods. + * * `node.fs.async`: Enables capture of trace data for file system async methods. + * * `node.fs_dir.async`: Enables capture of trace data for file system async directory methods. + * * `node.perf`: Enables capture of [Performance API](https://nodejs.org/docs/latest-v24.x/api/perf_hooks.html) measurements. + * * `node.perf.usertiming`: Enables capture of only Performance API User Timing + * measures and marks. + * * `node.perf.timerify`: Enables capture of only Performance API timerify + * measurements. + * * `node.promises.rejections`: Enables capture of trace data tracking the number + * of unhandled Promise rejections and handled-after-rejections. + * * `node.vm.script`: Enables capture of trace data for the `node:vm` module's `runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The [V8](https://nodejs.org/docs/latest-v24.x/api/v8.html) events are GC, compiling, and execution related. + * * `node.http`: Enables capture of trace data for http request / response. + * + * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. + * + * ```bash + * node --trace-event-categories v8,node,node.async_hooks server.js + * ``` + * + * Prior versions of Node.js required the use of the `--trace-events-enabled` flag to enable trace events. This requirement has been removed. However, the `--trace-events-enabled` flag _may_ still be + * used and will enable the `node`, `node.async_hooks`, and `v8` trace event categories by default. + * + * ```bash + * node --trace-events-enabled + * + * # is equivalent to + * + * node --trace-event-categories v8,node,node.async_hooks + * ``` + * + * Alternatively, trace events may be enabled using the `node:trace_events` module: + * + * ```js + * import trace_events from 'node:trace_events'; + * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); + * tracing.enable(); // Enable trace event capture for the 'node.perf' category + * + * // do work + * + * tracing.disable(); // Disable trace event capture for the 'node.perf' category + * ``` + * + * Running Node.js with tracing enabled will produce log files that can be opened + * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. + * + * The logging file is by default called `node_trace.${rotation}.log`, where `${rotation}` is an incrementing log-rotation id. The filepath pattern can + * be specified with `--trace-event-file-pattern` that accepts a template + * string that supports `${rotation}` and `${pid}`: + * + * ```bash + * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js + * ``` + * + * To guarantee that the log file is properly generated after signal events like `SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers + * in your code, such as: + * + * ```js + * process.on('SIGINT', function onSigint() { + * console.info('Received SIGINT.'); + * process.exit(130); // Or applicable exit code depending on OS and signal + * }); + * ``` + * + * The tracing system uses the same time source + * as the one used by `process.hrtime()`. + * However the trace-event timestamps are expressed in microseconds, + * unlike `process.hrtime()` which returns nanoseconds. + * + * The features from this module are not available in [`Worker`](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html#class-worker) threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/trace_events.js) + */ +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + * @since v10.0.0 + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + * + * ```js + * import trace_events from 'node:trace_events'; + * const t1 = trace_events.createTracing({ categories: ['node', 'v8'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] }); + * t1.enable(); + * t2.enable(); + * + * // Prints 'node,node.perf,v8' + * console.log(trace_events.getEnabledCategories()); + * + * t2.disable(); // Will only disable emission of the 'node.perf' category + * + * // Prints 'node,v8' + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + * @since v10.0.0 + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + * @since v10.0.0 + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * import trace_events from 'node:trace_events'; + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command `node --trace-event-categories node.perf test.js` will print `'node.async_hooks,node.perf'` to the console. + * + * ```js + * import trace_events from 'node:trace_events'; + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module "node:trace_events" { + export * from "trace_events"; +} diff --git a/tools/ui/node_modules/@types/node/ts5.6/buffer.buffer.d.ts b/tools/ui/node_modules/@types/node/ts5.6/buffer.buffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5f67d7c9306edd5b2d1ac4a3bf0c2dae6473a79 --- /dev/null +++ b/tools/ui/node_modules/@types/node/ts5.6/buffer.buffer.d.ts @@ -0,0 +1,468 @@ +declare module "buffer" { + global { + interface BufferConstructor { + // see ../buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: ArrayLike): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBufferLike): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an + * `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use + * `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal + * `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(array: WithImplicitCoercion>): Buffer; + /** + * This creates a view of the `ArrayBuffer` without copying the underlying + * memory. For example, when passed a reference to the `.buffer` property of a + * `TypedArray` instance, the newly created `Buffer` will share the same + * allocated memory as the `TypedArray`'s underlying `ArrayBuffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arr = new Uint16Array(2); + * + * arr[0] = 5000; + * arr[1] = 4000; + * + * // Shares memory with `arr`. + * const buf = Buffer.from(arr.buffer); + * + * console.log(buf); + * // Prints: + * + * // Changing the original Uint16Array changes the Buffer also. + * arr[1] = 6000; + * + * console.log(buf); + * // Prints: + * ``` + * + * The optional `byteOffset` and `length` arguments specify a memory range within + * the `arrayBuffer` that will be shared by the `Buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const ab = new ArrayBuffer(10); + * const buf = Buffer.from(ab, 0, 2); + * + * console.log(buf.length); + * // Prints: 2 + * ``` + * + * A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a + * `SharedArrayBuffer` or another type appropriate for `Buffer.from()` + * variants. + * + * It is important to remember that a backing `ArrayBuffer` can cover a range + * of memory that extends beyond the bounds of a `TypedArray` view. A new + * `Buffer` created using the `buffer` property of a `TypedArray` may extend + * beyond the range of the `TypedArray`: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements + * const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements + * console.log(arrA.buffer === arrB.buffer); // true + * + * const buf = Buffer.from(arrB.buffer); + * console.log(buf); + * // Prints: + * ``` + * @since v5.10.0 + * @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the + * `.buffer` property of a `TypedArray`. + * @param byteOffset Index of first byte to expose. **Default:** `0`. + * @param length Number of bytes to expose. **Default:** + * `arrayBuffer.byteLength - byteOffset`. + */ + from( + arrayBuffer: WithImplicitCoercion, + byteOffset?: number, + length?: number, + ): Buffer; + /** + * Creates a new `Buffer` containing `string`. The `encoding` parameter identifies + * the character encoding to be used when converting `string` into bytes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('this is a tést'); + * const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); + * + * console.log(buf1.toString()); + * // Prints: this is a tést + * console.log(buf2.toString()); + * // Prints: this is a tést + * console.log(buf1.toString('latin1')); + * // Prints: this is a tést + * ``` + * + * A `TypeError` will be thrown if `string` is not a string or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(string)` may also use the internal `Buffer` pool like + * `Buffer.allocUnsafe()` does. + * @since v5.10.0 + * @param string A string to encode. + * @param encoding The encoding of `string`. **Default:** `'utf8'`. + */ + from(string: WithImplicitCoercion, encoding?: BufferEncoding): Buffer; + from(arrayOrString: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=0] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + } + interface Buffer extends Uint8Array { + // see ../buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + } + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type NonSharedBuffer = Buffer; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type AllowSharedBuffer = Buffer; + } + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + var SlowBuffer: { + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + new(size: number): Buffer; + prototype: Buffer; + }; +} diff --git a/tools/ui/node_modules/@types/node/ts5.6/compatibility/float16array.d.ts b/tools/ui/node_modules/@types/node/ts5.6/compatibility/float16array.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f148cc4f85b83107f8e8bc4fe3fcf6b642b294fe --- /dev/null +++ b/tools/ui/node_modules/@types/node/ts5.6/compatibility/float16array.d.ts @@ -0,0 +1,71 @@ +// Interface declaration for Float16Array, required in @types/node v24+. +// These definitions are specific to TS <=5.6. + +// This needs all of the "common" properties/methods of the TypedArrays, +// otherwise the type unions `TypedArray` and `ArrayBufferView` will be +// empty objects. +interface Float16Array extends Pick { + readonly BYTES_PER_ELEMENT: number; + readonly buffer: ArrayBufferLike; + readonly byteLength: number; + readonly byteOffset: number; + readonly length: number; + readonly [Symbol.toStringTag]: "Float16Array"; + at(index: number): number | undefined; + copyWithin(target: number, start: number, end?: number): this; + every(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): boolean; + fill(value: number, start?: number, end?: number): this; + filter(predicate: (value: number, index: number, array: Float16Array) => any, thisArg?: any): Float16Array; + find(predicate: (value: number, index: number, obj: Float16Array) => boolean, thisArg?: any): number | undefined; + findIndex(predicate: (value: number, index: number, obj: Float16Array) => boolean, thisArg?: any): number; + findLast( + predicate: (value: number, index: number, array: Float16Array) => value is S, + thisArg?: any, + ): S | undefined; + findLast( + predicate: (value: number, index: number, array: Float16Array) => unknown, + thisArg?: any, + ): number | undefined; + findLastIndex(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): number; + forEach(callbackfn: (value: number, index: number, array: Float16Array) => void, thisArg?: any): void; + includes(searchElement: number, fromIndex?: number): boolean; + indexOf(searchElement: number, fromIndex?: number): number; + join(separator?: string): string; + lastIndexOf(searchElement: number, fromIndex?: number): number; + map(callbackfn: (value: number, index: number, array: Float16Array) => number, thisArg?: any): Float16Array; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + ): number; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + initialValue: number, + ): number; + reduce( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float16Array) => U, + initialValue: U, + ): U; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + ): number; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + initialValue: number, + ): number; + reduceRight( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float16Array) => U, + initialValue: U, + ): U; + reverse(): Float16Array; + set(array: ArrayLike, offset?: number): void; + slice(start?: number, end?: number): Float16Array; + some(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): boolean; + sort(compareFn?: (a: number, b: number) => number): this; + subarray(begin?: number, end?: number): Float16Array; + toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; + toReversed(): Float16Array; + toSorted(compareFn?: (a: number, b: number) => number): Float16Array; + toString(): string; + valueOf(): Float16Array; + with(index: number, value: number): Float16Array; + [index: number]: number; +} diff --git a/tools/ui/node_modules/@types/node/ts5.6/globals.typedarray.d.ts b/tools/ui/node_modules/@types/node/ts5.6/globals.typedarray.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..57a1ab4f2c93361e8694aab8527b67862f667a15 --- /dev/null +++ b/tools/ui/node_modules/@types/node/ts5.6/globals.typedarray.d.ts @@ -0,0 +1,36 @@ +export {}; // Make this a module + +declare global { + namespace NodeJS { + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float16Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + type NonSharedUint8Array = Uint8Array; + type NonSharedUint8ClampedArray = Uint8ClampedArray; + type NonSharedUint16Array = Uint16Array; + type NonSharedUint32Array = Uint32Array; + type NonSharedInt8Array = Int8Array; + type NonSharedInt16Array = Int16Array; + type NonSharedInt32Array = Int32Array; + type NonSharedBigUint64Array = BigUint64Array; + type NonSharedBigInt64Array = BigInt64Array; + type NonSharedFloat16Array = Float16Array; + type NonSharedFloat32Array = Float32Array; + type NonSharedFloat64Array = Float64Array; + type NonSharedDataView = DataView; + type NonSharedTypedArray = TypedArray; + type NonSharedArrayBufferView = ArrayBufferView; + } +} diff --git a/tools/ui/node_modules/@types/node/ts5.6/index.d.ts b/tools/ui/node_modules/@types/node/ts5.6/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..52c18699648e577b4992267e50e1b798ea215dbd --- /dev/null +++ b/tools/ui/node_modules/@types/node/ts5.6/index.d.ts @@ -0,0 +1,103 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * 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. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.2 through 5.6. + +// Reference required TypeScript libraries: +/// +/// + +// TypeScript library polyfills required for TypeScript <=5.6: +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript <=5.6: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/tools/ui/node_modules/@types/node/ts5.7/compatibility/float16array.d.ts b/tools/ui/node_modules/@types/node/ts5.7/compatibility/float16array.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..110b1ebb19cb26cfac04deff6f9280ce796089d5 --- /dev/null +++ b/tools/ui/node_modules/@types/node/ts5.7/compatibility/float16array.d.ts @@ -0,0 +1,72 @@ +// Interface declaration for Float16Array, required in @types/node v24+. +// These definitions are specific to TS 5.7. + +// This needs all of the "common" properties/methods of the TypedArrays, +// otherwise the type unions `TypedArray` and `ArrayBufferView` will be +// empty objects. +interface Float16Array { + readonly BYTES_PER_ELEMENT: number; + readonly buffer: TArrayBuffer; + readonly byteLength: number; + readonly byteOffset: number; + readonly length: number; + readonly [Symbol.toStringTag]: "Float16Array"; + at(index: number): number | undefined; + copyWithin(target: number, start: number, end?: number): this; + entries(): ArrayIterator<[number, number]>; + every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; + fill(value: number, start?: number, end?: number): this; + filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Float16Array; + find(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number | undefined; + findIndex(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number; + findLast( + predicate: (value: number, index: number, array: this) => value is S, + thisArg?: any, + ): S | undefined; + findLast(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number | undefined; + findLastIndex(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number; + forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void; + includes(searchElement: number, fromIndex?: number): boolean; + indexOf(searchElement: number, fromIndex?: number): number; + join(separator?: string): string; + keys(): ArrayIterator; + lastIndexOf(searchElement: number, fromIndex?: number): number; + map(callbackfn: (value: number, index: number, array: this) => number, thisArg?: any): Float16Array; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + ): number; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + initialValue: number, + ): number; + reduce( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, + initialValue: U, + ): U; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + ): number; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + initialValue: number, + ): number; + reduceRight( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, + initialValue: U, + ): U; + reverse(): this; + set(array: ArrayLike, offset?: number): void; + slice(start?: number, end?: number): Float16Array; + some(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; + sort(compareFn?: (a: number, b: number) => number): this; + subarray(begin?: number, end?: number): Float16Array; + toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; + toReversed(): Float16Array; + toSorted(compareFn?: (a: number, b: number) => number): Float16Array; + toString(): string; + valueOf(): this; + values(): ArrayIterator; + with(index: number, value: number): Float16Array; + [Symbol.iterator](): ArrayIterator; + [index: number]: number; +} diff --git a/tools/ui/node_modules/@types/node/ts5.7/index.d.ts b/tools/ui/node_modules/@types/node/ts5.7/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b3454a725e4714ca63768cfef2672993da987b8e --- /dev/null +++ b/tools/ui/node_modules/@types/node/ts5.7/index.d.ts @@ -0,0 +1,103 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * 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. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.7. + +// Reference required TypeScript libraries: +/// +/// + +// TypeScript library polyfills required for TypeScript 5.7: +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript 5.7+: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/tools/ui/node_modules/@types/node/tty.d.ts b/tools/ui/node_modules/@types/node/tty.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..602324ab905f2d1d4fc00bcdc52f23105261b693 --- /dev/null +++ b/tools/ui/node_modules/@types/node/tty.d.ts @@ -0,0 +1,208 @@ +/** + * The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. In most cases, it will not be necessary or possible to use this module + * directly. However, it can be accessed using: + * + * ```js + * import tty from 'node:tty'; + * ``` + * + * When Node.js detects that it is being run with a text terminal ("TTY") + * attached, `process.stdin` will, by default, be initialized as an instance of `tty.ReadStream` and both `process.stdout` and `process.stderr` will, by + * default, be instances of `tty.WriteStream`. The preferred method of determining + * whether Node.js is being run within a TTY context is to check that the value of + * the `process.stdout.isTTY` property is `true`: + * + * ```console + * $ node -p -e "Boolean(process.stdout.isTTY)" + * true + * $ node -p -e "Boolean(process.stdout.isTTY)" | cat + * false + * ``` + * + * In most cases, there should be little to no reason for an application to + * manually create instances of the `tty.ReadStream` and `tty.WriteStream` classes. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/tty.js) + */ +declare module "tty" { + import * as net from "node:net"; + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + /** + * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js + * process and there should be no reason to create additional instances. + * @since v0.5.8 + */ + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + /** + * A `boolean` that is `true` if the TTY is currently configured to operate as a + * raw device. + * + * This flag is always `false` when a process starts, even if the terminal is + * operating in raw mode. Its value will change with subsequent calls to `setRawMode`. + * @since v0.7.7 + */ + isRaw: boolean; + /** + * Allows configuration of `tty.ReadStream` so that it operates as a raw device. + * + * When in raw mode, input is always available character-by-character, not + * including modifiers. Additionally, all special processing of characters by the + * terminal is disabled, including echoing input + * characters. Ctrl+C will no longer cause a `SIGINT` when + * in this mode. + * @since v0.7.7 + * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` + * property will be set to the resulting mode. + * @return The read stream instance. + */ + setRawMode(mode: boolean): this; + /** + * A `boolean` that is always `true` for `tty.ReadStream` instances. + * @since v0.5.8 + */ + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + /** + * Represents the writable side of a TTY. In normal circumstances, `process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there + * should be no reason to create additional instances. + * @since v0.5.8 + */ + class WriteStream extends net.Socket { + constructor(fd: number); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "resize", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "resize"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "resize", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "resize", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "resize", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "resize", listener: () => void): this; + /** + * `writeStream.clearLine()` clears the current line of this `WriteStream` in a + * direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * `writeStream.clearScreenDown()` clears this `WriteStream` from the current + * cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified + * position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its + * current position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * Returns: + * + * * `1` for 2, + * * `4` for 16, + * * `8` for 256, + * * `24` for 16,777,216 colors supported. + * + * Use this to determine what colors the terminal supports. Due to the nature of + * colors in terminals it is possible to either have false positives or false + * negatives. It depends on process information and the environment variables that + * may lie about what terminal is used. + * It is possible to pass in an `env` object to simulate the usage of a specific + * terminal. This can be useful to check how specific environment settings behave. + * + * To enforce a specific color support, use one of the below environment settings. + * + * * 2 colors: `FORCE_COLOR = 0` (Disables colors) + * * 16 colors: `FORCE_COLOR = 1` + * * 256 colors: `FORCE_COLOR = 2` + * * 16,777,216 colors: `FORCE_COLOR = 3` + * + * Disabling color support is also possible by using the `NO_COLOR` and `NODE_DISABLE_COLORS` environment variables. + * @since v9.9.0 + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + getColorDepth(env?: object): number; + /** + * Returns `true` if the `writeStream` supports at least as many colors as provided + * in `count`. Minimum support is 2 (black and white). + * + * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. + * + * ```js + * process.stdout.hasColors(); + * // Returns true or false depending on if `stdout` supports at least 16 colors. + * process.stdout.hasColors(256); + * // Returns true or false depending on if `stdout` supports at least 256 colors. + * process.stdout.hasColors({ TMUX: '1' }); + * // Returns true. + * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); + * // Returns false (the environment setting pretends to support 2 ** 8 colors). + * ``` + * @since v11.13.0, v10.16.0 + * @param [count=16] The number of colors that are requested (minimum 2). + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + hasColors(count?: number): boolean; + hasColors(env?: object): boolean; + hasColors(count: number, env?: object): boolean; + /** + * `writeStream.getWindowSize()` returns the size of the TTY + * corresponding to this `WriteStream`. The array is of the type `[numColumns, numRows]` where `numColumns` and `numRows` represent the number + * of columns and rows in the corresponding TTY. + * @since v0.7.7 + */ + getWindowSize(): [number, number]; + /** + * A `number` specifying the number of columns the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + columns: number; + /** + * A `number` specifying the number of rows the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + rows: number; + /** + * A `boolean` that is always `true`. + * @since v0.5.8 + */ + isTTY: boolean; + } +} +declare module "node:tty" { + export * from "tty"; +} diff --git a/tools/ui/node_modules/@types/node/url.d.ts b/tools/ui/node_modules/@types/node/url.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..abf5796c5c501785919d2f329733b484615836f3 --- /dev/null +++ b/tools/ui/node_modules/@types/node/url.d.ts @@ -0,0 +1,1079 @@ +/** + * The `node:url` module provides utilities for URL resolution and parsing. It can + * be accessed using: + * + * ```js + * import url from 'node:url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/url.js) + */ +declare module "url" { + import { Blob as NodeBlob, NonSharedBuffer } from "node:buffer"; + import { ClientRequestArgs } from "node:http"; + import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + interface FileUrlToPathOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + interface PathToFileUrlOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * `url.parse()` uses a lenient, non-standard algorithm for parsing URL + * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) + * and incorrect handling of usernames and passwords. Do not use with untrusted + * input. CVEs are not issued for `url.parse()` vulnerabilities. Use the + * [WHATWG URL](https://nodejs.org/docs/latest-v24.x/api/url.html#the-whatwg-url-api) API instead, for example: + * + * ```js + * function getURL(req) { + * const proto = req.headers['x-forwarded-proto'] || 'https'; + * const host = req.headers['x-forwarded-host'] || req.headers.host || 'example.com'; + * return new URL(`${proto}://${host}${req.url || '/'}`); + * } + * ``` + * + * The example above assumes well-formed headers are forwarded from a reverse + * proxy to your Node.js server. If you are not using a reverse proxy, you should + * use the example below: + * + * ```js + * function getURL(req) { + * return new URL(`https://example.com${req.url || '/'}`); + * } + * ``` + * @since v0.1.25 + * @deprecated Use the WHATWG URL API instead. + * @param urlString The URL string to parse. + * @param parseQueryString If `true`, the `query` property will always + * be set to an object returned by the [`querystring`](https://nodejs.org/docs/latest-v24.x/api/querystring.html) module's `parse()` + * method. If `false`, the `query` property on the returned URL object will be an + * unparsed, undecoded string. **Default:** `false`. + * @param slashesDenoteHost If `true`, the first token after the literal + * string `//` and preceding the next `/` will be interpreted as the `host`. + * For instance, given `//foo/bar`, the result would be + * `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + * **Default:** `false`. + */ + function parse( + urlString: string, + parseQueryString?: false, + slashesDenoteHost?: boolean, + ): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * import url from 'node:url'; + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * import url from 'node:url'; + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a web browser resolving an anchor tag. + * + * ```js + * import url from 'node:url'; + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * To achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param from The base URL to use if `to` is a relative URL. + * @param to The target URL to resolve. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'node:url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * + * **Security Considerations:** + * + * This function decodes percent-encoded characters, including encoded dot-segments + * (`%2e` as `.` and `%2e%2e` as `..`), and then normalizes the resulting path. + * This means that encoded directory traversal sequences (such as `%2e%2e`) are + * decoded and processed as actual path traversal, even though encoded slashes + * (`%2F`, `%5C`) are correctly rejected. + * + * **Applications must not rely on `fileURLToPath()` alone to prevent directory + * traversal attacks.** Always perform explicit path validation and security checks + * on the returned path value to ensure it remains within expected boundaries + * before using it for file system operations. + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string; + /** + * Like `url.fileURLToPath(...)` except that instead of returning a string + * representation of the path, a `Buffer` is returned. This conversion is + * helpful when the input URL contains percent-encoded segments that are + * not valid UTF-8 / Unicode sequences. + * + * **Security Considerations:** + * + * This function has the same security considerations as `url.fileURLToPath()`. + * It decodes percent-encoded characters, including encoded dot-segments + * (`%2e` as `.` and `%2e%2e` as `..`), and normalizes the path. **Applications + * must not rely on this function alone to prevent directory traversal attacks.** + * Always perform explicit path validation on the returned buffer value before + * using it for file system operations. + * @since v24.3.0 + * @param url The file URL string or URL object to convert to a path. + * @returns The fully-resolved platform-specific Node.js file path + * as a `Buffer`. + */ + function fileURLToPathBuffer(url: string | URL, options?: FileUrlToPathOptions): NonSharedBuffer; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'node:url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string, options?: PathToFileUrlOptions): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'node:url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myURL)); + * /* + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0, v14.18.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + /** + * `true` if the serialized URL string should include the username and password, `false` otherwise. + * @default true + */ + auth?: boolean | undefined; + /** + * `true` if the serialized URL string should include the fragment, `false` otherwise. + * @default true + */ + fragment?: boolean | undefined; + /** + * `true` if the serialized URL string should include the search query, `false` otherwise. + * @default true + */ + search?: boolean | undefined; + /** + * `true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to + * being Punycode encoded. + * @default false + */ + unicode?: boolean | undefined; + } + /** + * Browser-compatible `URL` class, implemented by following the WHATWG URL + * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. + * The `URL` class is also available on the global object. + * + * In accordance with browser conventions, all properties of `URL` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. Thus, unlike `legacy urlObject`s, + * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still + * return `true`. + * @since v7.0.0, v6.13.0 + */ + class URL { + /** + * Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. + * + * ```js + * import { + * Blob, + * resolveObjectURL, + * } from 'node:buffer'; + * + * const blob = new Blob(['hello']); + * const id = URL.createObjectURL(blob); + * + * // later... + * + * const otherBlob = resolveObjectURL(id); + * console.log(otherBlob.size); + * ``` + * + * The data stored by the registered `Blob` will be retained in memory until `URL.revokeObjectURL()` is called to remove it. + * + * `Blob` objects are registered within the current thread. If using Worker + * Threads, `Blob` objects registered within one Worker will not be available + * to other workers or the main thread. + * @since v16.7.0 + */ + static createObjectURL(blob: NodeBlob): string; + /** + * Removes the stored `Blob` identified by the given ID. Attempting to revoke a + * ID that isn't registered will silently fail. + * @since v16.7.0 + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + static revokeObjectURL(id: string): void; + /** + * Checks if an `input` relative to the `base` can be parsed to a `URL`. + * + * ```js + * const isValid = URL.canParse('/foo', 'https://example.org/'); // true + * + * const isNotValid = URL.canParse('/foo'); // false + * ``` + * @since v19.9.0 + * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is + * `converted to a string` first. + * @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. + */ + static canParse(input: string, base?: string): boolean; + /** + * Parses a string as a URL. If `base` is provided, it will be used as the base + * URL for the purpose of resolving non-absolute `input` URLs. Returns `null` + * if the parameters can't be resolved to a valid URL. + * @since v22.1.0 + * @param input The absolute or relative input URL to parse. If `input` + * is relative, then `base` is required. If `input` is absolute, the `base` + * is ignored. If `input` is not a string, it is [converted to a string](https://tc39.es/ecma262/#sec-tostring) first. + * @param base The base URL to resolve against if the `input` is not + * absolute. If `base` is not a string, it is [converted to a string](https://tc39.es/ecma262/#sec-tostring) first. + */ + static parse(input: string, base?: string): URL | null; + constructor(input: string | { toString: () => string }, base?: string | URL); + /** + * Gets and sets the fragment portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/foo#bar'); + * console.log(myURL.hash); + * // Prints #bar + * + * myURL.hash = 'baz'; + * console.log(myURL.href); + * // Prints https://example.org/foo#baz + * ``` + * + * Invalid URL characters included in the value assigned to the `hash` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + hash: string; + /** + * Gets and sets the host portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.host); + * // Prints example.org:81 + * + * myURL.host = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:82/foo + * ``` + * + * Invalid host values assigned to the `host` property are ignored. + */ + host: string; + /** + * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the + * port. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.hostname); + * // Prints example.org + * + * // Setting the hostname does not change the port + * myURL.hostname = 'example.com'; + * console.log(myURL.href); + * // Prints https://example.com:81/foo + * + * // Use myURL.host to change the hostname and port + * myURL.host = 'example.org:82'; + * console.log(myURL.href); + * // Prints https://example.org:82/foo + * ``` + * + * Invalid host name values assigned to the `hostname` property are ignored. + */ + hostname: string; + /** + * Gets and sets the serialized URL. + * + * ```js + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.href); + * // Prints https://example.org/foo + * + * myURL.href = 'https://example.com/bar'; + * console.log(myURL.href); + * // Prints https://example.com/bar + * ``` + * + * Getting the value of the `href` property is equivalent to calling {@link toString}. + * + * Setting the value of this property to a new value is equivalent to creating a + * new `URL` object using `new URL(value)`. Each of the `URL` object's properties will be modified. + * + * If the value assigned to the `href` property is not a valid URL, a `TypeError` will be thrown. + */ + href: string; + /** + * Gets the read-only serialization of the URL's origin. + * + * ```js + * const myURL = new URL('https://example.org/foo/bar?baz'); + * console.log(myURL.origin); + * // Prints https://example.org + * ``` + * + * ```js + * const idnURL = new URL('https://測試'); + * console.log(idnURL.origin); + * // Prints https://xn--g6w251d + * + * console.log(idnURL.hostname); + * // Prints xn--g6w251d + * ``` + */ + readonly origin: string; + /** + * Gets and sets the password portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.password); + * // Prints xyz + * + * myURL.password = '123'; + * console.log(myURL.href); + * // Prints https://abc:123@example.com/ + * ``` + * + * Invalid URL characters included in the value assigned to the `password` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + password: string; + /** + * Gets and sets the path portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc/xyz?123'); + * console.log(myURL.pathname); + * // Prints /abc/xyz + * + * myURL.pathname = '/abcdef'; + * console.log(myURL.href); + * // Prints https://example.org/abcdef?123 + * ``` + * + * Invalid URL characters included in the value assigned to the `pathname` property are `percent-encoded`. The selection of which characters + * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + pathname: string; + /** + * Gets and sets the port portion of the URL. + * + * The port value may be a number or a string containing a number in the range `0` to `65535` (inclusive). Setting the value to the default port of the `URL` objects given `protocol` will + * result in the `port` value becoming + * the empty string (`''`). + * + * The port value can be an empty string in which case the port depends on + * the protocol/scheme: + * + * + * + * Upon assigning a value to the port, the value will first be converted to a + * string using `.toString()`. + * + * If that string is invalid but it begins with a number, the leading number is + * assigned to `port`. + * If the number lies outside the range denoted above, it is ignored. + * + * ```js + * const myURL = new URL('https://example.org:8888'); + * console.log(myURL.port); + * // Prints 8888 + * + * // Default ports are automatically transformed to the empty string + * // (HTTPS protocol's default port is 443) + * myURL.port = '443'; + * console.log(myURL.port); + * // Prints the empty string + * console.log(myURL.href); + * // Prints https://example.org/ + * + * myURL.port = 1234; + * console.log(myURL.port); + * // Prints 1234 + * console.log(myURL.href); + * // Prints https://example.org:1234/ + * + * // Completely invalid port strings are ignored + * myURL.port = 'abcd'; + * console.log(myURL.port); + * // Prints 1234 + * + * // Leading numbers are treated as a port number + * myURL.port = '5678abcd'; + * console.log(myURL.port); + * // Prints 5678 + * + * // Non-integers are truncated + * myURL.port = 1234.5678; + * console.log(myURL.port); + * // Prints 1234 + * + * // Out-of-range numbers which are not represented in scientific notation + * // will be ignored. + * myURL.port = 1e10; // 10000000000, will be range-checked as described below + * console.log(myURL.port); + * // Prints 1234 + * ``` + * + * Numbers which contain a decimal point, + * such as floating-point numbers or numbers in scientific notation, + * are not an exception to this rule. + * Leading numbers up to the decimal point will be set as the URL's port, + * assuming they are valid: + * + * ```js + * myURL.port = 4.567e21; + * console.log(myURL.port); + * // Prints 4 (because it is the leading number in the string '4.567e21') + * ``` + */ + port: string; + /** + * Gets and sets the protocol portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org'); + * console.log(myURL.protocol); + * // Prints https: + * + * myURL.protocol = 'ftp'; + * console.log(myURL.href); + * // Prints ftp://example.org/ + * ``` + * + * Invalid URL protocol values assigned to the `protocol` property are ignored. + */ + protocol: string; + /** + * Gets and sets the serialized query portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc?123'); + * console.log(myURL.search); + * // Prints ?123 + * + * myURL.search = 'abc=xyz'; + * console.log(myURL.href); + * // Prints https://example.org/abc?abc=xyz + * ``` + * + * Any invalid URL characters appearing in the value assigned the `search` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + search: string; + /** + * Gets the `URLSearchParams` object representing the query parameters of the + * URL. This property is read-only but the `URLSearchParams` object it provides + * can be used to mutate the URL instance; to replace the entirety of query + * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. + * + * Use care when using `.searchParams` to modify the `URL` because, + * per the WHATWG specification, the `URLSearchParams` object uses + * different rules to determine which characters to percent-encode. For + * instance, the `URL` object will not percent encode the ASCII tilde (`~`) + * character, while `URLSearchParams` will always encode it: + * + * ```js + * const myURL = new URL('https://example.org/abc?foo=~bar'); + * + * console.log(myURL.search); // prints ?foo=~bar + * + * // Modify the URL via searchParams... + * myURL.searchParams.sort(); + * + * console.log(myURL.search); // prints ?foo=%7Ebar + * ``` + */ + readonly searchParams: URLSearchParams; + /** + * Gets and sets the username portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.username); + * // Prints abc + * + * myURL.username = '123'; + * console.log(myURL.href); + * // Prints https://123:xyz@example.com/ + * ``` + * + * Any invalid URL characters appearing in the value assigned the `username` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + username: string; + /** + * The `toString()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toJSON}. + */ + toString(): string; + /** + * The `toJSON()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toString}. + * + * This method is automatically called when an `URL` object is serialized + * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). + * + * ```js + * const myURLs = [ + * new URL('https://www.example.com'), + * new URL('https://test.example.org'), + * ]; + * console.log(JSON.stringify(myURLs)); + * // Prints ["https://www.example.com/","https://test.example.org/"] + * ``` + */ + toJSON(): string; + } + interface URLPatternComponentResult { + input: string; + groups: Record; + } + interface URLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; + } + interface URLPatternOptions { + ignoreCase?: boolean; + } + interface URLPatternResult { + inputs: (string | URLPatternInit)[]; + protocol: URLPatternComponentResult; + username: URLPatternComponentResult; + password: URLPatternComponentResult; + hostname: URLPatternComponentResult; + port: URLPatternComponentResult; + pathname: URLPatternComponentResult; + search: URLPatternComponentResult; + hash: URLPatternComponentResult; + } + /** + * @since v23.8.0 + * @experimental + */ + class URLPattern { + constructor(input: string | URLPatternInit, baseURL: string, options?: URLPatternOptions); + constructor(input?: string | URLPatternInit, options?: URLPatternOptions); + exec(input?: string | URLPatternInit, baseURL?: string): URLPatternResult | null; + readonly hasRegExpGroups: boolean; + readonly hash: string; + readonly hostname: string; + readonly password: string; + readonly pathname: string; + readonly port: string; + readonly protocol: string; + readonly search: string; + test(input?: string | URLPatternInit, baseURL?: string): boolean; + readonly username: string; + } + interface URLSearchParamsIterator extends NodeJS.Iterator { + [Symbol.iterator](): URLSearchParamsIterator; + } + /** + * The `URLSearchParams` API provides read and write access to the query of a `URL`. The `URLSearchParams` class can also be used standalone with one of the + * four following constructors. + * The `URLSearchParams` class is also available on the global object. + * + * The WHATWG `URLSearchParams` interface and the `querystring` module have + * similar purpose, but the purpose of the `querystring` module is more + * general, as it allows the customization of delimiter characters (`&` and `=`). + * On the other hand, this API is designed purely for URL query strings. + * + * ```js + * const myURL = new URL('https://example.org/?abc=123'); + * console.log(myURL.searchParams.get('abc')); + * // Prints 123 + * + * myURL.searchParams.append('abc', 'xyz'); + * console.log(myURL.href); + * // Prints https://example.org/?abc=123&abc=xyz + * + * myURL.searchParams.delete('abc'); + * myURL.searchParams.set('a', 'b'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * + * const newSearchParams = new URLSearchParams(myURL.searchParams); + * // The above is equivalent to + * // const newSearchParams = new URLSearchParams(myURL.search); + * + * newSearchParams.append('a', 'c'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * console.log(newSearchParams.toString()); + * // Prints a=b&a=c + * + * // newSearchParams.toString() is implicitly called + * myURL.search = newSearchParams; + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * newSearchParams.delete('a'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * ``` + * @since v7.5.0, v6.13.0 + */ + class URLSearchParams implements Iterable<[string, string]> { + constructor( + init?: + | URLSearchParams + | string + | Record + | Iterable<[string, string]> + | ReadonlyArray<[string, string]>, + ); + /** + * Append a new name-value pair to the query string. + */ + append(name: string, value: string): void; + /** + * If `value` is provided, removes all name-value pairs + * where name is `name` and value is `value`. + * + * If `value` is not provided, removes all name-value pairs whose name is `name`. + */ + delete(name: string, value?: string): void; + /** + * Returns an ES6 `Iterator` over each of the name-value pairs in the query. + * Each item of the iterator is a JavaScript `Array`. The first item of the `Array` is the `name`, the second item of the `Array` is the `value`. + * + * Alias for `urlSearchParams[Symbol.iterator]()`. + */ + entries(): URLSearchParamsIterator<[string, string]>; + /** + * Iterates over each name-value pair in the query and invokes the given function. + * + * ```js + * const myURL = new URL('https://example.org/?a=b&c=d'); + * myURL.searchParams.forEach((value, name, searchParams) => { + * console.log(name, value, myURL.searchParams === searchParams); + * }); + * // Prints: + * // a b true + * // c d true + * ``` + * @param fn Invoked for each name-value pair in the query + * @param thisArg To be used as `this` value for when `fn` is called + */ + forEach( + fn: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, + thisArg?: TThis, + ): void; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns the values of all name-value pairs whose name is `name`. If there are + * no such pairs, an empty array is returned. + */ + getAll(name: string): string[]; + /** + * Checks if the `URLSearchParams` object contains key-value pair(s) based on `name` and an optional `value` argument. + * + * If `value` is provided, returns `true` when name-value pair with + * same `name` and `value` exists. + * + * If `value` is not provided, returns `true` if there is at least one name-value + * pair whose name is `name`. + */ + has(name: string, value?: string): boolean; + /** + * Returns an ES6 `Iterator` over the names of each name-value pair. + * + * ```js + * const params = new URLSearchParams('foo=bar&foo=baz'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // foo + * ``` + */ + keys(): URLSearchParamsIterator; + /** + * Sets the value in the `URLSearchParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value` and remove all others. If not, + * append the name-value pair to the query string. + * + * ```js + * const params = new URLSearchParams(); + * params.append('foo', 'bar'); + * params.append('foo', 'baz'); + * params.append('abc', 'def'); + * console.log(params.toString()); + * // Prints foo=bar&foo=baz&abc=def + * + * params.set('foo', 'def'); + * params.set('xyz', 'opq'); + * console.log(params.toString()); + * // Prints foo=def&abc=def&xyz=opq + * ``` + */ + set(name: string, value: string): void; + /** + * The total number of parameter entries. + * @since v19.8.0 + */ + readonly size: number; + /** + * Sort all existing name-value pairs in-place by their names. Sorting is done + * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs + * with the same name is preserved. + * + * This method can be used, in particular, to increase cache hits. + * + * ```js + * const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); + * params.sort(); + * console.log(params.toString()); + * // Prints query%5B%5D=abc&query%5B%5D=123&type=search + * ``` + * @since v7.7.0, v6.13.0 + */ + sort(): void; + /** + * Returns the search parameters serialized as a string, with characters + * percent-encoded where necessary. + */ + toString(): string; + /** + * Returns an ES6 `Iterator` over the values of each name-value pair. + */ + values(): URLSearchParamsIterator; + [Symbol.iterator](): URLSearchParamsIterator<[string, string]>; + } + import { + URL as _URL, + URLPattern as _URLPattern, + URLPatternInit as _URLPatternInit, + URLPatternResult as _URLPatternResult, + URLSearchParams as _URLSearchParams, + } from "url"; + global { + interface URL extends _URL {} + var URL: typeof globalThis extends { + onmessage: any; + URL: infer T; + } ? T + : typeof _URL; + interface URLSearchParams extends _URLSearchParams {} + var URLSearchParams: typeof globalThis extends { + onmessage: any; + URLSearchParams: infer T; + } ? T + : typeof _URLSearchParams; + interface URLPatternInit extends _URLPatternInit {} + interface URLPatternResult extends _URLPatternResult {} + interface URLPattern extends _URLPattern {} + var URLPattern: typeof globalThis extends { + onmessage: any; + scheduler: any; // Must be a var introduced at the same time as URLPattern. + URLPattern: infer T; + } ? T + : typeof _URLPattern; + } +} +declare module "node:url" { + export * from "url"; +} diff --git a/tools/ui/node_modules/@types/node/util.d.ts b/tools/ui/node_modules/@types/node/util.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..304d44ff143a569eb2f16d969ff20b7e5683290f --- /dev/null +++ b/tools/ui/node_modules/@types/node/util.d.ts @@ -0,0 +1,2336 @@ +/** + * The `node:util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * import util from 'node:util'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/util.js) + */ +declare module "util" { + import * as types from "node:util/types"; + export interface InspectOptions { + /** + * If `true`, object's non-enumerable symbols and properties are included in the formatted result. + * `WeakMap` and `WeakSet` entries are also included as well as user defined prototype properties (excluding method properties). + * @default false + */ + showHidden?: boolean | undefined; + /** + * Specifies the number of times to recurse while formatting object. + * This is useful for inspecting large objects. + * To recurse up to the maximum call stack size pass `Infinity` or `null`. + * @default 2 + */ + depth?: number | null | undefined; + /** + * If `true`, the output is styled with ANSI color codes. Colors are customizable. + */ + colors?: boolean | undefined; + /** + * If `false`, `[util.inspect.custom](depth, opts, inspect)` functions are not invoked. + * @default true + */ + customInspect?: boolean | undefined; + /** + * If `true`, `Proxy` inspection includes the target and handler objects. + * @default false + */ + showProxy?: boolean | undefined; + /** + * Specifies the maximum number of `Array`, `TypedArray`, `WeakMap`, and `WeakSet` elements + * to include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no elements. + * @default 100 + */ + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + /** + * The length at which input values are split across multiple lines. + * Set to `Infinity` to format the input as a single line + * (in combination with `compact` set to `true` or any number >= `1`). + * @default 80 + */ + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default true + */ + compact?: boolean | number | undefined; + /** + * If set to `true` or a function, all properties of an object, and `Set` and `Map` + * entries are sorted in the resulting string. + * If set to `true` the default sort is used. + * If set to a function, it is used as a compare function. + */ + sorted?: boolean | ((a: string, b: string) => number) | undefined; + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default false + */ + getters?: "get" | "set" | boolean | undefined; + /** + * If set to `true`, an underscore is used to separate every three digits in all bigints and numbers. + * @default false + */ + numericSeparator?: boolean | undefined; + } + export type Style = + | "special" + | "number" + | "bigint" + | "boolean" + | "undefined" + | "null" + | "string" + | "symbol" + | "date" + | "regexp" + | "module"; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => any; // TODO: , inspect: inspect + export interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + export interface CallSiteObject { + /** + * Returns the name of the function associated with this call site. + */ + functionName: string; + /** + * Returns the name of the resource that contains the script for the + * function for this call site. + */ + scriptName: string; + /** + * Returns the unique id of the script, as in Chrome DevTools protocol + * [`Runtime.ScriptId`](https://chromedevtools.github.io/devtools-protocol/1-3/Runtime/#type-ScriptId). + * @since v22.14.0 + */ + scriptId: string; + /** + * Returns the number, 1-based, of the line for the associate function call. + */ + lineNumber: number; + /** + * Returns the 1-based column offset on the line for the associated function call. + */ + columnNumber: number; + } + export type DiffEntry = [operation: -1 | 0 | 1, value: string]; + /** + * `util.diff()` compares two string or array values and returns an array of difference entries. + * It uses the Myers diff algorithm to compute minimal differences, which is the same algorithm + * used internally by assertion error messages. + * + * If the values are equal, an empty array is returned. + * + * ```js + * const { diff } = require('node:util'); + * + * // Comparing strings + * const actualString = '12345678'; + * const expectedString = '12!!5!7!'; + * console.log(diff(actualString, expectedString)); + * // [ + * // [0, '1'], + * // [0, '2'], + * // [1, '3'], + * // [1, '4'], + * // [-1, '!'], + * // [-1, '!'], + * // [0, '5'], + * // [1, '6'], + * // [-1, '!'], + * // [0, '7'], + * // [1, '8'], + * // [-1, '!'], + * // ] + * // Comparing arrays + * const actualArray = ['1', '2', '3']; + * const expectedArray = ['1', '3', '4']; + * console.log(diff(actualArray, expectedArray)); + * // [ + * // [0, '1'], + * // [1, '2'], + * // [0, '3'], + * // [-1, '4'], + * // ] + * // Equal values return empty array + * console.log(diff('same', 'same')); + * // [] + * ``` + * @since v22.15.0 + * @experimental + * @param actual The first value to compare + * @param expected The second value to compare + * @returns An array of difference entries. Each entry is an array with two elements: + * * Index 0: `number` Operation code: `-1` for delete, `0` for no-op/unchanged, `1` for insert + * * Index 1: `string` The value associated with the operation + */ + export function diff(actual: string | readonly string[], expected: string | readonly string[]): DiffEntry[]; + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using `util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()` returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + interface GetCallSitesOptions { + /** + * Reconstruct the original location in the stacktrace from the source-map. + * Enabled by default with the flag `--enable-source-maps`. + */ + sourceMap?: boolean | undefined; + } + /** + * Returns an array of call site objects containing the stack of + * the caller function. + * + * Unlike accessing an `error.stack`, the result returned from this API is not + * interfered with `Error.prepareStackTrace`. + * + * ```js + * import { getCallSites } from 'node:util'; + * + * function exampleFunction() { + * const callSites = getCallSites(); + * + * console.log('Call Sites:'); + * callSites.forEach((callSite, index) => { + * console.log(`CallSite ${index + 1}:`); + * console.log(`Function Name: ${callSite.functionName}`); + * console.log(`Script Name: ${callSite.scriptName}`); + * console.log(`Line Number: ${callSite.lineNumber}`); + * console.log(`Column Number: ${callSite.columnNumber}`); + * }); + * // CallSite 1: + * // Function Name: exampleFunction + * // Script Name: /home/example.js + * // Line Number: 5 + * // Column Number: 26 + * + * // CallSite 2: + * // Function Name: anotherFunction + * // Script Name: /home/example.js + * // Line Number: 22 + * // Column Number: 3 + * + * // ... + * } + * + * // A function to simulate another stack layer + * function anotherFunction() { + * exampleFunction(); + * } + * + * anotherFunction(); + * ``` + * + * It is possible to reconstruct the original locations by setting the option `sourceMap` to `true`. + * If the source map is not available, the original location will be the same as the current location. + * When the `--enable-source-maps` flag is enabled, for example when using `--experimental-transform-types`, + * `sourceMap` will be true by default. + * + * ```ts + * import { getCallSites } from 'node:util'; + * + * interface Foo { + * foo: string; + * } + * + * const callSites = getCallSites({ sourceMap: true }); + * + * // With sourceMap: + * // Function Name: '' + * // Script Name: example.js + * // Line Number: 7 + * // Column Number: 26 + * + * // Without sourceMap: + * // Function Name: '' + * // Script Name: example.js + * // Line Number: 2 + * // Column Number: 26 + * ``` + * @param frameCount Number of frames to capture as call site objects. + * **Default:** `10`. Allowable range is between 1 and 200. + * @return An array of call site objects + * @since v22.9.0 + */ + export function getCallSites(frameCount?: number, options?: GetCallSitesOptions): CallSiteObject[]; + export function getCallSites(options: GetCallSitesOptions): CallSiteObject[]; + /** + * Returns the string name for a numeric error code that comes from a Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const name = util.getSystemErrorName(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v9.7.0 + */ + export function getSystemErrorName(err: number): string; + /** + * Enable or disable printing a stack trace on `SIGINT`. The API is only available on the main thread. + * @since 24.6.0 + */ + export function setTraceSigInt(enable: boolean): void; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0, v14.17.0 + */ + export function getSystemErrorMap(): Map; + /** + * Returns the string message for a numeric error code that comes from a Node.js + * API. + * The mapping between error codes and string messages is platform-dependent. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const message = util.getSystemErrorMessage(err.errno); + * console.error(message); // no such file or directory + * }); + * ``` + * @since v22.12.0 + */ + export function getSystemErrorMessage(err: number): string; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + * @since v16.8.0, v14.18.0 + */ + export function toUSVString(string: string): string; + /** + * Creates and returns an `AbortController` instance whose `AbortSignal` is marked + * as transferable and can be used with `structuredClone()` or `postMessage()`. + * @since v18.11.0 + * @returns A transferable AbortController + */ + export function transferableAbortController(): AbortController; + /** + * Marks the given `AbortSignal` as transferable so that it can be used with`structuredClone()` and `postMessage()`. + * + * ```js + * const signal = transferableAbortSignal(AbortSignal.timeout(100)); + * const channel = new MessageChannel(); + * channel.port2.postMessage(signal, [signal]); + * ``` + * @since v18.11.0 + * @param signal The AbortSignal + * @returns The same AbortSignal + */ + export function transferableAbortSignal(signal: AbortSignal): AbortSignal; + /** + * Listens to abort event on the provided `signal` and returns a promise that resolves when the `signal` is aborted. + * If `resource` is provided, it weakly references the operation's associated object, + * so if `resource` is garbage collected before the `signal` aborts, + * then returned promise shall remain pending. + * This prevents memory leaks in long-running or non-cancelable operations. + * + * ```js + * import { aborted } from 'node:util'; + * + * // Obtain an object with an abortable signal, like a custom resource or operation. + * const dependent = obtainSomethingAbortable(); + * + * // Pass `dependent` as the resource, indicating the promise should only resolve + * // if `dependent` is still in memory when the signal is aborted. + * aborted(dependent.signal, dependent).then(() => { + * // This code runs when `dependent` is aborted. + * console.log('Dependent resource was aborted.'); + * }); + * + * // Simulate an event that triggers the abort. + * dependent.on('event', () => { + * dependent.abort(); // This will cause the `aborted` promise to resolve. + * }); + * ``` + * @since v19.7.0 + * @param resource Any non-null object tied to the abortable operation and held weakly. + * If `resource` is garbage collected before the `signal` aborts, the promise remains pending, + * allowing Node.js to stop tracking it. + * This helps prevent memory leaks in long-running or non-cancelable operations. + */ + export function aborted(signal: AbortSignal, resource: any): Promise; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result. + * `util.inspect()` will use the constructor's name and/or `Symbol.toStringTag` + * property to make an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * import { inspect } from 'node:util'; + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * import util from 'node:util'; + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * import { inspect } from 'node:util'; + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]), + * }; + * console.log(inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows `WeakMap` and `WeakSet` entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same + * `WeakSet` entries twice may result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * import { inspect } from 'node:util'; + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * import { inspect } from 'node:util'; + * import assert from 'node:assert'; + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]), + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1], + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }), + * ); + * ``` + * + * The `numericSeparator` option adds an underscore every three digits to all + * numbers. + * + * ```js + * import { inspect } from 'node:util'; + * + * const thousand = 1000; + * const million = 1000000; + * const bigNumber = 123456789n; + * const bigDecimal = 1234.12345; + * + * console.log(inspect(thousand, { numericSeparator: true })); + * // 1_000 + * console.log(inspect(million, { numericSeparator: true })); + * // 1_000_000 + * console.log(inspect(bigNumber, { numericSeparator: true })); + * // 123_456_789n + * console.log(inspect(bigDecimal, { numericSeparator: true })); + * // 1_234.123_45 + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MiB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options?: InspectOptions): string; + export namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string; + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + /** + * That can be used to declare custom inspect functions. + */ + const custom: unique symbol; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and + * `extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one + * [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from + * `superConstructor`. + * + * This mainly adds some input validation on top of + * `Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('node:util'); + * const EventEmitter = require('node:events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * import EventEmitter from 'node:events'; + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @legacy Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + /** + * The `util.debuglog().enabled` getter is used to create a test that can be used + * in conditionals based on the existence of the `NODE_DEBUG` environment variable. + * If the `section` name appears within the value of that environment variable, + * then the returned value will be `true`. If not, then the returned value will be + * `false`. + * + * ```js + * import { debuglog } from 'node:util'; + * const enabled = debuglog('foo').enabled; + * if (enabled) { + * console.log('hello from foo [%d]', 123); + * } + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then it will + * output something like: + * + * ```console + * hello from foo [123] + * ``` + */ + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG` + * environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to + * `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * import { debuglog } from 'node:util'; + * const log = debuglog('foo'); + * + * log('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * import { debuglog } from 'node:util'; + * const log = debuglog('foo-bar'); + * + * log('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG` + * environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * import { debuglog } from 'node:util'; + * let log = debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * log = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + export { debuglog as debug }; + export interface DeprecateOptions { + /** + * When false do not change the prototype of object while emitting the deprecation warning. + * @since v24.12.0 + * @default true + */ + modifyPrototype?: boolean | undefined; + } + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * import { deprecate } from 'node:util'; + * + * export const obsoleteFunction = deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a + * `DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * import { deprecate } from 'node:util'; + * + * const fn1 = deprecate( + * () => 'a value', + * 'deprecation message', + * 'DEP0001', + * ); + * const fn2 = deprecate( + * () => 'a different value', + * 'other dep message', + * 'DEP0001', + * ); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true` _prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the + * `process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation` + * property take precedence over `--trace-deprecation` and + * `process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string, options?: DeprecateOptions): T; + export interface IsDeepStrictEqualOptions { + /** + * If `true`, prototype and constructor + * comparison is skipped during deep strict equality check. + * @since v24.9.0 + * @default false + */ + skipPrototype?: boolean | undefined; + } + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown, options?: IsDeepStrictEqualOptions): boolean; + /** + * Returns `str` with any ANSI escape codes removed. + * + * ```js + * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); + * // Prints "value" + * ``` + * @since v16.11.0 + */ + export function stripVTControlCharacters(str: string): string; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise` + * resolved), and the second argument will be the resolved value. + * + * ```js + * import { callbackify } from 'node:util'; + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` + * event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named + * `reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && Object.hasOwn(err, 'reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param fn An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: () => Promise, + ): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify = + | CustomPromisifySymbol + | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * import { promisify } from 'node:util'; + * import { stat } from 'node:fs'; + * + * const promisifiedStat = promisify(stat); + * promisifiedStat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * import { promisify } from 'node:util'; + * import { stat } from 'node:fs'; + * + * const promisifiedStat = promisify(stat); + * + * async function callStat() { + * const stats = await promisifiedStat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * + * callStat(); + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify` + * will return its value, see [Custom promisified functions](https://nodejs.org/docs/latest-v24.x/api/util.html#custom-promisified-functions). + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()` + * will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * import { promisify } from 'node:util'; + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = promisify(foo.bar); + * // TypeError: Cannot read properties of undefined (reading 'a') + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify( + fn: (callback: (err: any, result: TResult) => void) => void, + ): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify( + fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + /** + * That can be used to declare custom promisified variants of functions. + */ + const custom: unique symbol; + } + /** + * Stability: 1.1 - Active development + * Given an example `.env` file: + * + * ```js + * import { parseEnv } from 'node:util'; + * + * parseEnv('HELLO=world\nHELLO=oh my\n'); + * // Returns: { HELLO: 'oh my' } + * ``` + * @param content The raw contents of a `.env` file. + * @since v20.12.0 + */ + export function parseEnv(content: string): NodeJS.Dict; + // https://nodejs.org/docs/latest/api/util.html#foreground-colors + type ForegroundColors = + | "black" + | "blackBright" + | "blue" + | "blueBright" + | "cyan" + | "cyanBright" + | "gray" + | "green" + | "greenBright" + | "grey" + | "magenta" + | "magentaBright" + | "red" + | "redBright" + | "white" + | "whiteBright" + | "yellow" + | "yellowBright"; + // https://nodejs.org/docs/latest/api/util.html#background-colors + type BackgroundColors = + | "bgBlack" + | "bgBlackBright" + | "bgBlue" + | "bgBlueBright" + | "bgCyan" + | "bgCyanBright" + | "bgGray" + | "bgGreen" + | "bgGreenBright" + | "bgGrey" + | "bgMagenta" + | "bgMagentaBright" + | "bgRed" + | "bgRedBright" + | "bgWhite" + | "bgWhiteBright" + | "bgYellow" + | "bgYellowBright"; + // https://nodejs.org/docs/latest/api/util.html#modifiers + type Modifiers = + | "blink" + | "bold" + | "dim" + | "doubleunderline" + | "framed" + | "hidden" + | "inverse" + | "italic" + | "none" + | "overlined" + | "reset" + | "strikethrough" + | "underline"; + export interface StyleTextOptions { + /** + * When true, `stream` is checked to see if it can handle colors. + * @default true + */ + validateStream?: boolean | undefined; + /** + * A stream that will be validated if it can be colored. + * @default process.stdout + */ + stream?: NodeJS.WritableStream | undefined; + } + /** + * This function returns a formatted text considering the `format` passed + * for printing in a terminal. It is aware of the terminal's capabilities + * and acts according to the configuration set via `NO_COLOR`, + * `NODE_DISABLE_COLORS` and `FORCE_COLOR` environment variables. + * + * ```js + * import { styleText } from 'node:util'; + * import { stderr } from 'node:process'; + * + * const successMessage = styleText('green', 'Success!'); + * console.log(successMessage); + * + * const errorMessage = styleText( + * 'red', + * 'Error! Error!', + * // Validate if process.stderr has TTY + * { stream: stderr }, + * ); + * console.error(errorMessage); + * ``` + * + * `util.inspect.colors` also provides text formats such as `italic`, and + * `underline` and you can combine both: + * + * ```js + * console.log( + * util.styleText(['underline', 'italic'], 'My italic underlined message'), + * ); + * ``` + * + * When passing an array of formats, the order of the format applied + * is left to right so the following style might overwrite the previous one. + * + * ```js + * console.log( + * util.styleText(['red', 'green'], 'text'), // green + * ); + * ``` + * + * The special format value `none` applies no additional styling to the text. + * + * The full list of formats can be found in [modifiers](https://nodejs.org/docs/latest-v24.x/api/util.html#modifiers). + * @param format A text format or an Array of text formats defined in `util.inspect.colors`. + * @param text The text to to be formatted. + * @since v20.12.0 + */ + export function styleText( + format: + | ForegroundColors + | BackgroundColors + | Modifiers + | Array, + text: string, + options?: StyleTextOptions, + ): string; + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder(); + * const u8arr = new Uint8Array([72, 101, 108, 108, 111]); + * console.log(decoder.decode(u8arr)); // Hello + * ``` + * @since v8.3.0 + */ + export class TextDecoder { + /** + * The encoding supported by the `TextDecoder` instance. + */ + readonly encoding: string; + /** + * The value will be `true` if decoding errors result in a `TypeError` being + * thrown. + */ + readonly fatal: boolean; + /** + * The value will be `true` if the decoding result will include the byte order + * mark. + */ + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { + fatal?: boolean | undefined; + ignoreBOM?: boolean | undefined; + }, + ); + /** + * Decodes the `input` and returns a string. If `options.stream` is `true`, any + * incomplete byte sequences occurring at the end of the `input` are buffered + * internally and emitted after the next call to `textDecoder.decode()`. + * + * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a `TypeError` being thrown. + * @param input An `ArrayBuffer`, `DataView`, or `TypedArray` instance containing the encoded data. + */ + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { + stream?: boolean | undefined; + }, + ): string; + } + export interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + export { types }; + + //// TextEncoder/Decoder + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All + * instances of `TextEncoder` only support UTF-8 encoding. + * + * ```js + * const encoder = new TextEncoder(); + * const uint8array = encoder.encode('this is some data'); + * ``` + * + * The `TextEncoder` class is also available on the global object. + * @since v8.3.0 + */ + export class TextEncoder { + /** + * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. + */ + readonly encoding: string; + /** + * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the + * encoded bytes. + * @param [input='an empty string'] The text to encode. + */ + encode(input?: string): NodeJS.NonSharedUint8Array; + /** + * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object + * containing the read Unicode code units and written UTF-8 bytes. + * + * ```js + * const encoder = new TextEncoder(); + * const src = 'this is some data'; + * const dest = new Uint8Array(10); + * const { read, written } = encoder.encodeInto(src, dest); + * ``` + * @param src The text to encode. + * @param dest The array to hold the encode result. + */ + encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; + } + import { TextDecoder as _TextDecoder, TextEncoder as _TextEncoder } from "util"; + global { + /** + * `TextDecoder` class is a global reference for `import { TextDecoder } from 'node:util'` + * https://nodejs.org/api/globals.html#textdecoder + * @since v11.0.0 + */ + var TextDecoder: typeof globalThis extends { + onmessage: any; + TextDecoder: infer TextDecoder; + } ? TextDecoder + : typeof _TextDecoder; + /** + * `TextEncoder` class is a global reference for `import { TextEncoder } from 'node:util'` + * https://nodejs.org/api/globals.html#textencoder + * @since v11.0.0 + */ + var TextEncoder: typeof globalThis extends { + onmessage: any; + TextEncoder: infer TextEncoder; + } ? TextEncoder + : typeof _TextEncoder; + } + + //// parseArgs + /** + * Provides a higher level API for command-line argument parsing than interacting + * with `process.argv` directly. Takes a specification for the expected arguments + * and returns a structured object with the parsed options and positionals. + * + * ```js + * import { parseArgs } from 'node:util'; + * const args = ['-f', '--bar', 'b']; + * const options = { + * foo: { + * type: 'boolean', + * short: 'f', + * }, + * bar: { + * type: 'string', + * }, + * }; + * const { + * values, + * positionals, + * } = parseArgs({ args, options }); + * console.log(values, positionals); + * // Prints: [Object: null prototype] { foo: true, bar: 'b' } [] + * ``` + * @since v18.3.0, v16.17.0 + * @param config Used to provide arguments for parsing and to configure the parser. `config` supports the following properties: + * @return The parsed command line arguments: + */ + export function parseArgs(config?: T): ParsedResults; + + /** + * Type of argument used in {@link parseArgs}. + */ + export type ParseArgsOptionsType = "boolean" | "string"; + + export interface ParseArgsOptionDescriptor { + /** + * Type of argument. + */ + type: ParseArgsOptionsType; + /** + * Whether this option can be provided multiple times. + * If `true`, all values will be collected in an array. + * If `false`, values for the option are last-wins. + * @default false. + */ + multiple?: boolean | undefined; + /** + * A single character alias for the option. + */ + short?: string | undefined; + /** + * The value to assign to + * the option if it does not appear in the arguments to be parsed. The value + * must match the type specified by the `type` property. If `multiple` is + * `true`, it must be an array. No default value is applied when the option + * does appear in the arguments to be parsed, even if the provided value + * is falsy. + * @since v18.11.0 + */ + default?: string | boolean | string[] | boolean[] | undefined; + } + export interface ParseArgsOptionsConfig { + [longOption: string]: ParseArgsOptionDescriptor; + } + export interface ParseArgsConfig { + /** + * Array of argument strings. + */ + args?: readonly string[] | undefined; + /** + * Used to describe arguments known to the parser. + */ + options?: ParseArgsOptionsConfig | undefined; + /** + * Should an error be thrown when unknown arguments are encountered, + * or when arguments are passed that do not match the `type` configured in `options`. + * @default true + */ + strict?: boolean | undefined; + /** + * Whether this command accepts positional arguments. + */ + allowPositionals?: boolean | undefined; + /** + * If `true`, allows explicitly setting boolean options to `false` by prefixing the option name with `--no-`. + * @default false + * @since v22.4.0 + */ + allowNegative?: boolean | undefined; + /** + * Return the parsed tokens. This is useful for extending the built-in behavior, + * from adding additional checks through to reprocessing the tokens in different ways. + * @default false + */ + tokens?: boolean | undefined; + } + /* + IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. + TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 + This means it is impossible to distinguish between "field X is definitely not present" and "field X may or may not be present". + But we expect users to generally provide their config inline or `as const`, which means TS will always know whether a given field is present. + So this helper treats "not definitely present" (i.e., not `extends boolean`) as being "definitely not present", i.e. it should have its default value. + This is technically incorrect but is a much nicer UX for the common case. + The IfDefaultsTrue version is for things which default to true; the IfDefaultsFalse version is for things which default to false. + */ + type IfDefaultsTrue = T extends true ? IfTrue + : T extends false ? IfFalse + : IfTrue; + + // we put the `extends false` condition first here because `undefined` compares like `any` when `strictNullChecks: false` + type IfDefaultsFalse = T extends false ? IfFalse + : T extends true ? IfTrue + : IfFalse; + + type ExtractOptionValue = IfDefaultsTrue< + T["strict"], + O["type"] extends "string" ? string : O["type"] extends "boolean" ? boolean : string | boolean, + string | boolean + >; + + type ApplyOptionalModifiers> = ( + & { -readonly [LongOption in keyof O]?: V[LongOption] } + & { [LongOption in keyof O as O[LongOption]["default"] extends {} ? LongOption : never]: V[LongOption] } + ) extends infer P ? { [K in keyof P]: P[K] } : never; // resolve intersection to object + + type ParsedValues = + & IfDefaultsTrue + & (T["options"] extends ParseArgsOptionsConfig ? ApplyOptionalModifiers< + T["options"], + { + [LongOption in keyof T["options"]]: IfDefaultsFalse< + T["options"][LongOption]["multiple"], + Array>, + ExtractOptionValue + >; + } + > + : {}); + + type ParsedPositionals = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type PreciseTokenForOptions< + K extends string, + O extends ParseArgsOptionDescriptor, + > = O["type"] extends "string" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: string; + inlineValue: boolean; + } + : O["type"] extends "boolean" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: undefined; + inlineValue: undefined; + } + : OptionToken & { name: K }; + + type TokenForOptions< + T extends ParseArgsConfig, + K extends keyof T["options"] = keyof T["options"], + > = K extends unknown + ? T["options"] extends ParseArgsOptionsConfig ? PreciseTokenForOptions + : OptionToken + : never; + + type ParsedOptionToken = IfDefaultsTrue, OptionToken>; + + type ParsedPositionalToken = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type ParsedTokens = Array< + ParsedOptionToken | ParsedPositionalToken | { kind: "option-terminator"; index: number } + >; + + type PreciseParsedResults = IfDefaultsFalse< + T["tokens"], + { + values: ParsedValues; + positionals: ParsedPositionals; + tokens: ParsedTokens; + }, + { + values: ParsedValues; + positionals: ParsedPositionals; + } + >; + + type OptionToken = + | { kind: "option"; index: number; name: string; rawName: string; value: string; inlineValue: boolean } + | { + kind: "option"; + index: number; + name: string; + rawName: string; + value: undefined; + inlineValue: undefined; + }; + + type Token = + | OptionToken + | { kind: "positional"; index: number; value: string } + | { kind: "option-terminator"; index: number }; + + // If ParseArgsConfig extends T, then the user passed config constructed elsewhere. + // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. + type ParsedResults = ParseArgsConfig extends T ? { + values: { + [longOption: string]: undefined | string | boolean | Array; + }; + positionals: string[]; + tokens?: Token[]; + } + : PreciseParsedResults; + + /** + * An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/). + * + * In accordance with browser conventions, all properties of `MIMEType` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. + * + * A MIME string is a structured string containing multiple meaningful + * components. When parsed, a `MIMEType` object is returned containing + * properties for each of these components. + * @since v19.1.0, v18.13.0 + */ + export class MIMEType { + /** + * Creates a new MIMEType object by parsing the input. + * + * A `TypeError` will be thrown if the `input` is not a valid MIME. + * Note that an effort will be made to coerce the given values into strings. + * @param input The input MIME to parse. + */ + constructor(input: string | { toString: () => string }); + + /** + * Gets and sets the type portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript'); + * console.log(myMIME.type); + * // Prints: text + * myMIME.type = 'application'; + * console.log(myMIME.type); + * // Prints: application + * console.log(String(myMIME)); + * // Prints: application/javascript + * ``` + */ + type: string; + /** + * Gets and sets the subtype portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/ecmascript'); + * console.log(myMIME.subtype); + * // Prints: ecmascript + * myMIME.subtype = 'javascript'; + * console.log(myMIME.subtype); + * // Prints: javascript + * console.log(String(myMIME)); + * // Prints: text/javascript + * ``` + */ + subtype: string; + /** + * Gets the essence of the MIME. This property is read only. + * Use `mime.type` or `mime.subtype` to alter the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript;key=value'); + * console.log(myMIME.essence); + * // Prints: text/javascript + * myMIME.type = 'application'; + * console.log(myMIME.essence); + * // Prints: application/javascript + * console.log(String(myMIME)); + * // Prints: application/javascript;key=value + * ``` + */ + readonly essence: string; + /** + * Gets the `MIMEParams` object representing the + * parameters of the MIME. This property is read-only. See `MIMEParams` documentation for details. + */ + readonly params: MIMEParams; + /** + * The `toString()` method on the `MIMEType` object returns the serialized MIME. + * + * Because of the need for standard compliance, this method does not allow users + * to customize the serialization process of the MIME. + */ + toString(): string; + } + /** + * The `MIMEParams` API provides read and write access to the parameters of a `MIMEType`. + * @since v19.1.0, v18.13.0 + */ + export class MIMEParams { + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + * Each item of the iterator is a JavaScript `Array`. The first item of the array + * is the `name`, the second item of the array is the `value`. + */ + entries(): NodeJS.Iterator<[name: string, value: string]>; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an iterator over the names of each name-value pair. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // bar + * ``` + */ + keys(): NodeJS.Iterator; + /** + * Sets the value in the `MIMEParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value`. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * params.set('foo', 'def'); + * params.set('baz', 'xyz'); + * console.log(params.toString()); + * // Prints: foo=def;bar=1;baz=xyz + * ``` + */ + set(name: string, value: string): void; + /** + * Returns an iterator over the values of each name-value pair. + */ + values(): NodeJS.Iterator; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + [Symbol.iterator](): NodeJS.Iterator<[name: string, value: string]>; + } +} +declare module "util/types" { + import { KeyObject, webcrypto } from "node:crypto"; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or + * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed + * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to + * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a BigInt object, e.g. created + * by `Object(BigInt(123))`. + * + * ```js + * util.types.isBigIntObject(Object(BigInt(123))); // Returns true + * util.types.isBigIntObject(BigInt(123)); // Returns false + * util.types.isBigIntObject(123); // Returns false + * ``` + * @since v10.4.0 + */ + function isBigIntObject(object: unknown): object is BigInt; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are + * [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a + * `null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * import native from 'napi_addon.node'; + * import { types } from 'node:util'; + * + * const data = native.myNapi(); + * types.isExternal(data); // returns true + * types.isExternal(0); // returns false + * types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to + * [`napi_create_external()`](https://nodejs.org/docs/latest-v24.x/api/n-api.html#napi_create_external). + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float16Array) instance. + * + * ```js + * util.types.isFloat16Array(new ArrayBuffer()); // Returns false + * util.types.isFloat16Array(new Float16Array()); // Returns true + * util.types.isFloat16Array(new Float32Array()); // Returns false + * ``` + * @since v24.0.0 + */ + function isFloat16Array(object: unknown): object is Float16Array; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap( + object: T | {}, + ): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) + : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value was returned by the constructor of a + * [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). + * + * ```js + * console.log(util.types.isNativeError(new Error())); // true + * console.log(util.types.isNativeError(new TypeError())); // true + * console.log(util.types.isNativeError(new RangeError())); // true + * ``` + * + * Subclasses of the native error types are also native errors: + * + * ```js + * class MyError extends Error {} + * console.log(util.types.isNativeError(new MyError())); // true + * ``` + * + * A value being `instanceof` a native error class is not equivalent to `isNativeError()` + * returning `true` for that value. `isNativeError()` returns `true` for errors + * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false` + * for these errors: + * + * ```js + * import { createContext, runInContext } from 'node:vm'; + * import { types } from 'node:util'; + * + * const context = createContext({}); + * const myError = runInContext('new Error()', context); + * console.log(types.isNativeError(myError)); // true + * console.log(myError instanceof Error); // false + * ``` + * + * Conversely, `isNativeError()` returns `false` for all objects which were not + * returned by the constructor of a native error. That includes values + * which are `instanceof` native errors: + * + * ```js + * const myError = { __proto__: Error.prototype }; + * console.log(util.types.isNativeError(myError)); // false + * console.log(myError instanceof Error); // true + * ``` + * @since v10.0.0 + * @deprecated The `util.types.isNativeError` API is deprecated. Please use `Error.isError` instead. + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet( + object: T | {}, + ): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a `KeyObject`, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} +declare module "node:util" { + export * from "util"; +} +declare module "node:util/types" { + export * from "util/types"; +} diff --git a/tools/ui/node_modules/@types/node/v8.d.ts b/tools/ui/node_modules/@types/node/v8.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e57f970d8fb5eab4760cdaef19442af1f67ef6cb --- /dev/null +++ b/tools/ui/node_modules/@types/node/v8.d.ts @@ -0,0 +1,982 @@ +/** + * The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: + * + * ```js + * import v8 from 'node:v8'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/v8.js) + */ +declare module "v8" { + import { NonSharedBuffer } from "node:buffer"; + import { Readable } from "node:stream"; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + total_global_handles_size: number; + used_global_handles_size: number; + external_memory: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + interface HeapSnapshotOptions { + /** + * If true, expose internals in the heap snapshot. + * @default false + */ + exposeInternals?: boolean | undefined; + /** + * If true, expose numeric values in artificial fields. + * @default false + */ + exposeNumericValues?: boolean | undefined; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the `--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * `total_global_handles_size` The value of total\_global\_handles\_size is the + * total memory size of V8 global handles. + * + * `used_global_handles_size` The value of used\_global\_handles\_size is the + * used memory size of V8 global handles. + * + * `external_memory` The value of external\_memory is the memory size of array + * buffers and external strings. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0, + * total_global_handles_size: 8192, + * used_global_handles_size: 3296, + * external_memory: 318824 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * It returns an object with a structure similar to the + * [`cppgc::HeapStatistics`](https://v8docs.nodesource.com/node-22.4/d7/d51/heap-statistics_8h_source.html) + * object. See the [V8 documentation](https://v8docs.nodesource.com/node-22.4/df/d2f/structcppgc_1_1_heap_statistics.html) + * for more information about the properties of the object. + * + * ```js + * // Detailed + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * space_statistics: [ + * { + * name: 'NormalPageSpace0', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace1', + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace2', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace3', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'LargePageSpace', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * ], + * type_names: [], + * detail_level: 'detailed', + * }); + * ``` + * + * ```js + * // Brief + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 128864, + * space_statistics: [], + * type_names: [], + * detail_level: 'brief', + * }); + * ``` + * @since v22.15.0 + * @param detailLevel **Default:** `'detailed'`. Specifies the level of detail in the returned statistics. + * Accepted values are: + * * `'brief'`: Brief statistics contain only the top-level + * allocated and used + * memory statistics for the entire heap. + * * `'detailed'`: Detailed statistics also contain a break + * down per space and page, as well as freelist statistics + * and object type histograms. + */ + function getCppHeapStatistics(detailLevel?: "brief" | "detailed"): object; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8 [`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running `node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * import v8 from 'node:v8'; + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * This is similar to the [`queryObjects()` console API](https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function) + * provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain + * in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should + * avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the + * application. + * + * To avoid accidental leaks, this API does not return raw references to the objects found. By default, it returns the count of the objects + * found. If `options.format` is `'summary'`, it returns an array containing brief string representations for each object. The visibility provided + * in this API is similar to what the heap snapshot provides, while users can save the cost of serialization and parsing and directly filter the + * target objects during the search. + * + * Only objects created in the current execution context are included in the results. + * + * ```js + * import { queryObjects } from 'node:v8'; + * class A { foo = 'bar'; } + * console.log(queryObjects(A)); // 0 + * const a = new A(); + * console.log(queryObjects(A)); // 1 + * // [ "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * + * class B extends A { bar = 'qux'; } + * const b = new B(); + * console.log(queryObjects(B)); // 1 + * // [ "B { foo: 'bar', bar: 'qux' }" ] + * console.log(queryObjects(B, { format: 'summary' })); + * + * // Note that, when there are child classes inheriting from a constructor, + * // the constructor also shows up in the prototype chain of the child + * // classes's prototoype, so the child classes's prototoype would also be + * // included in the result. + * console.log(queryObjects(A)); // 3 + * // [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * ``` + * @param ctor The constructor that can be used to search on the prototype chain in order to filter target objects in the heap. + * @since v20.13.0 + */ + function queryObjects(ctor: Function): number | string[]; + function queryObjects(ctor: Function, options: { format: "count" }): number; + function queryObjects(ctor: Function, options: { format: "summary" }): string[]; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * // Print heap snapshot to the console + * import v8 from 'node:v8'; + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable containing the V8 heap snapshot. + */ + function getHeapSnapshot(options?: HeapSnapshotOptions): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * import { writeHeapSnapshot } from 'node:v8'; + * import { + * Worker, + * isMainThread, + * parentPort, + * } from 'node:worker_threads'; + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string, options?: HeapSnapshotOptions): string; + /** + * Get statistics about code and its metadata in the heap, see + * V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the + * following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794, + * cpu_profiler_metadata_size: 0, + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * @since v24.12.0 + */ + interface SyncCPUProfileHandle { + /** + * Stopping collecting the profile and return the profile data. + * @since v24.12.0 + */ + stop(): string; + /** + * Stopping collecting the profile and the profile will be discarded. + * @since v24.12.0 + */ + [Symbol.dispose](): void; + } + /** + * @since v24.8.0 + */ + interface CPUProfileHandle { + /** + * Stopping collecting the profile, then return a Promise that fulfills with an error or the + * profile data. + * @since v24.8.0 + */ + stop(): Promise; + /** + * Stopping collecting the profile and the profile will be discarded. + * @since v24.8.0 + */ + [Symbol.asyncDispose](): Promise; + } + /** + * @since v24.9.0 + */ + interface HeapProfileHandle { + /** + * Stopping collecting the profile, then return a Promise that fulfills with an error or the + * profile data. + * @since v24.9.0 + */ + stop(): Promise; + /** + * Stopping collecting the profile and the profile will be discarded. + * @since v24.9.0 + */ + [Symbol.asyncDispose](): Promise; + } + /** + * V8 only supports `Latin-1/ISO-8859-1` and `UTF16` as the underlying representation of a string. + * If the `content` uses `Latin-1/ISO-8859-1` as the underlying representation, this function will return true; + * otherwise, it returns false. + * + * If this method returns false, that does not mean that the string contains some characters not in `Latin-1/ISO-8859-1`. + * Sometimes a `Latin-1` string may also be represented as `UTF16`. + * + * ```js + * const { isStringOneByteRepresentation } = require('node:v8'); + * + * const Encoding = { + * latin1: 1, + * utf16le: 2, + * }; + * const buffer = Buffer.alloc(100); + * function writeString(input) { + * if (isStringOneByteRepresentation(input)) { + * buffer.writeUint8(Encoding.latin1); + * buffer.writeUint32LE(input.length, 1); + * buffer.write(input, 5, 'latin1'); + * } else { + * buffer.writeUint8(Encoding.utf16le); + * buffer.writeUint32LE(input.length * 2, 1); + * buffer.write(input, 5, 'utf16le'); + * } + * } + * writeString('hello'); + * writeString('你好'); + * ``` + * @since v23.10.0, v22.15.0 + */ + function isStringOneByteRepresentation(content: string): boolean; + /** + * Starting a CPU profile then return a `SyncCPUProfileHandle` object. This API supports `using` syntax. + * + * ```js + * const handle = v8.startCpuProfile(); + * const profile = handle.stop(); + * console.log(profile); + * ``` + * @since v24.12.0 + */ + function startCpuProfile(): SyncCPUProfileHandle; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): NonSharedBuffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer's internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.ArrayBufferView): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before `.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer's internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * + * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to + * serialize a huge object which requires buffer + * larger than `buffer.constants.MAX_LENGTH`. + * @since v8.0.0 + */ + function serialize(value: any): NonSharedBuffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.ArrayBufferView): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function stopCoverage(): void; + /** + * The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the command line or the API is called more than once. + * `limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information. + * @since v18.10.0, v16.18.0 + */ + function setHeapSnapshotNearHeapLimit(limit: number): void; + /** + * This API collects GC data in current thread. + * @since v19.6.0, v18.15.0 + */ + class GCProfiler { + /** + * Start collecting GC data. + * @since v19.6.0, v18.15.0 + */ + start(): void; + /** + * Stop collecting GC data and return an object. The content of object + * is as follows. + * + * ```json + * { + * "version": 1, + * "startTime": 1674059033862, + * "statistics": [ + * { + * "gcType": "Scavenge", + * "beforeGC": { + * "heapStatistics": { + * "totalHeapSize": 5005312, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5226496, + * "totalAvailableSize": 4341325216, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4883840, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * }, + * "cost": 1574.14, + * "afterGC": { + * "heapStatistics": { + * "totalHeapSize": 6053888, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5500928, + * "totalAvailableSize": 4341101384, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4059096, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * } + * } + * ], + * "endTime": 1674059036865 + * } + * ``` + * + * Here's an example. + * + * ```js + * import { GCProfiler } from 'node:v8'; + * const profiler = new GCProfiler(); + * profiler.start(); + * setTimeout(() => { + * console.log(profiler.stop()); + * }, 1000); + * ``` + * @since v19.6.0, v18.15.0 + */ + stop(): GCProfilerResult; + /** + * Stop collecting GC data, and discard the profile. + * @since v24.13.0 + */ + [Symbol.dispose](): void; + } + interface GCProfilerResult { + version: number; + startTime: number; + endTime: number; + statistics: Array<{ + gcType: string; + cost: number; + beforeGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + afterGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + }>; + } + interface HeapStatistics { + totalHeapSize: number; + totalHeapSizeExecutable: number; + totalPhysicalSize: number; + totalAvailableSize: number; + totalGlobalHandlesSize: number; + usedGlobalHandlesSize: number; + usedHeapSize: number; + heapSizeLimit: number; + mallocedMemory: number; + externalMemory: number; + peakMallocedMemory: number; + } + interface HeapSpaceStatistics { + spaceName: string; + spaceSize: number; + spaceUsedSize: number; + spaceAvailableSize: number; + physicalSpaceSize: number; + } + /** + * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will + * happen if a promise is created without ever getting a continuation. + * @since v17.1.0, v16.14.0 + * @param promise The promise being created. + * @param parent The promise continued from, if applicable. + */ + interface Init { + (promise: Promise, parent: Promise): void; + } + /** + * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming. + * + * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise. + * The before callback may be called many times in the case where many continuations have been made from the same promise. + * @since v17.1.0, v16.14.0 + */ + interface Before { + (promise: Promise): void; + } + /** + * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await. + * @since v17.1.0, v16.14.0 + */ + interface After { + (promise: Promise): void; + } + /** + * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or + * {@link Promise.reject()}. + * @since v17.1.0, v16.14.0 + */ + interface Settled { + (promise: Promise): void; + } + /** + * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or + * around an await, and when the promise resolves or rejects. + * + * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and + * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop. + * @since v17.1.0, v16.14.0 + */ + interface HookCallbacks { + init?: Init; + before?: Before; + after?: After; + settled?: Settled; + } + interface PromiseHooks { + /** + * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param init The {@link Init | `init` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onInit: (init: Init) => Function; + /** + * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param settled The {@link Settled | `settled` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onSettled: (settled: Settled) => Function; + /** + * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param before The {@link Before | `before` callback} to call before a promise continuation executes. + * @return Call to stop the hook. + */ + onBefore: (before: Before) => Function; + /** + * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param after The {@link After | `after` callback} to call after a promise continuation executes. + * @return Call to stop the hook. + */ + onAfter: (after: After) => Function; + /** + * Registers functions to be called for different lifetime events of each promise. + * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. + * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. + * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register + * @return Used for disabling hooks + */ + createHook: (callbacks: HookCallbacks) => Function; + } + /** + * The `promiseHooks` interface can be used to track promise lifecycle events. + * @since v17.1.0, v16.14.0 + */ + const promiseHooks: PromiseHooks; + type StartupSnapshotCallbackFn = (args: any) => any; + /** + * The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots. + * + * ```bash + * $ node --snapshot-blob snapshot.blob --build-snapshot entry.js + * # This launches a process with the snapshot + * $ node --snapshot-blob snapshot.blob + * ``` + * + * In the example above, `entry.js` can use methods from the `v8.startupSnapshot` interface to specify how to save information for custom objects + * in the snapshot during serialization and how the information can be used to synchronize these objects during deserialization of the snapshot. + * For example, if the `entry.js` contains the following script: + * + * ```js + * 'use strict'; + * + * import fs from 'node:fs'; + * import zlib from 'node:zlib'; + * import path from 'node:path'; + * import assert from 'node:assert'; + * + * import v8 from 'node:v8'; + * + * class BookShelf { + * storage = new Map(); + * + * // Reading a series of files from directory and store them into storage. + * constructor(directory, books) { + * for (const book of books) { + * this.storage.set(book, fs.readFileSync(path.join(directory, book))); + * } + * } + * + * static compressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gzipSync(content)); + * } + * } + * + * static decompressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gunzipSync(content)); + * } + * } + * } + * + * // __dirname here is where the snapshot script is placed + * // during snapshot building time. + * const shelf = new BookShelf(__dirname, [ + * 'book1.en_US.txt', + * 'book1.es_ES.txt', + * 'book2.zh_CN.txt', + * ]); + * + * assert(v8.startupSnapshot.isBuildingSnapshot()); + * // On snapshot serialization, compress the books to reduce size. + * v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf); + * // On snapshot deserialization, decompress the books. + * v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf); + * v8.startupSnapshot.setDeserializeMainFunction((shelf) => { + * // process.env and process.argv are refreshed during snapshot + * // deserialization. + * const lang = process.env.BOOK_LANG || 'en_US'; + * const book = process.argv[1]; + * const name = `${book}.${lang}.txt`; + * console.log(shelf.storage.get(name)); + * }, shelf); + * ``` + * + * The resulted binary will get print the data deserialized from the snapshot during start up, using the refreshed `process.env` and `process.argv` of the launched process: + * + * ```bash + * $ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1 + * # Prints content of book1.es_ES.txt deserialized from the snapshot. + * ``` + * + * Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot. + * + * @since v18.6.0, v16.17.0 + */ + namespace startupSnapshot { + /** + * Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit. + * This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization. + * @since v18.6.0, v16.17.0 + */ + function addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Add a callback that will be called when the Node.js instance is deserialized from a snapshot. + * The `callback` and the `data` (if provided) will be serialized into the snapshot, they can be used to re-initialize the state of the application or + * to re-acquire resources that the application needs when the application is restarted from the snapshot. + * @since v18.6.0, v16.17.0 + */ + function addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * This sets the entry point of the Node.js application when it is deserialized from a snapshot. This can be called only once in the snapshot building script. + * If called, the deserialized application no longer needs an additional entry point script to start up and will simply invoke the callback along with the deserialized + * data (if provided), otherwise an entry point script still needs to be provided to the deserialized application. + * @since v18.6.0, v16.17.0 + */ + function setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Returns true if the Node.js instance is run to build a snapshot. + * @since v18.6.0, v16.17.0 + */ + function isBuildingSnapshot(): boolean; + } +} +declare module "node:v8" { + export * from "v8"; +} diff --git a/tools/ui/node_modules/@types/node/vm.d.ts b/tools/ui/node_modules/@types/node/vm.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e56db1f581e040df47c56f3c2ebdad4af1fec4d1 --- /dev/null +++ b/tools/ui/node_modules/@types/node/vm.d.ts @@ -0,0 +1,1195 @@ +/** + * The `node:vm` module enables compiling and running code within V8 Virtual + * Machine contexts. + * + * **The `node:vm` module is not a security** + * **mechanism. Do not use it to run untrusted code.** + * + * JavaScript code can be compiled and run immediately or + * compiled, saved, and run later. + * + * A common use case is to run the code in a different V8 Context. This means + * invoked code has a different global object than the invoking code. + * + * One can provide the context by `contextifying` an + * object. The invoked code treats any property in the context like a + * global variable. Any changes to global variables caused by the invoked + * code are reflected in the context object. + * + * ```js + * import vm from 'node:vm'; + * + * const x = 1; + * + * const context = { x: 2 }; + * vm.createContext(context); // Contextify the object. + * + * const code = 'x += 40; var y = 17;'; + * // `x` and `y` are global variables in the context. + * // Initially, x has the value 2 because that is the value of context.x. + * vm.runInContext(code, context); + * + * console.log(context.x); // 42 + * console.log(context.y); // 17 + * + * console.log(x); // 1; y is not defined. + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/vm.js) + */ +declare module "vm" { + import { NonSharedBuffer } from "node:buffer"; + import { ImportAttributes, ImportPhase } from "node:module"; + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * @default '' + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + type DynamicModuleLoader = ( + specifier: string, + referrer: T, + importAttributes: ImportAttributes, + phase: ImportPhase, + ) => Module | Promise; + interface ScriptOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: NodeJS.ArrayBufferView | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + /** + * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is + * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see + * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis). + * @experimental + */ + importModuleDynamically?: + | DynamicModuleLoader