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

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

No files matched your search

@@ -0,0 +1,46 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// packages/react/use-callback-ref/src/index.ts
var index_exports = {};
__export(index_exports, {
useCallbackRef: () => useCallbackRef
});
module.exports = __toCommonJS(index_exports);
// packages/react/use-callback-ref/src/use-callback-ref.tsx
var React = __toESM(require("react"));
function useCallbackRef(callback) {
const callbackRef = React.useRef(callback);
React.useEffect(() => {
callbackRef.current = callback;
});
return React.useMemo(() => (...args) => callbackRef.current?.(...args), []);
}
//# sourceMappingURL=index.js.map
@@ -0,0 +1,12 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.es2015_symbol = void 0;
const base_config_1 = require("./base-config");
exports.es2015_symbol = {
libs: [],
variables: [['SymbolConstructor', base_config_1.TYPE]],
};
@@ -0,0 +1,12 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/v4";
test("void", () => {
const v = z.void();
v.parse(undefined);
expect(() => v.parse(null)).toThrow();
expect(() => v.parse("")).toThrow();
type v = z.infer<typeof v>;
expectTypeOf<v>().toEqualTypeOf<void>();
});
@@ -0,0 +1 @@
{"version":3,"file":"grip-vertical.js","sources":["../../../src/icons/grip-vertical.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name GripVertical\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8Y2lyY2xlIGN4PSI5IiBjeT0iMTIiIHI9IjEiIC8+CiAgPGNpcmNsZSBjeD0iOSIgY3k9IjUiIHI9IjEiIC8+CiAgPGNpcmNsZSBjeD0iOSIgY3k9IjE5IiByPSIxIiAvPgogIDxjaXJjbGUgY3g9IjE1IiBjeT0iMTIiIHI9IjEiIC8+CiAgPGNpcmNsZSBjeD0iMTUiIGN5PSI1IiByPSIxIiAvPgogIDxjaXJjbGUgY3g9IjE1IiBjeT0iMTkiIHI9IjEiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/grip-vertical\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst GripVertical = createLucideIcon('GripVertical', [\n ['circle', { cx: '9', cy: '12', r: '1', key: '1vctgf' }],\n ['circle', { cx: '9', cy: '5', r: '1', key: 'hp0tcf' }],\n ['circle', { cx: '9', cy: '19', r: '1', key: 'fkjjf6' }],\n ['circle', { cx: '15', cy: '12', r: '1', key: '1tmaij' }],\n ['circle', { cx: '15', cy: '5', r: '1', key: '19l28e' }],\n ['circle', { cx: '15', cy: '19', r: '1', key: 'f4zoj3' }],\n]);\n\nexport default GripVertical;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAe,iBAAiB,cAAgB,CAAA,CAAA,CAAA;AAAA,CACpD,CAAA,CAAC,QAAU,CAAA,CAAA,CAAA,CAAE,EAAI,CAAA,CAAA,CAAA,CAAA,CAAA,EAAK,CAAI,CAAA,CAAA,CAAA,IAAA,CAAM,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,GAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAU,CAAA,CAAA;AAAA,CACvD,CAAA,CAAC,QAAU,CAAA,CAAA,CAAA,CAAE,EAAI,CAAA,CAAA,CAAA,CAAA,CAAA,EAAK,CAAI,CAAA,CAAA,CAAA,GAAA,CAAK,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,GAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAU,CAAA,CAAA;AAAA,CACtD,CAAA,CAAC,QAAU,CAAA,CAAA,CAAA,CAAE,EAAI,CAAA,CAAA,CAAA,CAAA,CAAA,EAAK,CAAI,CAAA,CAAA,CAAA,IAAA,CAAM,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,GAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAU,CAAA,CAAA;AAAA,CACvD,CAAA,CAAC,QAAU,CAAA,CAAA,CAAA,CAAE,EAAI,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAM,CAAI,CAAA,CAAA,CAAA,IAAA,CAAM,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,GAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAU,CAAA,CAAA;AAAA,CACxD,CAAA,CAAC,QAAU,CAAA,CAAA,CAAA,CAAE,EAAI,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAM,CAAI,CAAA,CAAA,CAAA,GAAA,CAAK,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,GAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAU,CAAA,CAAA;AAAA,CACvD,CAAA,CAAC,QAAU,CAAA,CAAA,CAAA,CAAE,EAAI,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAM,CAAI,CAAA,CAAA,CAAA,IAAA,CAAM,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,GAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAU,CAAA;AAC1D,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1 @@
{"version":3,"file":"server.js","sources":["../../../src/icons/server.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Server\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cmVjdCB3aWR0aD0iMjAiIGhlaWdodD0iOCIgeD0iMiIgeT0iMiIgcng9IjIiIHJ5PSIyIiAvPgogIDxyZWN0IHdpZHRoPSIyMCIgaGVpZ2h0PSI4IiB4PSIyIiB5PSIxNCIgcng9IjIiIHJ5PSIyIiAvPgogIDxsaW5lIHgxPSI2IiB4Mj0iNi4wMSIgeTE9IjYiIHkyPSI2IiAvPgogIDxsaW5lIHgxPSI2IiB4Mj0iNi4wMSIgeTE9IjE4IiB5Mj0iMTgiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/server\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst Server = createLucideIcon('Server', [\n ['rect', { width: '20', height: '8', x: '2', y: '2', rx: '2', ry: '2', key: 'ngkwjq' }],\n ['rect', { width: '20', height: '8', x: '2', y: '14', rx: '2', ry: '2', key: 'iecqi9' }],\n ['line', { x1: '6', x2: '6.01', y1: '6', y2: '6', key: '16zg32' }],\n ['line', { x1: '6', x2: '6.01', y1: '18', y2: '18', key: 'nzw8ys' }],\n]);\n\nexport default Server;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAS,iBAAiB,QAAU,CAAA,CAAA,CAAA;AAAA,CAAA,CACxC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,KAAO,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAQ,CAAA,CAAA,CAAA,CAAK,CAAA,CAAA,CAAA,EAAG,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAG,KAAK,CAAI,CAAA,CAAA,CAAA,GAAA,CAAK,CAAA,CAAA,EAAI,CAAA,CAAA,CAAA,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAU,CAAA,CAAA;AAAA,CAAA,CACtF,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,KAAO,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAQ,CAAA,CAAA,CAAA,CAAK,CAAA,CAAA,CAAA,EAAG,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAG,MAAM,CAAI,CAAA,CAAA,CAAA,GAAA,CAAK,CAAA,CAAA,EAAI,CAAA,CAAA,CAAA,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAU,CAAA,CAAA;AAAA,CACvF,CAAA,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAE,CAAA,CAAA,CAAA,EAAI,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAI,CAAQ,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,CAAI,CAAA,CAAA,CAAA,CAAK,CAAA,CAAA,CAAA,CAAA,CAAI,CAAA,CAAA,CAAA,CAAK,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CACjE,CAAA,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAE,CAAA,CAAA,CAAA,EAAI,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAI,CAAQ,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,CAAI,CAAA,CAAA,CAAA,CAAA,CAAM,CAAA,CAAA,CAAA,CAAA,CAAI,CAAA,CAAA,CAAA,CAAA,CAAM,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AACrE,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const baseLogFactory = require("base-log-factory");
const pc = require("picocolors");
const colors = require("./colors.js");
class ColorfulAppender extends baseLogFactory.ConsoleAppender {
/**
* Constructor (构造函数)
*/
constructor(opts = {}) {
super(opts.layout);
this.name = "colorful";
this.colors = opts.colors || colors.colors;
}
/**
* Write log (写入日志)
* @param event Log event (日志事件)
*/
write(event) {
const { layout } = this;
if (layout) {
console.log(this.color(layout.format(event), event));
} else {
console.log(this.color(baseLogFactory.basicLogPrefix(event, this.dateFormat), event), ...event.message);
}
}
color(str, event) {
return pc[this.colors[event.level]](str);
}
}
exports.ColorfulAppender = ColorfulAppender;
@@ -0,0 +1,39 @@
<!-- BEGIN MICROSOFT SECURITY.MD V0.0.9 BLOCK -->
## Security
Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations.
If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/security.md/definition), please report it to us as described below.
## Reporting Security Issues
**Please do not report security vulnerabilities through public GitHub issues.**
Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report).
You should receive a response within 24 hours. If for some reason you do not, please follow up using the messaging functionality found at the bottom of the Activity tab on your vulnerability report on [https://msrc.microsoft.com/report/vulnerability](https://msrc.microsoft.com/report/vulnerability/) or via email as described in the instructions at the bottom of [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report). Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc) or on MSRC's [FAQ page for reporting an issue](https://www.microsoft.com/en-us/msrc/faqs-report-an-issue).
Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
* Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
* Full paths of source file(s) related to the manifestation of the issue
* The location of the affected source code (tag/branch/commit or direct URL)
* Any special configuration required to reproduce the issue
* Step-by-step instructions to reproduce the issue
* Proof-of-concept or exploit code (if possible)
* Impact of the issue, including how an attacker might exploit the issue
This information will help us triage your report more quickly.
If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/security.md/msrc/bounty) page for more details about our active programs.
## Preferred Languages
We prefer all communications to be in English.
## Policy
Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/security.md/cvd).
<!-- END MICROSOFT SECURITY.MD BLOCK -->
@@ -0,0 +1,45 @@
'use strict'
const assert = require('node:assert')
const { URLSerializer } = require('../fetch/data-url')
const { isValidHeaderName } = require('../fetch/util')
/**
* @see https://url.spec.whatwg.org/#concept-url-equals
* @param {URL} A
* @param {URL} B
* @param {boolean | undefined} excludeFragment
* @returns {boolean}
*/
function urlEquals (A, B, excludeFragment = false) {
const serializedA = URLSerializer(A, excludeFragment)
const serializedB = URLSerializer(B, excludeFragment)
return serializedA === serializedB
}
/**
* @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262
* @param {string} header
*/
function getFieldValues (header) {
assert(header !== null)
const values = []
for (let value of header.split(',')) {
value = value.trim()
if (isValidHeaderName(value)) {
values.push(value)
}
}
return values
}
module.exports = {
urlEquals,
getFieldValues
}
@@ -0,0 +1 @@
{"version":3,"file":"magic-string.cjs.js","sources":["../src/BitSet.js","../src/Chunk.js","../src/SourceMap.js","../src/utils/guessIndent.js","../src/utils/getRelativePath.js","../src/utils/isObject.js","../src/utils/getLocator.js","../src/utils/Mappings.js","../src/MagicString.js","../src/Bundle.js","../src/index-legacy.js"],"sourcesContent":["export default class BitSet {\n\tconstructor(arg) {\n\t\tthis.bits = arg instanceof BitSet ? arg.bits.slice() : [];\n\t}\n\n\tadd(n) {\n\t\tthis.bits[n >> 5] |= 1 << (n & 31);\n\t}\n\n\thas(n) {\n\t\treturn !!(this.bits[n >> 5] & (1 << (n & 31)));\n\t}\n}\n","export default class Chunk {\n\tconstructor(start, end, content) {\n\t\tthis.start = start;\n\t\tthis.end = end;\n\t\tthis.original = content;\n\n\t\tthis.intro = '';\n\t\tthis.outro = '';\n\n\t\tthis.content = content;\n\t\tthis.storeName = false;\n\t\tthis.edited = false;\n\n\t\tif (DEBUG) {\n\t\t\t// we make these non-enumerable, for sanity while debugging\n\t\t\tObject.defineProperties(this, {\n\t\t\t\tprevious: { writable: true, value: null },\n\t\t\t\tnext: { writable: true, value: null },\n\t\t\t});\n\t\t} else {\n\t\t\tthis.previous = null;\n\t\t\tthis.next = null;\n\t\t}\n\t}\n\n\tappendLeft(content) {\n\t\tthis.outro += content;\n\t}\n\n\tappendRight(content) {\n\t\tthis.intro = this.intro + content;\n\t}\n\n\tclone() {\n\t\tconst chunk = new Chunk(this.start, this.end, this.original);\n\n\t\tchunk.intro = this.intro;\n\t\tchunk.outro = this.outro;\n\t\tchunk.content = this.content;\n\t\tchunk.storeName = this.storeName;\n\t\tchunk.edited = this.edited;\n\n\t\treturn chunk;\n\t}\n\n\tcontains(index) {\n\t\treturn this.start < index && index < this.end;\n\t}\n\n\teachNext(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.next;\n\t\t}\n\t}\n\n\teachPrevious(fn) {\n\t\tlet chunk = this;\n\t\twhile (chunk) {\n\t\t\tfn(chunk);\n\t\t\tchunk = chunk.previous;\n\t\t}\n\t}\n\n\tedit(content, storeName, contentOnly) {\n\t\tthis.content = content;\n\t\tif (!contentOnly) {\n\t\t\tthis.intro = '';\n\t\t\tthis.outro = '';\n\t\t}\n\t\tthis.storeName = storeName;\n\n\t\tthis.edited = true;\n\n\t\treturn this;\n\t}\n\n\tprependLeft(content) {\n\t\tthis.outro = content + this.outro;\n\t}\n\n\tprependRight(content) {\n\t\tthis.intro = content + this.intro;\n\t}\n\n\treset() {\n\t\tthis.intro = '';\n\t\tthis.outro = '';\n\t\tif (this.edited) {\n\t\t\tthis.content = this.original;\n\t\t\tthis.storeName = false;\n\t\t\tthis.edited = false;\n\t\t}\n\t}\n\n\tsplit(index) {\n\t\tconst sliceIndex = index - this.start;\n\n\t\tconst originalBefore = this.original.slice(0, sliceIndex);\n\t\tconst originalAfter = this.original.slice(sliceIndex);\n\n\t\tthis.original = originalBefore;\n\n\t\tconst newChunk = new Chunk(index, this.end, originalAfter);\n\t\tnewChunk.outro = this.outro;\n\t\tthis.outro = '';\n\n\t\tthis.end = index;\n\n\t\tif (this.edited) {\n\t\t\t// after split we should save the edit content record into the correct chunk\n\t\t\t// to make sure sourcemap correct\n\t\t\t// For example:\n\t\t\t// ' test'.trim()\n\t\t\t// split -> ' ' + 'test'\n\t\t\t// ✔️ edit -> '' + 'test'\n\t\t\t// ✖️ edit -> 'test' + ''\n\t\t\t// TODO is this block necessary?...\n\t\t\tnewChunk.edit('', false);\n\t\t\tthis.content = '';\n\t\t} else {\n\t\t\tthis.content = originalBefore;\n\t\t}\n\n\t\tnewChunk.next = this.next;\n\t\tif (newChunk.next) newChunk.next.previous = newChunk;\n\t\tnewChunk.previous = this;\n\t\tthis.next = newChunk;\n\n\t\treturn newChunk;\n\t}\n\n\ttoString() {\n\t\treturn this.intro + this.content + this.outro;\n\t}\n\n\ttrimEnd(rx) {\n\t\tthis.outro = this.outro.replace(rx, '');\n\t\tif (this.outro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tthis.split(this.start + trimmed.length).edit('', undefined, true);\n\t\t\t\tif (this.edited) {\n\t\t\t\t\t// save the change, if it has been edited\n\t\t\t\t\tthis.edit(trimmed, this.storeName, true);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.intro = this.intro.replace(rx, '');\n\t\t\tif (this.intro.length) return true;\n\t\t}\n\t}\n\n\ttrimStart(rx) {\n\t\tthis.intro = this.intro.replace(rx, '');\n\t\tif (this.intro.length) return true;\n\n\t\tconst trimmed = this.content.replace(rx, '');\n\n\t\tif (trimmed.length) {\n\t\t\tif (trimmed !== this.content) {\n\t\t\t\tconst newChunk = this.split(this.end - trimmed.length);\n\t\t\t\tif (this.edited) {\n\t\t\t\t\t// save the change, if it has been edited\n\t\t\t\t\tnewChunk.edit(trimmed, this.storeName, true);\n\t\t\t\t}\n\t\t\t\tthis.edit('', undefined, true);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tthis.edit('', undefined, true);\n\n\t\t\tthis.outro = this.outro.replace(rx, '');\n\t\t\tif (this.outro.length) return true;\n\t\t}\n\t}\n}\n","import { encode } from '@jridgewell/sourcemap-codec'Line truncated
@@ -0,0 +1,2 @@
import { Fragment, jsxDEV } from "./jsx-dev-runtime.js";
export { Fragment, jsxDEV as jsx, jsxDEV as jsxs };
@@ -0,0 +1 @@
{"version":3,"file":"inMemoryEventStore.js","sourceRoot":"","sources":["../../../../src/examples/shared/inMemoryEventStore.ts"],"names":[],"mappings":";;;AAGA;;;;GAIG;AACH,MAAa,kBAAkB;IAA/B;QACY,WAAM,GAA+D,IAAI,GAAG,EAAE,CAAC;IAoE3F,CAAC;IAlEG;;OAEG;IACK,eAAe,CAAC,QAAgB;QACpC,OAAO,GAAG,QAAQ,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC;IACtF,CAAC;IAED;;OAEG;IACK,sBAAsB,CAAC,OAAe;QAC1C,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACjC,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC5C,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,UAAU,CAAC,QAAgB,EAAE,OAAuB;QACtD,MAAM,OAAO,GAAG,IAAI,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC;QAC/C,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC;QAChD,OAAO,OAAO,CAAC;IACnB,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,iBAAiB,CACnB,WAAmB,EACnB,EAAE,IAAI,EAAyE;QAE/E,IAAI,CAAC,WAAW,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;YAChD,OAAO,EAAE,CAAC;QACd,CAAC;QAED,0CAA0C;QAC1C,MAAM,QAAQ,GAAG,IAAI,CAAC,sBAAsB,CAAC,WAAW,CAAC,CAAC;QAC1D,IAAI,CAAC,QAAQ,EAAE,CAAC;YACZ,OAAO,EAAE,CAAC;QACd,CAAC;QAED,IAAI,cAAc,GAAG,KAAK,CAAC;QAE3B,oDAAoD;QACpD,MAAM,YAAY,GAAG,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAEzF,KAAK,MAAM,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,aAAa,EAAE,OAAO,EAAE,CAAC,IAAI,YAAY,EAAE,CAAC;YACzE,2CAA2C;YAC3C,IAAI,aAAa,KAAK,QAAQ,EAAE,CAAC;gBAC7B,SAAS;YACb,CAAC;YAED,qDAAqD;YACrD,IAAI,OAAO,KAAK,WAAW,EAAE,CAAC;gBAC1B,cAAc,GAAG,IAAI,CAAC;gBACtB,SAAS;YACb,CAAC;YAED,IAAI,cAAc,EAAE,CAAC;gBACjB,MAAM,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACjC,CAAC;QACL,CAAC;QACD,OAAO,QAAQ,CAAC;IACpB,CAAC;CACJ;AArED,gDAqEC"}
@@ -0,0 +1,72 @@
'use client'
import React from 'react'
export interface ClientOnlyProps {
/**
* The children to render when the JS is loaded.
*/
children: React.ReactNode
/**
* The fallback component to render if the JS is not yet loaded.
*/
fallback?: React.ReactNode
}
/**
* Render the children only after the JS has loaded client-side. Use an optional
* fallback component if the JS is not yet loaded.
*
* @example
* Render a Chart component if JS loads, renders a simple FakeChart
* component server-side or if there is no JS. The FakeChart can have only the
* UI without the behavior or be a loading spinner or skeleton.
*
* ```tsx
* return (
* <ClientOnly fallback={<FakeChart />}>
* <Chart />
* </ClientOnly>
* )
* ```
*/
export function ClientOnly({ children, fallback = null }: ClientOnlyProps) {
return useHydrated() ? (
<React.Fragment>{children}</React.Fragment>
) : (
<React.Fragment>{fallback}</React.Fragment>
)
}
/**
* Return a boolean indicating if the JS has been hydrated already.
* When doing Server-Side Rendering, the result will always be false.
* When doing Client-Side Rendering, the result will always be false on the
* first render and true from then on. Even if a new component renders it will
* always start with true.
*
* @example
* ```tsx
* // Disable a button that needs JS to work.
* let hydrated = useHydrated()
* return (
* <button type="button" disabled={!hydrated} onClick={doSomethingCustom}>
* Click me
* </button>
* )
* ```
* @returns True if the JS has been hydrated already, false otherwise.
*/
export function useHydrated(): boolean {
return React.useSyncExternalStore(
subscribe,
() => true,
() => false,
)
}
function subscribe() {
return () => {
// noop
}
}
@@ -0,0 +1 @@
{"version":3,"file":"start.mjs","sources":["../../../src/view/start.ts"],"sourcesContent":["import { secondsToMilliseconds } from \"motion-utils\"\nimport { GroupAnimation } from \"../animation/GroupAnimation\"\nimport { NativeAnimation } from \"../animation/NativeAnimation\"\nimport { NativeAnimationWrapper } from \"../animation/NativeAnimationWrapper\"\nimport { AnimationPlaybackControls } from \"../animation/types\"\nimport { getValueTransition } from \"../animation/utils/get-value-transition\"\nimport { mapEasingToNativeEasing } from \"../animation/waapi/easing/map-easing\"\nimport { applyGeneratorOptions } from \"../animation/waapi/utils/apply-generator\"\nimport type { ViewTransitionBuilder } from \"./index\"\nimport { ViewTransitionTarget } from \"./types\"\nimport { chooseLayerType } from \"./utils/choose-layer-type\"\nimport { css } from \"./utils/css\"\nimport { getViewAnimationLayerInfo } from \"./utils/get-layer-info\"\nimport { getViewAnimations } from \"./utils/get-view-animations\"\nimport { hasTarget } from \"./utils/has-target\"\n\nconst definitionNames = [\"layout\", \"enter\", \"exit\", \"new\", \"old\"] as const\n\nexport function startViewAnimation(\n builder: ViewTransitionBuilder\n): Promise<GroupAnimation> {\n const { update, targets, options: defaultOptions } = builder\n\n if (!document.startViewTransition) {\n return new Promise(async (resolve) => {\n await update()\n resolve(new GroupAnimation([]))\n })\n }\n\n // TODO: Go over existing targets and ensure they all have ids\n\n /**\n * If we don't have any animations defined for the root target,\n * remove it from being captured.\n */\n if (!hasTarget(\"root\", targets)) {\n css.set(\":root\", {\n \"view-transition-name\": \"none\",\n })\n }\n\n /**\n * Set the timing curve to linear for all view transition layers.\n * This gets baked into the keyframes, which can't be changed\n * without breaking the generated animation.\n *\n * This allows us to set easing via updateTiming - which can be changed.\n */\n css.set(\n \"::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*)\",\n { \"animation-timing-function\": \"linear !important\" }\n )\n\n css.commit() // Write\n\n const transition = document.startViewTransition(async () => {\n await update()\n\n // TODO: Go over new targets and ensure they all have ids\n })\n\n transition.finished.finally(() => {\n css.remove() // Write\n })\n\n return new Promise((resolve) => {\n transition.ready.then(() => {\n const generatedViewAnimations = getViewAnimations()\n\n const animations: AnimationPlaybackControls[] = []\n\n /**\n * Create animations for each of our explicitly-defined subjects.\n */\n targets.forEach((definition, target) => {\n // TODO: If target is not \"root\", resolve elements\n // and iterate over each\n for (const key of definitionNames) {\n if (!definition[key]) continue\n const { keyframes, options } =\n definition[key as keyof ViewTransitionTarget]!\n\n for (let [valueName, valueKeyframes] of Object.entries(\n keyframes\n )) {\n if (!valueKeyframes) continue\n\n const valueOptions = {\n ...getValueTransition(\n defaultOptions as any,\n valueName\n ),\n ...getValueTransition(options as any, valueName),\n }\n\n const type = chooseLayerType(\n key as keyof ViewTransitionTarget\n )\n\n /**\n * If this is an opacity animation, and keyframes are not an array,\n * we need to convert them into an array and set an initial value.\n */\n if (\n valueName === \"opacity\" &&\n !Array.isArray(valueKeyframes)\n ) {\n const initialValue = type === \"new\" ? 0 : 1\n valueKeyframes = [initialValue, valueKeyframes]\n }\n\n /**\n * Resolve stagger function if provided.\n */\n if (typeof valueOptions.delay === \"function\") {\n valueOptions.delay = valueOptions.delay(0, 1)\n }\n\n valueOptions.duration &&= secondsToMilliseconds(\n Line truncated
@@ -0,0 +1 @@
{"version":3,"file":"book-audio.js","sources":["../../../src/icons/book-audio.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name BookAudio\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMTIgNnY3IiAvPgogIDxwYXRoIGQ9Ik0xNiA4djMiIC8+CiAgPHBhdGggZD0iTTQgMTkuNXYtMTVBMi41IDIuNSAwIDAgMSA2LjUgMkgxOWExIDEgMCAwIDEgMSAxdjE4YTEgMSAwIDAgMS0xIDFINi41YTEgMSAwIDAgMSAwLTVIMjAiIC8+CiAgPHBhdGggZD0iTTggOHYzIiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/book-audio\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst BookAudio = createLucideIcon('BookAudio', [\n ['path', { d: 'M12 6v7', key: '1f6ttz' }],\n ['path', { d: 'M16 8v3', key: 'gejaml' }],\n [\n 'path',\n {\n d: 'M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20',\n key: 'k3hazp',\n },\n ],\n ['path', { d: 'M8 8v3', key: '1qzp49' }],\n]);\n\nexport default BookAudio;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAY,iBAAiB,WAAa,CAAA,CAAA,CAAA;AAAA,CAAA,CAC9C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACxC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CACxC,CAAA,CAAA;AAAA,CAAA,CAAA,CAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACA,CAAA,CAAA,CAAA,CAAA;AAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACH,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACP,CAAA,CAAA,CAAA,CAAA;AAAA,CACF,CAAA,CAAA,CAAA;AAAA,CAAA,CACA,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAU,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AACzC,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1 @@
{"version":3,"file":"copyleft.js","sources":["../../../src/icons/copyleft.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Copyleft\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSIxMCIgLz4KICA8cGF0aCBkPSJNOS4xNyAxNC44M2E0IDQgMCAxIDAgMC01LjY2IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/copyleft\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst Copyleft = createLucideIcon('Copyleft', [\n ['circle', { cx: '12', cy: '12', r: '10', key: '1mglay' }],\n ['path', { d: 'M9.17 14.83a4 4 0 1 0 0-5.66', key: '1sveal' }],\n]);\n\nexport default Copyleft;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAW,iBAAiB,UAAY,CAAA,CAAA,CAAA;AAAA,CAC5C,CAAA,CAAC,QAAU,CAAA,CAAA,CAAA,CAAE,EAAI,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAM,CAAI,CAAA,CAAA,CAAA,IAAA,CAAM,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM,GAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAU,CAAA,CAAA;AAAA,CAAA,CACzD,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAgC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC/D,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,2 @@
import type { LibDefinition } from '../variable';
export declare const es2023_array: LibDefinition;
@@ -0,0 +1 @@
{"version":3,"file":"redirect.cjs","names":[],"sources":["../../src/redirect.ts"],"sourcesContent":["import type { NavigateOptions } from './link'\nimport type { AnyRouter, RegisteredRouter } from './router'\nimport type { ParsedLocation } from './location'\n\nexport type AnyRedirect = Redirect<any, any, any, any, any>\n\n/**\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType)\n */\nexport type Redirect<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = undefined,\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = Response & {\n options: NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {\n /**\n * @internal\n * A **trusted** built location that can be used to redirect to.\n */\n _builtLocation?: ParsedLocation\n }\n redirectHandled?: boolean\n}\n\nexport type RedirectOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = undefined,\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = {\n href?: string\n /**\n * @deprecated Use `statusCode` instead\n **/\n code?: number\n /**\n * The HTTP status code to use when redirecting.\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType#statuscode-property)\n */\n statusCode?: number\n /**\n * If provided, will throw the redirect object instead of returning it. This can be useful in places where `throwing` in a function might cause it to have a return type of `never`. In that case, you can use `redirect({ throw: true })` to throw the redirect object instead of returning it.\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType#throw-property)\n */\n throw?: any\n /**\n * The HTTP headers to use when redirecting.\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType#headers-property)\n */\n headers?: HeadersInit\n /**\n * @internal\n * A **trusted** built location that can be used to redirect to.\n */\n _builtLocation?: ParsedLocation\n} & NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>\n\nexport type ResolvedRedirect<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string = '',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '',\n> = Redirect<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>\n\n/**\n * Options for route-bound redirect, where 'from' is automatically set.\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType)\n */\nexport type RedirectOptionsRoute<\n TDefaultFrom extends string = string,\n TRouter extends AnyRouter = RegisteredRouter,\n TTo extends string | undefined = undefined,\n TMaskTo extends string = '',\n> = Omit<\n RedirectOptions<TRouter, TDefaultFrom, TTo, TDefaultFrom, TMaskTo>,\n 'from'\n>\n\n/**\n * A redirect function bound to a specific route, with 'from' pre-set to the route's fullPath.\n * This enables relative redirects like `Route.redirect({ to: './overview' })`.\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType)\n */\nexport interface RedirectFnRoute<in out TDefaultFrom extends string = string> {\n <\n TRouter extends AnyRouter = RegisteredRouter,\n const TTo extends string | undefined = undefined,\n const TMaskTo extends string = '',\n >(\n opts: RedirectOptionsRoute<TDefaultFrom, TRouter, TTo, TMaskTo>,\n ): Redirect<TRouter, TDefaultFrom, TTo, TDefaultFrom, TMaskTo>\n}\n\n/**\n * Create a redirect Response understood by TanStack Router.\n *\n * Use from route `loader`/`beforeLoad` or server functions to trigger a\n * navigation. If `throw: true` is set, the redirect is thrown instead of\n * returned. When an absolute `href` is supplied and `reloadDocument` is not\n * set, a full-document navigation is inferred.\n *\n * @param opts Options for the redirect. Common fields:\n * - `href`: absolute URL for external redirects; infers `reloadDocument`.\n * - `statusCode`: HTTP status code to use (defaults to 307).\n * - `headers`: additional headers to include on the Response.\n * - Standard navigation options like `to`, `params`, `search`, `replace`,\n * and `reloadDocument` for internal redirects.\n * @returns A Response augmented with router navigation options.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction\n */\nexport function redirect<\n TRouter extends AnyRouter = RegisteredRouter,\n const TTo extends string | undefined = '.',\n const TFrom extends string = string,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(\n opts: RedirectOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n): Redirect<TRouter, TFrom, TTo, TMaskFrLine truncated
@@ -0,0 +1 @@
{"version":3,"file":"panels-right-bottom.js","sources":["../../../src/icons/panels-right-bottom.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name PanelsRightBottom\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cmVjdCB3aWR0aD0iMTgiIGhlaWdodD0iMTgiIHg9IjMiIHk9IjMiIHJ4PSIyIiAvPgogIDxwYXRoIGQ9Ik0zIDE1aDEyIiAvPgogIDxwYXRoIGQ9Ik0xNSAzdjE4IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/panels-right-bottom\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst PanelsRightBottom = createLucideIcon('PanelsRightBottom', [\n ['rect', { width: '18', height: '18', x: '3', y: '3', rx: '2', key: 'afitv7' }],\n ['path', { d: 'M3 15h12', key: '1wkqb3' }],\n ['path', { d: 'M15 3v18', key: '14nvp0' }],\n]);\n\nexport default PanelsRightBottom;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAoB,iBAAiB,mBAAqB,CAAA,CAAA,CAAA;AAAA,CAAA,CAC9D,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAO,MAAM,CAAQ,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM,CAAG,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,GAAG,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAI,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC9E,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAY,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACzC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAY,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC3C,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1 @@
{"version":3,"names":["_caching","require","fs","_fs2","data","makeStaticFileCache","fn","makeStrongCache","filepath","cache","cached","invalidate","fileMtime","readFile","nodeFs","existsSync","statSync","mtime","e","code"],"sources":["../../../src/config/files/utils.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\n\nimport { makeStrongCache } from \"../caching.ts\";\nimport type { CacheConfigurator } from \"../caching.ts\";\nimport * as fs from \"../../gensync-utils/fs.ts\";\nimport nodeFs from \"node:fs\";\n\nexport function makeStaticFileCache<T>(\n fn: (filepath: string, contents: string) => T,\n) {\n return makeStrongCache(function* (\n filepath: string,\n cache: CacheConfigurator<void>,\n ): Handler<null | T> {\n const cached = cache.invalidate(() => fileMtime(filepath));\n\n if (cached === null) {\n return null;\n }\n\n return fn(filepath, yield* fs.readFile(filepath, \"utf8\"));\n });\n}\n\nfunction fileMtime(filepath: string): number | null {\n if (!nodeFs.existsSync(filepath)) return null;\n\n try {\n return +nodeFs.statSync(filepath).mtime;\n } catch (e) {\n if (e.code !== \"ENOENT\" && e.code !== \"ENOTDIR\") throw e;\n }\n\n return null;\n}\n"],"mappings":";;;;;;AAEA,IAAAA,QAAA,GAAAC,OAAA;AAEA,IAAAC,EAAA,GAAAD,OAAA;AACA,SAAAE,KAAA;EAAA,MAAAC,IAAA,GAAAH,OAAA;EAAAE,IAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEO,SAASC,mBAAmBA,CACjCC,EAA6C,EAC7C;EACA,OAAO,IAAAC,wBAAe,EAAC,WACrBC,QAAgB,EAChBC,KAA8B,EACX;IACnB,MAAMC,MAAM,GAAGD,KAAK,CAACE,UAAU,CAAC,MAAMC,SAAS,CAACJ,QAAQ,CAAC,CAAC;IAE1D,IAAIE,MAAM,KAAK,IAAI,EAAE;MACnB,OAAO,IAAI;IACb;IAEA,OAAOJ,EAAE,CAACE,QAAQ,EAAE,OAAON,EAAE,CAACW,QAAQ,CAACL,QAAQ,EAAE,MAAM,CAAC,CAAC;EAC3D,CAAC,CAAC;AACJ;AAEA,SAASI,SAASA,CAACJ,QAAgB,EAAiB;EAClD,IAAI,CAACM,KAAKA,CAAC,CAACC,UAAU,CAACP,QAAQ,CAAC,EAAE,OAAO,IAAI;EAE7C,IAAI;IACF,OAAO,CAACM,KAAKA,CAAC,CAACE,QAAQ,CAACR,QAAQ,CAAC,CAACS,KAAK;EACzC,CAAC,CAAC,OAAOC,CAAC,EAAE;IACV,IAAIA,CAAC,CAACC,IAAI,KAAK,QAAQ,IAAID,CAAC,CAACC,IAAI,KAAK,SAAS,EAAE,MAAMD,CAAC;EAC1D;EAEA,OAAO,IAAI;AACb;AAAC","ignoreList":[]}
@@ -0,0 +1,603 @@
/**
* @fileoverview Rule to flag constant comparisons and logical expressions that always/never short circuit
* @author Jordan Eldredge <https://jordaneldredge.com>
*/
"use strict";
const {
isNullLiteral,
isConstant,
isReferenceToGlobalVariable,
isLogicalAssignmentOperator,
ECMASCRIPT_GLOBALS,
} = require("./utils/ast-utils");
const NUMERIC_OR_STRING_BINARY_OPERATORS = new Set([
"+",
"-",
"*",
"/",
"%",
"|",
"^",
"&",
"**",
"<<",
">>",
">>>",
]);
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Checks whether or not a node is `null` or `undefined`. Similar to the one
* found in ast-utils.js, but this one correctly handles the edge case that
* `undefined` has been redefined.
* @param {Scope} scope Scope in which the expression was found.
* @param {ASTNode} node A node to check.
* @returns {boolean} Whether or not the node is a `null` or `undefined`.
* @public
*/
function isNullOrUndefined(scope, node) {
return (
isNullLiteral(node) ||
(node.type === "Identifier" &&
node.name === "undefined" &&
isReferenceToGlobalVariable(scope, node)) ||
(node.type === "UnaryExpression" && node.operator === "void")
);
}
/**
* Test if an AST node has a statically knowable constant nullishness. Meaning,
* it will always resolve to a constant value of either: `null`, `undefined`
* or not `null` _or_ `undefined`. An expression that can vary between those
* three states at runtime would return `false`.
* @param {Scope} scope The scope in which the node was found.
* @param {ASTNode} node The AST node being tested.
* @param {boolean} nonNullish if `true` then nullish values are not considered constant.
* @returns {boolean} Does `node` have constant nullishness?
*/
function hasConstantNullishness(scope, node, nonNullish) {
if (nonNullish && isNullOrUndefined(scope, node)) {
return false;
}
switch (node.type) {
case "ObjectExpression": // Objects are never nullish
case "ArrayExpression": // Arrays are never nullish
case "ArrowFunctionExpression": // Functions never nullish
case "FunctionExpression": // Functions are never nullish
case "ClassExpression": // Classes are never nullish
case "NewExpression": // Objects are never nullish
case "Literal": // Nullish, or non-nullish, literals never change
case "TemplateLiteral": // A string is never nullish
case "UpdateExpression": // Numbers are never nullish
case "BinaryExpression": // Numbers, strings, or booleans are never nullish
return true;
case "CallExpression": {
if (node.callee.type !== "Identifier") {
return false;
}
const functionName = node.callee.name;
return (
(functionName === "Boolean" ||
functionName === "String" ||
functionName === "Number") &&
isReferenceToGlobalVariable(scope, node.callee)
);
}
case "LogicalExpression": {
return (
node.operator === "??" &&
hasConstantNullishness(scope, node.right, true)
);
}
case "AssignmentExpression":
if (node.operator === "=") {
return hasConstantNullishness(scope, node.right, nonNullish);
}
/*
* Handling short-circuiting assignment operators would require
* walking the scope. We won't attempt that (for now...) /
*/
if (isLogicalAssignmentOperator(node.operator)) {
return false;
}
/*
* The remaining assignment expressions all result in a numeric or
* string (non-nullish) value:
* "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&="
*/
return true;
case "UnaryExpression":
/*
* "void" Always returns `undefined`
* "typeof" All types are strings, and thus non-nullish
* "!" Boolean is never nullish
* "delete" Returns a boolean, which is never nullish
* Math operators always return numbers or strings, neither of which
* are non-nullish "+", "-", "~"
*/
return true;
case "SequenceExpression": {
const last = node.expressions.at(-1);
return hasConstantNullishness(scope, last, nonNullish);
}
case "Identifier":
return (
node.name === "undefined" &&
isReferenceToGlobalVariable(scope, node)
);
case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior.
case "JSXFragment":
return false;
default:
return false;
}
}
/**
* Test if an AST node is a boolean value that never changes. Specifically we
* test for:
* 1. Literal booleans (`true` or `false`)
* 2. Unary `!` expressions with a constant value
* 3. Constant booleans created via the `Boolean` global function
* @param {Scope} scope The scope in which the node was found.
* @param {ASTNode} node The node to test
* @returns {boolean} Is `node` guaranteed to be a boolean?
*/
function isStaticBoolean(scope, node) {
switch (node.type) {
case "Literal":
return typeof node.value === "boolean";
case "CallExpression":
return (
node.callee.type === "Identifier" &&
node.callee.name === "Boolean" &&
isReferenceToGlobalVariable(scope, node.callee) &&
(node.arguments.length === 0 ||
isConstant(scope, node.arguments[0], true))
);
case "UnaryExpression":
return (
node.operator === "!" && isConstant(scope, node.argument, true)
);
default:
return false;
}
}
/**
* Test if an AST node will always give the same result when compared to a
* boolean value. Note that comparison to boolean values is different than
* truthiness.
* https://262.ecma-international.org/5.1/#sec-11.9.3
*
* JavaScript `==` operator works by converting the boolean to `1` (true) or
* `+0` (false) and then checks the values `==` equality to that number.
* @param {Scope} scope The scope in which node was found.
* @param {ASTNode} node The node to test.
* @returns {boolean} Will `node` always coerce to the same boolean value?
*/
function hasConstantLooseBooleanComparison(scope, node) {
switch (node.type) {
case "ObjectExpression":
case "ClassExpression":
/**
* In theory objects like:
*
* `{toString: () => a}`
* `{valueOf: () => a}`
*
* Or a classes like:
*
* `class { static toString() { return a } }`
* `class { static valueOf() { return a } }`
*
* Are not constant verifiably when `inBooleanPosition` is
* false, but it's an edge case we've opted not to handle.
*/
return true;
case "ArrayExpression": {
const nonSpreadElements = node.elements.filter(
e =>
// Elements can be `null` in sparse arrays: `[,,]`;
e !== null && e.type !== "SpreadElement",
);
/*
* Possible future direction if needed: We could check if the
* single value would result in variable boolean comparison.
* For now we will err on the side of caution since `[x]` could
* evaluate to `[0]` or `[1]`.
*/
return node.elements.length === 0 || nonSpreadElements.length > 1;
}
case "ArrowFunctionExpression":
case "FunctionExpression":
return true;
case "UnaryExpression":
if (
node.operator === "void" || // Always returns `undefined`
node.operator === "typeof" // All `typeof` strings, when coerced to number, are not 0 or 1.
) {
return true;
}
if (node.operator === "!") {
return isConstant(scope, node.argument, true);
}
/*
* We won't try to reason about +, -, ~, or delete
* In theory, for the mathematical operators, we could look at the
* argument and try to determine if it coerces to a constant numeric
* value.
*/
return false;
case "NewExpression": // Objects might have custom `.valueOf` or `.toString`.
return false;
case "CallExpression": {
if (
node.callee.type === "Identifier" &&
node.callee.name === "Boolean" &&
isReferenceToGlobalVariable(scope, node.callee)
) {
return (
node.arguments.length === 0 ||
isConstant(scope, node.arguments[0], true)
);
}
return false;
}
case "Literal": // True or false, literals never change
return true;
case "Identifier":
return (
node.name === "undefined" &&
isReferenceToGlobalVariable(scope, node)
);
case "TemplateLiteral":
/*
* In theory we could try to check if the quasi are sufficient to
* prove that the expression will always be true, but it would be
* tricky to get right. For example: `000.${foo}000`
*/
return node.expressions.length === 0;
case "AssignmentExpression":
if (node.operator === "=") {
return hasConstantLooseBooleanComparison(scope, node.right);
}
/*
* Handling short-circuiting assignment operators would require
* walking the scope. We won't attempt that (for now...)
*
* The remaining assignment expressions all result in a numeric or
* string (non-nullish) values which could be truthy or falsy:
* "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&="
*/
return false;
case "SequenceExpression": {
const last = node.expressions.at(-1);
return hasConstantLooseBooleanComparison(scope, last);
}
case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior.
case "JSXFragment":
return false;
default:
return false;
}
}
/**
* Test if an AST node will always give the same result when _strictly_ compared
* to a boolean value. This can happen if the expression can never be boolean, or
* if it is always the same boolean value.
* @param {Scope} scope The scope in which the node was found.
* @param {ASTNode} node The node to test
* @returns {boolean} Will `node` always give the same result when compared to a
* static boolean value?
*/
function hasConstantStrictBooleanComparison(scope, node) {
switch (node.type) {
case "ObjectExpression": // Objects are not booleans
case "ArrayExpression": // Arrays are not booleans
case "ArrowFunctionExpression": // Functions are not booleans
case "FunctionExpression":
case "ClassExpression": // Classes are not booleans
case "NewExpression": // Objects are not booleans
case "TemplateLiteral": // Strings are not booleans
case "Literal": // True, false, or not boolean, literals never change.
case "UpdateExpression": // Numbers are not booleans
return true;
case "BinaryExpression":
return NUMERIC_OR_STRING_BINARY_OPERATORS.has(node.operator);
case "UnaryExpression": {
if (node.operator === "delete") {
return false;
}
if (node.operator === "!") {
return isConstant(scope, node.argument, true);
}
/*
* The remaining operators return either strings or numbers, neither
* of which are boolean.
*/
return true;
}
case "SequenceExpression": {
const last = node.expressions.at(-1);
return hasConstantStrictBooleanComparison(scope, last);
}
case "Identifier":
return (
node.name === "undefined" &&
isReferenceToGlobalVariable(scope, node)
);
case "AssignmentExpression":
if (node.operator === "=") {
return hasConstantStrictBooleanComparison(scope, node.right);
}
/*
* Handling short-circuiting assignment operators would require
* walking the scope. We won't attempt that (for now...)
*/
if (isLogicalAssignmentOperator(node.operator)) {
return false;
}
/*
* The remaining assignment expressions all result in either a number
* or a string, neither of which can ever be boolean.
*/
return true;
case "CallExpression": {
if (node.callee.type !== "Identifier") {
return false;
}
const functionName = node.callee.name;
if (
(functionName === "String" || functionName === "Number") &&
isReferenceToGlobalVariable(scope, node.callee)
) {
return true;
}
if (
functionName === "Boolean" &&
isReferenceToGlobalVariable(scope, node.callee)
) {
return (
node.arguments.length === 0 ||
isConstant(scope, node.arguments[0], true)
);
}
return false;
}
case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior.
case "JSXFragment":
return false;
default:
return false;
}
}
/**
* Test if an AST node will always result in a newly constructed object
* @param {Scope} scope The scope in which the node was found.
* @param {ASTNode} node The node to test
* @returns {boolean} Will `node` always be new?
*/
function isAlwaysNew(scope, node) {
switch (node.type) {
case "ObjectExpression":
case "ArrayExpression":
case "ArrowFunctionExpression":
case "FunctionExpression":
case "ClassExpression":
return true;
case "NewExpression": {
if (node.callee.type !== "Identifier") {
return false;
}
/*
* All the built-in constructors are always new, but
* user-defined constructors could return a sentinel
* object.
*
* Catching these is especially useful for primitive constructors
* which return boxed values, a surprising gotcha' in JavaScript.
*/
return (
Object.hasOwn(ECMASCRIPT_GLOBALS, node.callee.name) &&
isReferenceToGlobalVariable(scope, node.callee)
);
}
case "Literal":
// Regular expressions are objects, and thus always new
return typeof node.regex === "object";
case "SequenceExpression": {
const last = node.expressions.at(-1);
return isAlwaysNew(scope, last);
}
case "AssignmentExpression":
if (node.operator === "=") {
return isAlwaysNew(scope, node.right);
}
return false;
case "ConditionalExpression":
return (
isAlwaysNew(scope, node.consequent) &&
isAlwaysNew(scope, node.alternate)
);
case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior.
case "JSXFragment":
return false;
default:
return false;
}
}
/**
* Checks if one operand will cause the result to be constant.
* @param {Scope} scope Scope in which the expression was found.
* @param {ASTNode} a One side of the expression
* @param {ASTNode} b The other side of the expression
* @param {string} operator The binary expression operator
* @returns {ASTNode | null} The node which will cause the expression to have a constant result.
*/
function findBinaryExpressionConstantOperand(scope, a, b, operator) {
if (operator === "==" || operator === "!=") {
if (
(isNullOrUndefined(scope, a) &&
hasConstantNullishness(scope, b, false)) ||
(isStaticBoolean(scope, a) &&
hasConstantLooseBooleanComparison(scope, b))
) {
return b;
}
} else if (operator === "===" || operator === "!==") {
if (
(isNullOrUndefined(scope, a) &&
hasConstantNullishness(scope, b, false)) ||
(isStaticBoolean(scope, a) &&
hasConstantStrictBooleanComparison(scope, b))
) {
return b;
}
}
return null;
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
docs: {
description:
"Disallow expressions where the operation doesn't affect the value",
recommended: true,
url: "https://eslint.org/docs/latest/rules/no-constant-binary-expression",
},
schema: [],
messages: {
constantBinaryOperand:
"Unexpected constant binary expression. Compares constantly with the {{otherSide}}-hand side of the `{{operator}}`.",
constantShortCircuit:
"Unexpected constant {{property}} on the left-hand side of a `{{operator}}` expression.",
alwaysNew:
"Unexpected comparison to newly constructed object. These two values can never be equal.",
bothAlwaysNew:
"Unexpected comparison of two newly constructed objects. These two values can never be equal.",
},
},
create(context) {
const sourceCode = context.sourceCode;
return {
LogicalExpression(node) {
const { operator, left } = node;
const scope = sourceCode.getScope(node);
if (
(operator === "&&" || operator === "||") &&
isConstant(scope, left, true)
) {
context.report({
node: left,
messageId: "constantShortCircuit",
data: { property: "truthiness", operator },
});
} else if (
operator === "??" &&
hasConstantNullishness(scope, left, false)
) {
context.report({
node: left,
messageId: "constantShortCircuit",
data: { property: "nullishness", operator },
});
}
},
BinaryExpression(node) {
const scope = sourceCode.getScope(node);
const { right, left, operator } = node;
const rightConstantOperand =
findBinaryExpressionConstantOperand(
scope,
left,
right,
operator,
);
const leftConstantOperand = findBinaryExpressionConstantOperand(
scope,
right,
left,
operator,
);
if (rightConstantOperand) {
context.report({
node: rightConstantOperand,
messageId: "constantBinaryOperand",
data: { operator, otherSide: "left" },
});
} else if (leftConstantOperand) {
context.report({
node: leftConstantOperand,
messageId: "constantBinaryOperand",
data: { operator, otherSide: "right" },
});
} else if (operator === "===" || operator === "!==") {
if (isAlwaysNew(scope, left)) {
context.report({ node: left, messageId: "alwaysNew" });
} else if (isAlwaysNew(scope, right)) {
context.report({ node: right, messageId: "alwaysNew" });
}
} else if (operator === "==" || operator === "!=") {
/*
* If both sides are "new", then both sides are objects and
* therefore they will be compared by reference even with `==`
* equality.
*/
if (isAlwaysNew(scope, left) && isAlwaysNew(scope, right)) {
context.report({
node: left,
messageId: "bothAlwaysNew",
});
}
}
},
/*
* In theory we could handle short-circuiting assignment operators,
* for some constant values, but that would require walking the
* scope to find the value of the variable being assigned. This is
* dependent on https://github.com/eslint/eslint/issues/13776
*
* AssignmentExpression() {},
*/
};
},
};
@@ -0,0 +1,31 @@
/**
* Formats a date according to the specified format string.
* 根据指定的格式字符串格式化日期。
*
* @param date - The date to format. (要格式化的日期。)
* @param formatString - The format string to use. (要使用的格式字符串。)
* @returns The formatted date string. (格式化后的日期字符串。)
* @example
* ```ts
* // Formatting a date with 'YYYY-MM-DD' format (使用 'YYYY-MM-DD' 格式格式化日期)
* const date1 = new Date('2023-10-01T12:00:00');
* const formattedDate1 = format(date1, 'YYYY-MM-DD');
* console.log(formattedDate1); // Outputs: '2023-10-01' (输出: '2023-10-01')
*
* // Formatting a date with 'YYYY-MM-DD HH:mm:ss' format (使用 'YYYY-MM-DD HH:mm:ss' 格式格式化日期)
* const date2 = new Date('2023-10-01T12:30:45');
* const formattedDate2 = format(date2, 'YYYY-MM-DD HH:mm:ss');
* console.log(formattedDate2); // Outputs: '2023-10-01 12:30:45' (输出: '2023-10-01 12:30:45')
*
* // Formatting a date with 'YYYY-MM-DDTHH:mm:ssZ' format (使用 'YYYY-MM-DDTHH:mm:ssZ' 格式格式化日期)
* const date3 = new Date('2023-10-01T12:30:45');
* const formattedDate3 = format(date3, 'YYYY-MM-DDTHH:mm:ssZ');
* console.log(formattedDate3); // Outputs: '2023-10-01T12:30:45-04:00' (输出: '2023-10-01T12:30:45-04:00')
*
* // Using 'ISO' format (使用 'ISO' 格式)
* const date4 = new Date('2023-10-01T12:30:45');
* const formattedDate4 = format(date4, 'ISO');
* console.log(formattedDate4); // Outputs: '2023-10-01T16:30:45.000Z' (输出: '2023-10-01T16:30:45.000Z')
* ```
*/
export default function format(date: Date, formatString?: string): string;
@@ -0,0 +1,917 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/v4";
declare const iss: z.core.$ZodIssueCode;
const Test = z.object({
f1: z.number(),
f2: z.string().optional(),
f3: z.string().nullable(),
f4: z.array(z.object({ t: z.union([z.string(), z.boolean()]) })),
});
// type TestFlattenedErrors = core.inferFlattenedErrors<typeof Test, { message: string; code: number }>;
// type TestFormErrors = core.inferFlattenedErrors<typeof Test>;
const parsed = Test.safeParse({});
test("regular error", () => {
expect(parsed).toMatchInlineSnapshot(`
{
"error": [ZodError: [
{
"expected": "number",
"code": "invalid_type",
"path": [
"f1"
],
"message": "Invalid input: expected number, received undefined"
},
{
"expected": "string",
"code": "invalid_type",
"path": [
"f3"
],
"message": "Invalid input: expected string, received undefined"
},
{
"expected": "array",
"code": "invalid_type",
"path": [
"f4"
],
"message": "Invalid input: expected array, received undefined"
}
]],
"success": false,
}
`);
});
test(".flatten()", () => {
const flattened = parsed.error!.flatten();
// flattened.
expectTypeOf(flattened).toMatchTypeOf<{
formErrors: string[];
fieldErrors: {
f2?: string[];
f1?: string[];
f3?: string[];
f4?: string[];
};
}>();
expect(flattened).toMatchInlineSnapshot(`
{
"fieldErrors": {
"f1": [
"Invalid input: expected number, received undefined",
],
"f3": [
"Invalid input: expected string, received undefined",
],
"f4": [
"Invalid input: expected array, received undefined",
],
},
"formErrors": [],
}
`);
});
test("custom .flatten()", () => {
type ErrorType = { message: string; code: number };
const flattened = parsed.error!.flatten((iss) => ({
message: iss.message,
code: 1234,
}));
expectTypeOf(flattened).toMatchTypeOf<{
formErrors: ErrorType[];
fieldErrors: {
f2?: ErrorType[];
f1?: ErrorType[];
f3?: ErrorType[];
f4?: ErrorType[];
};
}>();
expect(flattened).toMatchInlineSnapshot(`
{
"fieldErrors": {
"f1": [
{
"code": 1234,
"message": "Invalid input: expected number, received undefined",
},
],
"f3": [
{
"code": 1234,
"message": "Invalid input: expected string, received undefined",
},
],
"f4": [
{
"code": 1234,
"message": "Invalid input: expected array, received undefined",
},
],
},
"formErrors": [],
}
`);
});
test(".format()", () => {
const formatted = parsed.error!.format();
expectTypeOf(formatted).toMatchTypeOf<{
_errors: string[];
f2?: { _errors: string[] };
f1?: { _errors: string[] };
f3?: { _errors: string[] };
f4?: {
[x: number]: {
_errors: string[];
t?: {
_errors: string[];
};
};
_errors: string[];
};
}>();
expect(formatted).toMatchInlineSnapshot(`
{
"_errors": [],
"f1": {
"_errors": [
"Invalid input: expected number, received undefined",
],
},
"f3": {
"_errors": [
"Invalid input: expected string, received undefined",
],
},
"f4": {
"_errors": [
"Invalid input: expected array, received undefined",
],
},
}
`);
});
test("custom .format()", () => {
type ErrorType = { message: string; code: number };
const formatted = parsed.error!.format((iss) => ({
message: iss.message,
code: 1234,
}));
expectTypeOf(formatted).toMatchTypeOf<{
_errors: ErrorType[];
f2?: { _errors: ErrorType[] };
f1?: { _errors: ErrorType[] };
f3?: { _errors: ErrorType[] };
f4?: {
[x: number]: {
_errors: ErrorType[];
t?: {
_errors: ErrorType[];
};
};
_errors: ErrorType[];
};
}>();
expect(formatted).toMatchInlineSnapshot(`
{
"_errors": [],
"f1": {
"_errors": [
{
"code": 1234,
"message": "Invalid input: expected number, received undefined",
},
],
},
"f3": {
"_errors": [
{
"code": 1234,
"message": "Invalid input: expected string, received undefined",
},
],
},
"f4": {
"_errors": [
{
"code": 1234,
"message": "Invalid input: expected array, received undefined",
},
],
},
}
`);
});
test("all errors", () => {
const propertySchema = z.string();
const schema = z
.object({
a: propertySchema,
b: propertySchema,
})
.refine(
(val) => {
return val.a === val.b;
},
{ message: "Must be equal" }
);
const r1 = schema.safeParse({
a: "asdf",
b: "qwer",
});
expect(z.core.flattenError(r1.error!)).toEqual({
formErrors: ["Must be equal"],
fieldErrors: {},
});
const r2 = schema.safeParse({
a: null,
b: null,
});
// const error = _error as z.ZodError;
expect(z.core.flattenError(r2.error!)).toMatchInlineSnapshot(`
{
"fieldErrors": {
"a": [
"Invalid input: expected string, received null",
],
"b": [
"Invalid input: expected string, received null",
],
},
"formErrors": [],
}
`);
expect(z.core.flattenError(r2.error!, (iss) => iss.message.toUpperCase())).toMatchInlineSnapshot(`
{
"fieldErrors": {
"a": [
"INVALID INPUT: EXPECTED STRING, RECEIVED NULL",
],
"b": [
"INVALID INPUT: EXPECTED STRING, RECEIVED NULL",
],
},
"formErrors": [],
}
`);
// Test identity
expect(z.core.flattenError(r2.error!, (i: z.ZodIssue) => i)).toMatchInlineSnapshot(`
{
"fieldErrors": {
"a": [
{
"code": "invalid_type",
"expected": "string",
"message": "Invalid input: expected string, received null",
"path": [
"a",
],
},
],
"b": [
{
"code": "invalid_type",
"expected": "string",
"message": "Invalid input: expected string, received null",
"path": [
"b",
],
},
],
},
"formErrors": [],
}
`);
// Test mapping
const f1 = z.core.flattenError(r2.error!, (i: z.ZodIssue) => i.message.length);
expect(f1).toMatchInlineSnapshot(`
{
"fieldErrors": {
"a": [
45,
],
"b": [
45,
],
},
"formErrors": [],
}
`);
// expect(f1.fieldErrors.a![0]).toEqual("Invalid input: expected string".length);
// expect(f1).toMatchObject({
// formErrors: [],
// fieldErrors: {
// a: ["Invalid input: expected string".length],
// b: ["Invalid input: expected string".length],
// },
// });
});
const schema = z.strictObject({
username: z.string().brand<"username">(),
favoriteNumbers: z.array(z.number()),
nesting: z.object({
a: z.string(),
}),
});
const result = schema.safeParse({
username: 1234,
favoriteNumbers: [1234, "4567"],
nesting: {
a: 123,
},
extra: 1234,
});
const tree = z.treeifyError(result.error!);
expectTypeOf(tree).toEqualTypeOf<{
errors: string[];
properties?: {
username?: {
errors: string[];
};
favoriteNumbers?: {
errors: string[];
items?: {
errors: string[];
}[];
};
nesting?: {
errors: string[];
properties?: {
a?: {
errors: string[];
};
};
};
};
}>();
test("z.treeifyError", () => {
expect(tree).toMatchInlineSnapshot(`
{
"errors": [
"Unrecognized key: "extra"",
],
"properties": {
"favoriteNumbers": {
"errors": [],
"items": [
,
{
"errors": [
"Invalid input: expected number, received string",
],
},
],
},
"nesting": {
"errors": [],
"properties": {
"a": {
"errors": [
"Invalid input: expected string, received number",
],
},
},
},
"username": {
"errors": [
"Invalid input: expected string, received number",
],
},
},
}
`);
});
test("z.treeifyError 2", () => {
const schema = z.strictObject({
name: z.string(),
logLevel: z.union([z.string(), z.number()]),
env: z.literal(["production", "development"]),
});
const data = {
name: 1000,
logLevel: false,
extra: 1000,
};
const result = schema.safeParse(data);
const err = z.treeifyError(result.error!);
expect(err).toMatchInlineSnapshot(`
{
"errors": [
"Unrecognized key: "extra"",
],
"properties": {
"env": {
"errors": [
"Invalid option: expected one of "production"|"development"",
],
},
"logLevel": {
"errors": [
"Invalid input: expected string, received boolean",
"Invalid input: expected number, received boolean",
],
},
"name": {
"errors": [
"Invalid input: expected string, received number",
],
},
},
}
`);
});
test("z.prettifyError", () => {
expect(z.prettifyError(result.error!)).toMatchInlineSnapshot(`
"✖ Unrecognized key: "extra"
✖ Invalid input: expected string, received number
→ at username
✖ Invalid input: expected number, received string
→ at favoriteNumbers[1]
✖ Invalid input: expected string, received number
→ at nesting.a"
`);
});
test("z.toDotPath", () => {
expect(z.core.toDotPath(["a", "b", 0, "c"])).toMatchInlineSnapshot(`"a.b[0].c"`);
expect(z.core.toDotPath(["a", Symbol("b"), 0, "c"])).toMatchInlineSnapshot(`"a["Symbol(b)"][0].c"`);
// Test with periods in keys
expect(z.core.toDotPath(["user.name", "first.last"])).toMatchInlineSnapshot(`"["user.name"]["first.last"]"`);
// Test with special characters
expect(z.core.toDotPath(["user", "$special", Symbol("#symbol")])).toMatchInlineSnapshot(
`"user.$special["Symbol(#symbol)"]"`
);
// Test with dots and quotes
expect(z.core.toDotPath(["search", `query("foo.bar"="abc")`])).toMatchInlineSnapshot(
`"search["query(\\"foo.bar\\"=\\"abc\\")"]"`
);
// Test with newlines
expect(z.core.toDotPath(["search", `foo\nbar`])).toMatchInlineSnapshot(`"search["foo\\nbar"]"`);
// Test with empty strings
expect(z.core.toDotPath(["", "empty"])).toMatchInlineSnapshot(`".empty"`);
// Test with array indices
expect(z.core.toDotPath(["items", 0, 1, 2])).toMatchInlineSnapshot(`"items[0][1][2]"`);
// Test with mixed path elements
expect(z.core.toDotPath(["users", "user.config", 0, "settings.theme"])).toMatchInlineSnapshot(
`"users["user.config"][0]["settings.theme"]"`
);
// Test with square brackets in keys
expect(z.core.toDotPath(["data[0]", "value"])).toMatchInlineSnapshot(`"["data[0]"].value"`);
// Test with empty path
expect(z.core.toDotPath([])).toMatchInlineSnapshot(`""`);
});
test("inheritance", () => {
const e1 = new z.ZodError([]);
expect(e1).toBeInstanceOf(z.core.$ZodError);
expect(e1).toBeInstanceOf(z.ZodError);
// expect(e1).not.toBeInstanceOf(Error);
const e2 = new z.ZodRealError([]);
expect(e2).toBeInstanceOf(z.ZodError);
expect(e2).toBeInstanceOf(z.ZodRealError);
expect(e2).toBeInstanceOf(Error);
});
test("disc union treeify/format", () => {
const schema = z.discriminatedUnion(
"foo",
[
z.object({
foo: z.literal("x"),
x: z.string(),
}),
z.object({
foo: z.literal("y"),
y: z.string(),
}),
],
{
error: "Invalid discriminator",
}
);
const error = schema.safeParse({ foo: "invalid" }).error;
expect(z.treeifyError(error!)).toMatchInlineSnapshot(`
{
"errors": [],
"properties": {
"foo": {
"errors": [
"Invalid discriminator",
],
},
},
}
`);
expect(z.prettifyError(error!)).toMatchInlineSnapshot(`
"✖ Invalid discriminator
→ at foo"
`);
expect(z.formatError(error!)).toMatchInlineSnapshot(`
{
"_errors": [],
"foo": {
"_errors": [
"Invalid discriminator",
],
},
}
`);
});
test("update message after adding issues", () => {
const e = new z.ZodError([]);
e.addIssue({
code: "custom",
message: "message",
input: "asdf",
path: [],
});
expect(e.message).toMatchInlineSnapshot(`
"[
{
"code": "custom",
"message": "message",
"input": "asdf",
"path": []
}
]"
`);
e.addIssue({
code: "custom",
message: "message",
input: "asdf",
path: [],
});
expect(e.message).toMatchInlineSnapshot(`
"[
{
"code": "custom",
"message": "message",
"input": "asdf",
"path": []
},
{
"code": "custom",
"message": "message",
"input": "asdf",
"path": []
}
]"
`);
});
test("z.formatError nested union preserves parent path", () => {
const syntheticError = new z.ZodError([
{
code: "invalid_union",
path: ["parent"],
message: "Invalid input",
errors: [
[
{
code: "invalid_type",
expected: "string",
path: [],
message: "Expected string",
input: {},
},
],
[
{
code: "invalid_union",
path: ["child"],
message: "Invalid input",
errors: [
[
{
code: "invalid_type",
expected: "string",
path: [],
message: "Expected string",
input: true,
},
],
[
{
code: "invalid_type",
expected: "number",
path: [],
message: "Expected number",
input: true,
},
],
],
},
],
],
},
] as any);
const formatted: any = z.formatError(syntheticError);
// "child" must be nested under "parent", not at root
expect(formatted).not.toHaveProperty("child");
expect(formatted).toHaveProperty("parent");
expect(formatted.parent).toHaveProperty("child");
expect(formatted.parent.child._errors).toContain("Expected string");
expect(formatted.parent.child._errors).toContain("Expected number");
expect(formatted.parent._errors).toContain("Expected string");
});
test("z.treeifyError nested union preserves parent path", () => {
// When a nested invalid_union appears inside another invalid_union, the inner errors must stay nested under their parent path, not flatten to root.
const syntheticError = new z.ZodError([
{
code: "invalid_union",
path: ["parent"],
message: "Invalid input",
errors: [
[
{
code: "invalid_type",
expected: "string",
path: [],
message: "Expected string",
input: {},
},
],
[
{
code: "invalid_union",
path: ["child"],
message: "Invalid input",
errors: [
[
{
code: "invalid_type",
expected: "string",
path: [],
message: "Expected string",
input: true,
},
],
[
{
code: "invalid_type",
expected: "number",
path: [],
message: "Expected number",
input: true,
},
],
],
},
],
],
},
] as any);
const tree: any = z.treeifyError(syntheticError);
// "child" must be nested under "parent", not at root
expect(tree.properties).not.toHaveProperty("child");
expect(tree.properties).toHaveProperty("parent");
expect(tree.properties.parent.properties).toHaveProperty("child");
expect(tree.properties.parent.properties.child.errors).toContain("Expected string");
expect(tree.properties.parent.properties.child.errors).toContain("Expected number");
expect(tree.properties.parent.errors).toContain("Expected string");
});
test("z.treeifyError deeply nested union (4 levels) preserves full path", () => {
// a > b > c > d — each level wrapped in an invalid_union
const syntheticError = new z.ZodError([
{
code: "invalid_union",
path: ["a"],
message: "Invalid input",
errors: [
[
{
code: "invalid_union",
path: ["b"],
message: "Invalid input",
errors: [
[
{
code: "invalid_union",
path: ["c"],
message: "Invalid input",
errors: [
[
{
code: "invalid_type",
expected: "string",
path: ["d"],
message: "Expected string",
input: 123,
},
],
],
},
],
],
},
],
],
},
] as any);
const tree: any = z.treeifyError(syntheticError);
// The full path must be preserved: a.b.c.d
expect(tree.properties).toHaveProperty("a");
expect(tree.properties).not.toHaveProperty("b");
expect(tree.properties).not.toHaveProperty("c");
const lvlA = tree.properties.a;
expect(lvlA.properties).toHaveProperty("b");
const lvlB = lvlA.properties.b;
expect(lvlB.properties).toHaveProperty("c");
const lvlC = lvlB.properties.c;
expect(lvlC.properties).toHaveProperty("d");
expect(lvlC.properties.d.errors).toContain("Expected string");
});
test("z.treeifyError nested union with real schema", () => {
const innerUnion = z.union([
z.object({ type: z.literal("a"), value: z.string() }),
z.object({ type: z.literal("b"), value: z.number() }),
]);
const schema = z.string().or(
z.object({
settings: z.object({ name: z.string() }).and(innerUnion),
})
);
const result = schema.safeParse({
settings: { name: 123, type: "x", value: true },
});
expect(result.success).toBe(false);
if (!result.success) {
const tree: any = z.treeifyError(result.error);
// All settings-related errors should be under "settings", not at root
expect(tree.properties).toHaveProperty("settings");
const settingsProperties = tree.properties.settings.properties ?? {};
for (const key of Object.keys(settingsProperties)) {
// Every sub-property under settings should NOT also appear at root
if (key !== "settings") {
expect(tree.properties).not.toHaveProperty(key);
}
}
}
});
const prototypePropertyNames = ["__proto__", "constructor", "toString", "hasOwnProperty", "valueOf"] as const;
test.each(prototypePropertyNames)("z.formatError handles Object.prototype property path: %s", (name) => {
const schema = z.object({ data: z.string() }).superRefine((_, ctx) => {
ctx.addIssue({ code: "custom", message: "invalid value", path: [name] });
});
const result = schema.safeParse({ data: "hello" });
expect(result.success).toBe(false);
const formatted = z.formatError(result.error!);
expect(Object.prototype.hasOwnProperty.call(formatted, name)).toBe(true);
expect(Object.getPrototypeOf(formatted)).toBe(Object.prototype);
expect((formatted as any)[name]._errors).toEqual(["invalid value"]);
});
test.each(prototypePropertyNames)("z.treeifyError handles Object.prototype property path: %s", (name) => {
const schema = z.object({ data: z.string() }).superRefine((_, ctx) => {
ctx.addIssue({ code: "custom", message: "invalid value", path: [name] });
});
const result = schema.safeParse({ data: "hello" });
expect(result.success).toBe(false);
const tree = z.treeifyError(result.error!);
expect(Object.prototype.hasOwnProperty.call(tree.properties, name)).toBe(true);
expect(Object.getPrototypeOf(tree.properties)).toBe(Object.prototype);
expect((tree as any).properties[name].errors).toEqual(["invalid value"]);
});
test.each(prototypePropertyNames)("z.flattenError handles Object.prototype property path: %s", (name) => {
const schema = z.object({ data: z.string() }).superRefine((_, ctx) => {
ctx.addIssue({ code: "custom", message: "invalid value", path: [name] });
});
const result = schema.safeParse({ data: "hello" });
expect(result.success).toBe(false);
const { fieldErrors } = z.flattenError(result.error!);
expect(Object.prototype.hasOwnProperty.call(fieldErrors, name)).toBe(true);
expect(Object.getPrototypeOf(fieldErrors)).toBe(Object.prototype);
expect((fieldErrors as any)[name]).toEqual(["invalid value"]);
});
/** The "__proto__" node must be a real own data property, not the inherited accessor. */
const protoNode = (obj: any) => Object.getOwnPropertyDescriptor(obj, "__proto__")!.value;
test("error formatters merge sibling issues under a __proto__ path", () => {
const schema = z.string().check((ctx) => {
ctx.issues.push({ code: "custom", message: "a", path: ["__proto__", "x"], input: ctx.value });
ctx.issues.push({ code: "custom", message: "b", path: ["__proto__", "y"], input: ctx.value });
});
const error = schema.safeParse("hello").error!;
const formatted = protoNode(z.formatError(error));
expect(formatted.x._errors).toEqual(["a"]);
expect(formatted.y._errors).toEqual(["b"]);
const tree = protoNode((z.treeifyError(error) as any).properties);
expect(tree.properties.x.errors).toEqual(["a"]);
expect(tree.properties.y.errors).toEqual(["b"]);
expect(({} as any).x).toBeUndefined();
expect(({} as any).y).toBeUndefined();
});
test("error formatting leaves Object.prototype untouched for input-derived keys", () => {
const record = z.record(z.string(), z.string()).safeParse(JSON.parse('{"toString": 1}'));
expect(record.success).toBe(false);
expect((z.formatError(record.error!) as any).toString._errors).toHaveLength(1);
const entries = new Map(Object.entries(JSON.parse('{"__proto__": {"pwn": 1}}')));
const result = z.map(z.string(), z.object({ pwn: z.string() })).safeParse(entries);
expect(result.success).toBe(false);
expect(protoNode(z.formatError(result.error!)).pwn._errors).toHaveLength(1);
expect(protoNode((z.treeifyError(result.error!) as any).properties).properties.pwn.errors).toHaveLength(1);
expect(({} as any).pwn).toBeUndefined();
});
test("formatError handles an input-derived _errors path", () => {
const schema = z.object({ parent: z.record(z.string(), z.string()) });
const result = schema.safeParse({ parent: { _errors: 1 } });
expect(result.success).toBe(false);
const formatted = z.formatError(result.error!);
expect(formatted.parent?._errors).toEqual(["Invalid input: expected string, received number"]);
const nested = z
.object({ parent: z.record(z.string(), z.object({ child: z.string() })) })
.safeParse({ parent: { _errors: { child: 1 } } });
expect(nested.success).toBe(false);
expect((z.formatError(nested.error!) as any).parent.child._errors).toEqual([
"Invalid input: expected string, received number",
]);
});
test("error walkers handle path elements named after inherited methods", () => {
// "toString" and "constructor" are truthy on the prototype, so a plain lookup finds
// the inherited function instead of creating a node, and the push then throws.
for (const [schema, input] of [
[z.object({ toString: z.string() }), { toString: 1 }],
[z.object({ constructor: z.string() }), { constructor: 1 }],
[z.object({ toString: z.string(), constructor: z.string() }), { toString: 1, constructor: 2 }],
] as const) {
const result = (schema as any).safeParse(input);
expect(result.success).toBe(false);
const formatted = z.formatError(result.error) as any;
const tree = z.treeifyError(result.error) as any;
for (const key of Object.keys(input)) {
expect(formatted[key]._errors).toHaveLength(1);
expect(tree.properties[key].errors).toHaveLength(1);
expect(Object.prototype.hasOwnProperty.call(formatted, key)).toBe(true);
}
}
});
@@ -0,0 +1,13 @@
# `react-use-layout-effect`
## Installation
```sh
$ yarn add @radix-ui/react-use-layout-effect
# or
$ npm install @radix-ui/react-use-layout-effect
```
## Usage
This is an internal utility, not intended for public usage.
@@ -0,0 +1,77 @@
/**
* Experimental McpServer task features for MCP SDK.
* WARNING: These APIs are experimental and may change without notice.
*
* @experimental
*/
import type { McpServer, RegisteredTool } from '../../server/mcp.js';
import type { ZodRawShapeCompat, AnySchema } from '../../server/zod-compat.js';
import type { ToolAnnotations } from '../../types.js';
import type { ToolTaskHandler, TaskToolExecution } from './interfaces.js';
/**
* Experimental task features for McpServer.
*
* Access via `server.experimental.tasks`:
* ```typescript
* server.experimental.tasks.registerToolTask('long-running', config, handler);
* ```
*
* @experimental
*/
export declare class ExperimentalMcpServerTasks {
private readonly _mcpServer;
constructor(_mcpServer: McpServer);
/**
* Registers a task-based tool with a config object and handler.
*
* Task-based tools support long-running operations that can be polled for status
* and results. The handler must implement `createTask`, `getTask`, and `getTaskResult`
* methods.
*
* @example
* ```typescript
* server.experimental.tasks.registerToolTask('long-computation', {
* description: 'Performs a long computation',
* inputSchema: { input: z.string() },
* execution: { taskSupport: 'required' }
* }, {
* createTask: async (args, extra) => {
* const task = await extra.taskStore.createTask({ ttl: 300000 });
* startBackgroundWork(task.taskId, args);
* return { task };
* },
* getTask: async (args, extra) => {
* return extra.taskStore.getTask(extra.taskId);
* },
* getTaskResult: async (args, extra) => {
* return extra.taskStore.getTaskResult(extra.taskId);
* }
* });
* ```
*
* @param name - The tool name
* @param config - Tool configuration (description, schemas, etc.)
* @param handler - Task handler with createTask, getTask, getTaskResult methods
* @returns RegisteredTool for managing the tool's lifecycle
*
* @experimental
*/
registerToolTask<OutputArgs extends undefined | ZodRawShapeCompat | AnySchema>(name: string, config: {
title?: string;
description?: string;
outputSchema?: OutputArgs;
annotations?: ToolAnnotations;
execution?: TaskToolExecution;
_meta?: Record<string, unknown>;
}, handler: ToolTaskHandler<undefined>): RegisteredTool;
registerToolTask<InputArgs extends ZodRawShapeCompat | AnySchema, OutputArgs extends undefined | ZodRawShapeCompat | AnySchema>(name: string, config: {
title?: string;
description?: string;
inputSchema: InputArgs;
outputSchema?: OutputArgs;
annotations?: ToolAnnotations;
execution?: TaskToolExecution;
_meta?: Record<string, unknown>;
}, handler: ToolTaskHandler<InputArgs>): RegisteredTool;
}
//# sourceMappingURL=mcp-server.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"reply-all.js","sources":["../../../src/icons/reply-all.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name ReplyAll\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cG9seWxpbmUgcG9pbnRzPSI3IDE3IDIgMTIgNyA3IiAvPgogIDxwb2x5bGluZSBwb2ludHM9IjEyIDE3IDcgMTIgMTIgNyIgLz4KICA8cGF0aCBkPSJNMjIgMTh2LTJhNCA0IDAgMCAwLTQtNEg3IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/reply-all\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst ReplyAll = createLucideIcon('ReplyAll', [\n ['polyline', { points: '7 17 2 12 7 7', key: 't83bqg' }],\n ['polyline', { points: '12 17 7 12 12 7', key: '1g4ajm' }],\n ['path', { d: 'M22 18v-2a4 4 0 0 0-4-4H7', key: '1fcyog' }],\n]);\n\nexport default ReplyAll;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAW,iBAAiB,UAAY,CAAA,CAAA,CAAA;AAAA,CAAA,CAC5C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAY,CAAA,CAAA,CAAA,CAAE,QAAQ,CAAiB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACvD,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAY,CAAA,CAAA,CAAA,CAAE,QAAQ,CAAmB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACzD,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAA6B,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC5D,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,76 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. 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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABILITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference lib="es2015.symbol.wellknown" />
interface WeakRef<T extends WeakKey> {
readonly [Symbol.toStringTag]: "WeakRef";
/**
* Returns the WeakRef instance's target value, or undefined if the target value has been
* reclaimed.
* In es2023 the value can be either a symbol or an object, in previous versions only object is permissible.
*/
deref(): T | undefined;
}
interface WeakRefConstructor {
readonly prototype: WeakRef<any>;
/**
* Creates a WeakRef instance for the given target value.
* In es2023 the value can be either a symbol or an object, in previous versions only object is permissible.
* @param target The target value for the WeakRef instance.
*/
new <T extends WeakKey>(target: T): WeakRef<T>;
}
declare var WeakRef: WeakRefConstructor;
interface FinalizationRegistry<T> {
readonly [Symbol.toStringTag]: "FinalizationRegistry";
/**
* Registers a value with the registry.
* In es2023 the value can be either a symbol or an object, in previous versions only object is permissible.
* @param target The target value to register.
* @param heldValue The value to pass to the finalizer for this value. This cannot be the
* target value.
* @param unregisterToken The token to pass to the unregister method to unregister the target
* value. If not provided, the target cannot be unregistered.
*/
register(target: WeakKey, heldValue: T, unregisterToken?: WeakKey): void;
/**
* Unregisters a value from the registry.
* In es2023 the value can be either a symbol or an object, in previous versions only object is permissible.
* @param unregisterToken The token that was used as the unregisterToken argument when calling
* register to register the target value.
*/
unregister(unregisterToken: WeakKey): boolean;
}
interface FinalizationRegistryConstructor {
readonly prototype: FinalizationRegistry<any>;
/**
* Creates a finalization registry with an associated cleanup callback
* @param cleanupCallback The callback to call after a value in the registry has been reclaimed.
*/
new <T>(cleanupCallback: (heldValue: T) => void): FinalizationRegistry<T>;
}
declare var FinalizationRegistry: FinalizationRegistryConstructor;
@@ -0,0 +1 @@
{"version":3,"file":"DocumentProjectionNode.mjs","sources":["../../../../src/projection/node/DocumentProjectionNode.ts"],"sourcesContent":["import { addDomEvent } from \"../../events/add-dom-event\"\nimport { createProjectionNode } from \"./create-projection-node\"\n\nexport const DocumentProjectionNode = createProjectionNode<Window>({\n attachResizeListener: (\n ref: Window | Element,\n notify: VoidFunction\n ): VoidFunction => addDomEvent(ref, \"resize\", notify),\n measureScroll: () => ({\n x: document.documentElement.scrollLeft || document.body?.scrollLeft || 0,\n y: document.documentElement.scrollTop || document.body?.scrollTop || 0,\n }),\n checkIsScrollRoot: () => true,\n})\n"],"names":[],"mappings":";;;AAGO,MAAM,sBAAsB,GAAG,oBAAoB,CAAS;AAC/D,IAAA,oBAAoB,EAAE,CAClB,GAAqB,EACrB,MAAoB,KACL,WAAW,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,CAAC;AACrD,IAAA,aAAa,EAAE,OAAO;AAClB,QAAA,CAAC,EAAE,QAAQ,CAAC,eAAe,CAAC,UAAU,IAAI,QAAQ,CAAC,IAAI,EAAE,UAAU,IAAI,CAAC;AACxE,QAAA,CAAC,EAAE,QAAQ,CAAC,eAAe,CAAC,SAAS,IAAI,QAAQ,CAAC,IAAI,EAAE,SAAS,IAAI,CAAC;KACzE,CAAC;AACF,IAAA,iBAAiB,EAAE,MAAM,IAAI;AAChC,CAAA;;;;"}
@@ -0,0 +1,568 @@
'use client'
import * as React from 'react'
import { useStore } from '@tanstack/react-store'
import {
createControlledPromise,
getLocationChangeInfo,
invariant,
isNotFound,
isRedirect,
rootRouteId,
} from '@tanstack/router-core'
import { isServer } from '@tanstack/router-core/isServer'
import { CatchBoundary, ErrorComponent } from './CatchBoundary'
import { useRouter } from './useRouter'
import { CatchNotFound } from './not-found'
import { matchContext } from './matchContext'
import { SafeFragment } from './SafeFragment'
import { renderRouteNotFound } from './renderRouteNotFound'
import { ScrollRestoration } from './scroll-restoration'
import { ClientOnly } from './ClientOnly'
import { useLayoutEffect } from './utils'
import type { AnyRoute, RootRouteOptions } from '@tanstack/router-core'
export const Match = React.memo(function MatchImpl({
matchId,
}: {
matchId: string
}) {
const router = useRouter()
if (isServer ?? router.isServer) {
const match = router.stores.matchStores.get(matchId)?.get()
if (!match) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(
`Invariant failed: Could not find match for matchId "${matchId}". Please file an issue!`,
)
}
invariant()
}
const routeId = match.routeId as string
const parentRouteId = (router.routesById[routeId] as AnyRoute).parentRoute
?.id
return (
<MatchView
router={router}
matchId={matchId}
resetKey={router.stores.loadedAt.get()}
matchState={{
routeId,
ssr: match.ssr,
_displayPending: match._displayPending,
parentRouteId,
}}
/>
)
}
// Subscribe directly to the match store from the pool.
// The matchId prop is stable for this component's lifetime (set by Outlet),
// and reconcileMatchPool reuses stores for the same matchId.
const matchStore = router.stores.matchStores.get(matchId)
if (!matchStore) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(
`Invariant failed: Could not find match for matchId "${matchId}". Please file an issue!`,
)
}
invariant()
}
// eslint-disable-next-line react-hooks/rules-of-hooks
const resetKey = useStore(router.stores.loadedAt, (loadedAt) => loadedAt)
// eslint-disable-next-line react-hooks/rules-of-hooks
const match = useStore(matchStore, (value) => value)
// eslint-disable-next-line react-hooks/rules-of-hooks
const matchState = React.useMemo(() => {
const routeId = match.routeId as string
const parentRouteId = (router.routesById[routeId] as AnyRoute).parentRoute
?.id
return {
routeId,
ssr: match.ssr,
_displayPending: match._displayPending,
parentRouteId: parentRouteId as string | undefined,
} satisfies MatchViewState
}, [match._displayPending, match.routeId, match.ssr, router.routesById])
return (
<MatchView
router={router}
matchId={matchId}
resetKey={resetKey}
matchState={matchState}
/>
)
})
type MatchViewState = {
routeId: string
ssr: boolean | 'data-only' | undefined
_displayPending: boolean | undefined
parentRouteId: string | undefined
}
function MatchView({
router,
matchId,
resetKey,
matchState,
}: {
router: ReturnType<typeof useRouter>
matchId: string
resetKey: number
matchState: MatchViewState
}) {
const route: AnyRoute = router.routesById[matchState.routeId]
const PendingComponent =
route.options.pendingComponent ?? router.options.defaultPendingComponent
const pendingElement = PendingComponent ? <PendingComponent /> : null
const routeErrorComponent =
route.options.errorComponent ?? router.options.defaultErrorComponent
const routeOnCatch = route.options.onCatch ?? router.options.defaultOnCatch
const routeNotFoundComponent = route.isRoot
? // If it's the root route, use the globalNotFound option, with fallback to the notFoundRoute's component
(route.options.notFoundComponent ??
router.options.notFoundRoute?.options.component)
: route.options.notFoundComponent
const resolvedNoSsr =
matchState.ssr === false || matchState.ssr === 'data-only'
const ResolvedSuspenseBoundary =
// If we're on the root route, allow forcefully wrapping in suspense
(!route.isRoot || route.options.wrapInSuspense || resolvedNoSsr) &&
(route.options.wrapInSuspense ??
PendingComponent ??
((route.options.errorComponent as any)?.preload || resolvedNoSsr))
? React.Suspense
: SafeFragment
const ResolvedCatchBoundary = routeErrorComponent
? CatchBoundary
: SafeFragment
const ResolvedNotFoundBoundary = routeNotFoundComponent
? CatchNotFound
: SafeFragment
const ShellComponent = route.isRoot
? ((route.options as RootRouteOptions).shellComponent ?? SafeFragment)
: SafeFragment
return (
<ShellComponent>
<matchContext.Provider value={matchId}>
<ResolvedSuspenseBoundary fallback={pendingElement}>
<ResolvedCatchBoundary
getResetKey={() => resetKey}
errorComponent={routeErrorComponent || ErrorComponent}
onCatch={(error, errorInfo) => {
// Forward not found errors (we don't want to show the error component for these)
if (isNotFound(error)) {
error.routeId ??= matchState.routeId as any
throw error
}
if (process.env.NODE_ENV !== 'production') {
console.warn(`Warning: Error in route match: ${matchId}`)
}
routeOnCatch?.(error, errorInfo)
}}
>
<ResolvedNotFoundBoundary
fallback={(error) => {
error.routeId ??= matchState.routeId as any
// If the current not found handler doesn't exist or it has a
// route ID which doesn't match the current route, rethrow the error
if (
!routeNotFoundComponent ||
(error.routeId && error.routeId !== matchState.routeId) ||
(!error.routeId && !route.isRoot)
)
throw error
return React.createElement(routeNotFoundComponent, error as any)
}}
>
{resolvedNoSsr || matchState._displayPending ? (
<ClientOnly fallback={pendingElement}>
<MatchInner matchId={matchId} />
</ClientOnly>
) : (
<MatchInner matchId={matchId} />
)}
</ResolvedNotFoundBoundary>
</ResolvedCatchBoundary>
</ResolvedSuspenseBoundary>
</matchContext.Provider>
{matchState.parentRouteId === rootRouteId ? (
<>
<OnRendered resetKey={resetKey} />
{router.options.scrollRestoration && (isServer ?? router.isServer) ? (
<ScrollRestoration />
) : null}
</>
) : null}
</ShellComponent>
)
}
// On Rendered can't happen above the root layout because it needs to run after
// the route subtree has committed below the root layout. Keeping it here lets
// us fire onRendered even after a hydration mismatch above the root layout
// (like bad head/link tags, which is common).
function OnRendered({ resetKey }: { resetKey: number }) {
const router = useRouter()
if (isServer ?? router.isServer) {
return null
}
// eslint-disable-next-line react-hooks/rules-of-hooks
const prevHrefRef = React.useRef<string | undefined>(undefined)
// eslint-disable-next-line react-hooks/rules-of-hooks
useLayoutEffect(() => {
const currentHref = router.latestLocation.href
if (
prevHrefRef.current === undefined ||
prevHrefRef.current !== currentHref
) {
router.emit({
type: 'onRendered',
...getLocationChangeInfo(
router.stores.location.get(),
router.stores.resolvedLocation.get(),
),
})
prevHrefRef.current = currentHref
}
}, [router.latestLocation.state.__TSR_key, resetKey, router])
return null
}
export const MatchInner = React.memo(function MatchInnerImpl({
matchId,
}: {
matchId: string
}): any {
const router = useRouter()
const getMatchPromise = (
match: {
id: string
_nonReactive: {
displayPendingPromise?: Promise<void>
minPendingPromise?: Promise<void>
loadPromise?: Promise<void>
}
},
key: 'displayPendingPromise' | 'minPendingPromise' | 'loadPromise',
) => {
return (
router.getMatch(match.id)?._nonReactive[key] ?? match._nonReactive[key]
)
}
if (isServer ?? router.isServer) {
const match = router.stores.matchStores.get(matchId)?.get()
if (!match) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(
`Invariant failed: Could not find match for matchId "${matchId}". Please file an issue!`,
)
}
invariant()
}
const routeId = match.routeId as string
const route = router.routesById[routeId] as AnyRoute
const remountFn =
(router.routesById[routeId] as AnyRoute).options.remountDeps ??
router.options.defaultRemountDeps
const remountDeps = remountFn?.({
routeId,
loaderDeps: match.loaderDeps,
params: match._strictParams,
search: match._strictSearch,
})
const key = remountDeps ? JSON.stringify(remountDeps) : undefined
const Comp = route.options.component ?? router.options.defaultComponent
const out = Comp ? <Comp key={key} /> : <Outlet />
if (match._displayPending) {
throw getMatchPromise(match, 'displayPendingPromise')
}
if (match._forcePending) {
throw getMatchPromise(match, 'minPendingPromise')
}
if (match.status === 'pending') {
throw getMatchPromise(match, 'loadPromise')
}
if (match.status === 'notFound') {
if (!isNotFound(match.error)) {
if (process.env.NODE_ENV !== 'production') {
throw new Error('Invariant failed: Expected a notFound error')
}
invariant()
}
return renderRouteNotFound(router, route, match.error)
}
if (match.status === 'redirected') {
if (!isRedirect(match.error)) {
if (process.env.NODE_ENV !== 'production') {
throw new Error('Invariant failed: Expected a redirect error')
}
invariant()
}
throw getMatchPromise(match, 'loadPromise')
}
if (match.status === 'error') {
const RouteErrorComponent =
(route.options.errorComponent ??
router.options.defaultErrorComponent) ||
ErrorComponent
return (
<RouteErrorComponent
error={match.error as any}
reset={undefined as any}
info={{
componentStack: '',
}}
/>
)
}
return out
}
const matchStore = router.stores.matchStores.get(matchId)
if (!matchStore) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(
`Invariant failed: Could not find match for matchId "${matchId}". Please file an issue!`,
)
}
invariant()
}
// eslint-disable-next-line react-hooks/rules-of-hooks
const match = useStore(matchStore, (value) => value)
const routeId = match.routeId as string
const route = router.routesById[routeId] as AnyRoute
// eslint-disable-next-line react-hooks/rules-of-hooks
const key = React.useMemo(() => {
const remountFn =
(router.routesById[routeId] as AnyRoute).options.remountDeps ??
router.options.defaultRemountDeps
const remountDeps = remountFn?.({
routeId,
loaderDeps: match.loaderDeps,
params: match._strictParams,
search: match._strictSearch,
})
return remountDeps ? JSON.stringify(remountDeps) : undefined
}, [
routeId,
match.loaderDeps,
match._strictParams,
match._strictSearch,
router.options.defaultRemountDeps,
router.routesById,
])
// eslint-disable-next-line react-hooks/rules-of-hooks
const out = React.useMemo(() => {
const Comp = route.options.component ?? router.options.defaultComponent
if (Comp) {
return <Comp key={key} />
}
return <Outlet />
}, [key, route.options.component, router.options.defaultComponent])
if (match._displayPending) {
throw getMatchPromise(match, 'displayPendingPromise')
}
if (match._forcePending) {
throw getMatchPromise(match, 'minPendingPromise')
}
// see also hydrate() in packages/router-core/src/ssr/ssr-client.ts
if (match.status === 'pending') {
// We're pending, and if we have a minPendingMs, we need to wait for it
const pendingMinMs =
route.options.pendingMinMs ?? router.options.defaultPendingMinMs
if (pendingMinMs) {
const routerMatch = router.getMatch(match.id)
if (routerMatch && !routerMatch._nonReactive.minPendingPromise) {
// Create a promise that will resolve after the minPendingMs
if (!(isServer ?? router.isServer)) {
const minPendingPromise = createControlledPromise<void>()
routerMatch._nonReactive.minPendingPromise = minPendingPromise
setTimeout(() => {
minPendingPromise.resolve()
// We've handled the minPendingPromise, so we can delete it
routerMatch._nonReactive.minPendingPromise = undefined
}, pendingMinMs)
}
}
}
throw getMatchPromise(match, 'loadPromise')
}
if (match.status === 'notFound') {
if (!isNotFound(match.error)) {
if (process.env.NODE_ENV !== 'production') {
throw new Error('Invariant failed: Expected a notFound error')
}
invariant()
}
return renderRouteNotFound(router, route, match.error)
}
if (match.status === 'redirected') {
// A match can be observed as redirected during an in-flight transition,
// especially when pending UI is already rendering. Suspend on the match's
// load promise so React can abandon this stale render and continue the
// redirect transition.
if (!isRedirect(match.error)) {
if (process.env.NODE_ENV !== 'production') {
throw new Error('Invariant failed: Expected a redirect error')
}
invariant()
}
throw getMatchPromise(match, 'loadPromise')
}
if (match.status === 'error') {
// If we're on the server, we need to use React's new and super
// wonky api for throwing errors from a server side render inside
// of a suspense boundary. This is the only way to get
// renderToPipeableStream to not hang indefinitely.
// We'll serialize the error and rethrow it on the client.
if (isServer ?? router.isServer) {
const RouteErrorComponent =
(route.options.errorComponent ??
router.options.defaultErrorComponent) ||
ErrorComponent
return (
<RouteErrorComponent
error={match.error as any}
reset={undefined as any}
info={{
componentStack: '',
}}
/>
)
}
throw match.error
}
return out
})
/**
* Render the next child match in the route tree. Typically used inside
* a route component to render nested routes.
*
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/outletComponent
*/
export const Outlet = React.memo(function OutletImpl() {
const router = useRouter()
const matchId = React.useContext(matchContext)
let routeId: string | undefined
let parentGlobalNotFound = false
let childMatchId: string | undefined
if (isServer ?? router.isServer) {
const matches = router.stores.matches.get()
const parentIndex = matchId
? matches.findIndex((match) => match.id === matchId)
: -1
const parentMatch = parentIndex >= 0 ? matches[parentIndex] : undefined
routeId = parentMatch?.routeId as string | undefined
parentGlobalNotFound = parentMatch?.globalNotFound ?? false
childMatchId =
parentIndex >= 0 ? (matches[parentIndex + 1]?.id as string) : undefined
} else {
// Subscribe directly to the match store from the pool instead of
// the two-level byId → matchStore pattern.
const parentMatchStore = matchId
? router.stores.matchStores.get(matchId)
: undefined
// eslint-disable-next-line react-hooks/rules-of-hooks
;[routeId, parentGlobalNotFound] = useStore(parentMatchStore, (match) => [
match?.routeId as string | undefined,
match?.globalNotFound ?? false,
])
// eslint-disable-next-line react-hooks/rules-of-hooks
childMatchId = useStore(router.stores.matchesId, (ids) => {
const index = ids.findIndex((id) => id === matchId)
return ids[index + 1]
})
}
const route = routeId ? router.routesById[routeId] : undefined
const pendingElement = router.options.defaultPendingComponent ? (
<router.options.defaultPendingComponent />
) : null
if (parentGlobalNotFound) {
if (!route) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(
'Invariant failed: Could not resolve route for Outlet render',
)
}
invariant()
}
return renderRouteNotFound(router, route, undefined)
}
if (!childMatchId) {
return null
}
const nextMatch = <Match matchId={childMatchId} />
if (routeId === rootRouteId) {
return (
<React.Suspense fallback={pendingElement}>{nextMatch}</React.Suspense>
)
}
return nextMatch
})
@@ -0,0 +1,25 @@
# Security Policies and Procedures
## Reporting a Bug
The `cookie` team and community take all security bugs seriously. Thank
you for improving the security of the project. We appreciate your efforts and
responsible disclosure and will make every effort to acknowledge your
contributions.
Report security bugs by emailing the current owner(s) of `cookie`. This
information can be found in the npm registry using the command
`npm owner ls cookie`.
If unsure or unable to get the information from the above, open an issue
in the [project issue tracker](https://github.com/jshttp/cookie/issues)
asking for the current contact information.
To ensure the timely response to your report, please ensure that the entirety
of the report is contained within the email body and not solely behind a web
link or an attachment.
At least one owner will acknowledge your email within 48 hours, and will send a
more detailed response within 48 hours indicating the next steps in handling
your report. After the initial reply to your report, the owners will
endeavor to keep you informed of the progress towards a fix and full
announcement, and may ask for additional information or guidance.
@@ -0,0 +1,36 @@
import type {
CodeKeywordDefinition,
KeywordErrorDefinition,
ErrorObject,
AnySchema,
} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, str} from "../../compile/codegen"
import {alwaysValidSchema} from "../../compile/util"
import {validateArray} from "../code"
import {validateAdditionalItems} from "./additionalItems"
export type ItemsError = ErrorObject<"items", {limit: number}, AnySchema>
const error: KeywordErrorDefinition = {
message: ({params: {len}}) => str`must NOT have more than ${len} items`,
params: ({params: {len}}) => _`{limit: ${len}}`,
}
const def: CodeKeywordDefinition = {
keyword: "items",
type: "array",
schemaType: ["object", "boolean"],
before: "uniqueItems",
error,
code(cxt: KeywordCxt) {
const {schema, parentSchema, it} = cxt
const {prefixItems} = parentSchema
it.items = true
if (alwaysValidSchema(it, schema)) return
if (prefixItems) validateAdditionalItems(cxt, prefixItems)
else cxt.ok(validateArray(cxt))
},
}
export default def
@@ -0,0 +1 @@
{"version":3,"file":"mouse-pointer-2.js","sources":["../../../src/icons/mouse-pointer-2.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name MousePointer2\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNNC4wMzcgNC42ODhhLjQ5NS40OTUgMCAwIDEgLjY1MS0uNjUxbDE2IDYuNWEuNS41IDAgMCAxLS4wNjMuOTQ3bC02LjEyNCAxLjU4YTIgMiAwIDAgMC0xLjQzOCAxLjQzNWwtMS41NzkgNi4xMjZhLjUuNSAwIDAgMS0uOTQ3LjA2M3oiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/mouse-pointer-2\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst MousePointer2 = createLucideIcon('MousePointer2', [\n [\n 'path',\n {\n d: 'M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z',\n key: 'edeuup',\n },\n ],\n]);\n\nexport default MousePointer2;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAgB,iBAAiB,eAAiB,CAAA,CAAA,CAAA;AAAA,CACtD,CAAA,CAAA;AAAA,CAAA,CAAA,CAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACA,CAAA,CAAA,CAAA,CAAA;AAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACH,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACP,CAAA,CAAA,CAAA,CAAA;AAAA,CACF,CAAA,CAAA;AACF,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1 @@
{"version":3,"names":["_t","require","_modules","_index","_types2","isDeclareExportDeclaration","isStatement","AnyTypeAnnotation","word","ArrayTypeAnnotation","node","print","elementType","token","BooleanTypeAnnotation","BooleanLiteralTypeAnnotation","value","NullLiteralTypeAnnotation","DeclareClass","parent","space","_interfaceish","call","DeclareFunction","id","typeAnnotation","predicate","semicolon","InferredPredicate","DeclaredPredicate","DeclareInterface","InterfaceDeclaration","DeclareModule","body","DeclareModuleExports","DeclareTypeAlias","TypeAlias","DeclareOpaqueType","OpaqueType","DeclareVariable","DeclareExportDeclaration","default","FlowExportDeclaration","DeclareExportAllDeclaration","ExportAllDeclaration","EnumDeclaration","enumExplicitType","context","name","hasExplicitType","enumBody","members","indent","newline","member","hasUnknownMembers","dedent","EnumBooleanBody","explicitType","EnumNumberBody","EnumStringBody","EnumSymbolBody","EnumDefaultedMember","enumInitializedMember","init","EnumBooleanMember","EnumNumberMember","EnumStringMember","declaration","declar","specifiers","length","printList","source","ExistsTypeAnnotation","FunctionTypeAnnotation","typeParameters","this","params","rest","type","method","returnType","FunctionTypeParam","optional","InterfaceExtends","_node$extends","extends","_node$mixins","_node$implements","mixins","implements","_variance","_node$variance","kind","variance","andSeparator","occurrenceCount","InterfaceTypeAnnotation","_node$extends2","IntersectionTypeAnnotation","printJoin","types","undefined","MixedTypeAnnotation","EmptyTypeAnnotation","NullableTypeAnnotation","NumberTypeAnnotation","StringTypeAnnotation","ThisTypeAnnotation","TupleTypeAnnotation","TypeofTypeAnnotation","argument","right","TypeAnnotation","tokenContext","TokenContext","arrowFlowReturnType","TypeParameterInstantiation","TypeParameter","bound","supertype","impltype","ObjectTypeAnnotation","exact","props","properties","callProperties","indexers","internalSlots","inexact","ObjectTypeInternalSlot","static","ObjectTypeCallProperty","ObjectTypeIndexer","key","ObjectTypeProperty","proto","ObjectTypeSpreadProperty","QualifiedTypeIdentifier","qualification","SymbolTypeAnnotation","orSeparator","UnionTypeAnnotation","TypeCastExpression","expression","Variance","VoidTypeAnnotation","IndexedAccessType","objectType","indexType","OptionalIndexedAccessType"],"sources":["../../src/generators/flow.ts"],"sourcesContent":["import type Printer from \"../printer.ts\";\nimport { isDeclareExportDeclaration, isStatement } from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport { ExportAllDeclaration } from \"./modules.ts\";\nimport { TokenContext } from \"../node/index.ts\";\n\nexport function AnyTypeAnnotation(this: Printer) {\n this.word(\"any\");\n}\n\nexport function ArrayTypeAnnotation(\n this: Printer,\n node: t.ArrayTypeAnnotation,\n) {\n this.print(node.elementType, true);\n this.token(\"[\");\n this.token(\"]\");\n}\n\nexport function BooleanTypeAnnotation(this: Printer) {\n this.word(\"boolean\");\n}\n\nexport function BooleanLiteralTypeAnnotation(\n this: Printer,\n node: t.BooleanLiteralTypeAnnotation,\n) {\n this.word(node.value ? \"true\" : \"false\");\n}\n\nexport function NullLiteralTypeAnnotation(this: Printer) {\n this.word(\"null\");\n}\n\nexport function DeclareClass(\n this: Printer,\n node: t.DeclareClass,\n parent: t.Node,\n) {\n if (!isDeclareExportDeclaration(parent)) {\n this.word(\"declare\");\n this.space();\n }\n this.word(\"class\");\n this.space();\n _interfaceish.call(this, node);\n}\n\nexport function DeclareFunction(\n this: Printer,\n node: t.DeclareFunction,\n parent: t.Node,\n) {\n if (!isDeclareExportDeclaration(parent)) {\n this.word(\"declare\");\n this.space();\n }\n this.word(\"function\");\n this.space();\n this.print(node.id);\n // @ts-ignore(Babel 7 vs Babel 8) TODO(Babel 8) Remove this comment, since we'll remove the Noop node\n this.print(node.id.typeAnnotation.typeAnnotation);\n\n if (node.predicate) {\n this.space();\n this.print(node.predicate);\n }\n\n this.semicolon();\n}\n\nexport function InferredPredicate(this: Printer) {\n this.token(\"%\");\n this.word(\"checks\");\n}\n\nexport function DeclaredPredicate(this: Printer, node: t.DeclaredPredicate) {\n this.token(\"%\");\n this.word(\"checks\");\n this.token(\"(\");\n this.print(node.value);\n this.token(\")\");\n}\n\nexport function DeclareInterface(this: Printer, node: t.DeclareInterface) {\n this.word(\"declare\");\n this.space();\n InterfaceDeclaration.call(this, node);\n}\n\nexport function DeclareModule(this: Printer, node: t.DeclareModule) {\n this.word(\"declare\");\n this.space();\n this.word(\"module\");\n this.space();\n this.print(node.id);\n this.space();\n this.print(node.body);\n}\n\nexport function DeclareModuleExports(\n this: Printer,\n node: t.DeclareModuleExports,\n) {\n this.word(\"declare\");\n thLine truncated
@@ -0,0 +1,373 @@
export default `flf2a$ 1 1 11 -1 11 0
binary.flf (C) 1994 by Victor Parada (vparada@inf.utfsm.cl) 94/12/05
figlet 2.1 font, includes ISO Latin-1, excludes "-D" option chars.
Spaces are not shown as binary. If this is required, change "$@" below
to "00100000 @". Change to "@" to remove the hardspace between words.
Note that figlet always removes spaces when it moves words to a new line.
Try option "-m 0" to remove the space between letters (octets).
$@
00100001 @
00100010 @
00100011 @
00100100 @
00100101 @
00100110 @
00100111 @
00101000 @
00101001 @
00101010 @
00101011 @
00101100 @
00101101 @
00101110 @
00101111 @
00110000 @
00110001 @
00110010 @
00110011 @
00110100 @
00110101 @
00110110 @
00110111 @
00111000 @
00111001 @
00111010 @
00111011 @
00111100 @
00111101 @
00111110 @
00111111 @
01000000 @
01000001 @
01000010 @
01000011 @
01000100 @
01000101 @
01000110 @
01000111 @
01001000 @
01001001 @
01001010 @
01001011 @
01001100 @
01001101 @
01001110 @
01001111 @
01010000 @
01010001 @
01010010 @
01010011 @
01010100 @
01010101 @
01010110 @
01010111 @
01011000 @
01011001 @
01011010 @
01011011 @
01011100 @
01011101 @
01011110 @
01011111 @
01100000 @
01100001 @
01100010 @
01100011 @
01100100 @
01100101 @
01100110 @
01100111 @
01101000 @
01101001 @
01101010 @
01101011 @
01101100 @
01101101 @
01101110 @
01101111 @
01110000 @
01110001 @
01110010 @
01110011 @
01110100 @
01110101 @
01110110 @
01110111 @
01111000 @
01111001 @
01111010 @
01111011 @
01111100 @
01111101 @
01111110 @
@
@
@
@
@
@
@
127
01111111 @
128
10000000 @
129
10000001 @
130
10000010 @
131
10000011 @
132
10000100 @
133
10000101 @
134
10000110 @
135
10000111 @
136
10001000 @
137
10001001 @
138
10001010 @
139
10001011 @
140
10001100 @
141
10001101 @
142
10001110 @
143
10001111 @
144
10010000 @
145
10010001 @
146
10010010 @
147
10010011 @
148
10010100 @
149
10010101 @
150
10010110 @
151
10010111 @
152
10011000 @
153
10011001 @
154
10011010 @
155
10011011 @
156
10011100 @
157
10011101 @
158
10011110 @
159
10011111 @
160
10100000 @
161
10100001 @
162
10100010 @
163
10100011 @
164
10100100 @
165
10100101 @
166
10100110 @
167
10100111 @
168
10101000 @
169
10101001 @
170
10101010 @
171
10101011 @
172
10101100 @
173
10101101 @
174
10101110 @
175
10101111 @
176
10110000 @
177
10110001 @
178
10110010 @
179
10110011 @
180
10110100 @
181
10110101 @
182
10110110 @
183
10110111 @
184
10111000 @
185
10111001 @
186
10111010 @
187
10111011 @
188
10111100 @
189
10111101 @
190
10111110 @
191
10111111 @
192
11000000 @
193
11000001 @
194
11000010 @
195
11000011 @
196
11000100 @
197
11000101 @
198
11000110 @
199
11000111 @
200
11001000 @
201
11001001 @
202
11001010 @
203
11001011 @
204
11001100 @
205
11001101 @
206
11001110 @
207
11001111 @
208
11010000 @
209
11010001 @
210
11010010 @
211
11010011 @
212
11010100 @
213
11010101 @
214
11010110 @
215
11010111 @
216
11011000 @
217
11011001 @
218
11011010 @
219
11011011 @
220
11011100 @
221
11011101 @
222
11011110 @
223
11011111 @
224
11100000 @
225
11100001 @
226
11100010 @
227
11100011 @
228
11100100 @
229
11100101 @
230
11100110 @
231
11100111 @
232
11101000 @
233
11101001 @
234
11101010 @
235
11101011 @
236
11101100 @
237
11101101 @
238
11101110 @
239
11101111 @
240
11110000 @
241
11110001 @
242
11110010 @
243
11110011 @
244
11110100 @
245
11110101 @
246
11110110 @
247
11110111 @
248
11111000 @
249
11111001 @
250
11111010 @
251
11111011 @
252
11111100 @
253
11111101 @
254
11111110 @
255
11111111 @
`
@@ -0,0 +1,8 @@
{
"description": "separate entrypoint for constants only",
"private": true,
"main": "../dist/es5/constants.js",
"jsnext:main": "../dist/es2015/constants.js",
"module": "../dist/es2015/constants.js",
"sideEffects": false
}
@@ -0,0 +1 @@
{"version":3,"file":"symlink-error.js","sourceRoot":"","sources":["../../src/symlink-error.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,YAAa,SAAQ,KAAK;IACrC,IAAI,CAAQ;IACZ,OAAO,CAAQ;IACf,OAAO,GAAG,SAAkB,CAAA;IAC5B,IAAI,GAAG,mBAA4B,CAAA;IACnC,YAAY,OAAe,EAAE,IAAY;QACvC,KAAK,CAAC,yDAAyD,CAAC,CAAA;QAChE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;IAClB,CAAC;IACD,IAAI,IAAI;QACN,OAAO,cAAc,CAAA;IACvB,CAAC;CACF","sourcesContent":["export class SymlinkError extends Error {\n path: string\n symlink: string\n syscall = 'symlink' as const\n code = 'TAR_SYMLINK_ERROR' as const\n constructor(symlink: string, path: string) {\n super('TAR_SYMLINK_ERROR: Cannot extract through symbolic link')\n this.symlink = symlink\n this.path = path\n }\n get name() {\n return 'SymlinkError'\n }\n}\n"]}
@@ -0,0 +1,34 @@
import { MIN_YEAR_SPACE, REFERENCE_YEAR } from '../../data/const'
import { MatchEstimated, MatchExtended } from '../../types'
export default ({
regexName,
regexMatch,
token,
}: MatchExtended | MatchEstimated) => {
const charClassBases = {
alphaLower: 26,
alphaUpper: 26,
alpha: 52,
alphanumeric: 62,
digits: 10,
symbols: 33,
}
if (regexName in charClassBases) {
return (
charClassBases[regexName as keyof typeof charClassBases] ** token.length
)
}
// TODO add more regex types for example special dates like 09.11
switch (regexName) {
case 'recentYear':
// conservative estimate of year space: num years from REFERENCE_YEAR.
// if year is close to REFERENCE_YEAR, estimate a year space of MIN_YEAR_SPACE.
return Math.max(
Math.abs(parseInt(regexMatch[0], 10) - REFERENCE_YEAR),
MIN_YEAR_SPACE,
)
}
return 0
}
@@ -0,0 +1,232 @@
import { PrettyFormatOptions } from '@vitest/pretty-format';
import { SequenceHooks, SequenceSetupFiles, SerializableRetry, TestTagDefinition } from '@vitest/runner';
import { SnapshotUpdateState, SnapshotEnvironment } from '@vitest/snapshot';
import { SerializedDiffOptions } from '@vitest/utils/diff';
import { L as LabelColor } from './traces.d.D2T_R8rx.js';
/**
* Names of clock methods that may be faked by install.
*/
type FakeMethod =
| "setTimeout"
| "clearTimeout"
| "setImmediate"
| "clearImmediate"
| "setInterval"
| "clearInterval"
| "Date"
| "nextTick"
| "hrtime"
| "requestAnimationFrame"
| "cancelAnimationFrame"
| "requestIdleCallback"
| "cancelIdleCallback"
| "performance"
| "queueMicrotask";
interface FakeTimerInstallOpts {
/**
* Installs fake timers with the specified unix epoch (default: 0)
*/
now?: number | Date | undefined;
/**
* An array with names of global methods and APIs to fake. By default, `@sinonjs/fake-timers` does not replace `nextTick()` and `queueMicrotask()`.
* For instance, `FakeTimers.install({ toFake: ['setTimeout', 'nextTick'] })` will fake only `setTimeout()` and `nextTick()`
*/
toFake?: FakeMethod[] | undefined;
/**
* The maximum number of timers that will be run when calling runAll() (default: 1000)
*/
loopLimit?: number | undefined;
/**
* Tells @sinonjs/fake-timers to increment mocked time automatically based on the real system time shift (e.g. the mocked time will be incremented by
* 20ms for every 20ms change in the real system time) (default: false)
*/
shouldAdvanceTime?: boolean | undefined;
/**
* Relevant only when using with shouldAdvanceTime: true. increment mocked time by advanceTimeDelta ms every advanceTimeDelta ms change
* in the real system time (default: 20)
*/
advanceTimeDelta?: number | undefined;
/**
* Tells FakeTimers to clear 'native' (i.e. not fake) timers by delegating to their respective handlers. These are not cleared by
* default, leading to potentially unexpected behavior if timers existed prior to installing FakeTimers. (default: false)
*/
shouldClearNativeTimers?: boolean | undefined;
/**
* Tells FakeTimers to not throw an error when faking a timer that does not exist in the global object. (default: false)
*/
ignoreMissingTimers?: boolean | undefined;
}
/**
* Config that tests have access to.
*/
interface SerializedConfig {
name: string | undefined;
color?: LabelColor;
globals: boolean;
base: string | undefined;
snapshotEnvironment?: string;
disableConsoleIntercept: boolean | undefined;
runner: string | undefined;
isolate: boolean;
maxWorkers: number;
mode: "test" | "benchmark";
bail: number | undefined;
environmentOptions?: Record<string, any>;
root: string;
setupFiles: string[];
passWithNoTests: boolean;
testNamePattern: RegExp | undefined;
allowOnly: boolean;
testTimeout: number;
hookTimeout: number;
clearMocks: boolean;
mockReset: boolean;
restoreMocks: boolean;
unstubGlobals: boolean;
unstubEnvs: boolean;
fakeTimers: FakeTimerInstallOpts;
maxConcurrency: number;
defines: Record<string, any>;
expect: {
requireAssertions?: boolean;
poll?: {
timeout?: number;
interval?: number;
};
};
printConsoleTrace: boolean | undefined;
sequence: {
shuffle?: boolean;
concurrent?: boolean;
seed: number;
hooks: SequenceHooks;
setupFiles: SequenceSetupFiles;
};
deps: {
web: {
transformAssets?: boolean;
transformCss?: boolean;
transformGlobPattern?: RegExp | RegExp[];
};
optimizer: Record<string, {
enabled: boolean;
}>;
interopDefault: boolean | undefined;
moduleDirectories: string[] | undefined;
};
snapshotOptions: {
updateSnapshot: SnapshotUpdateState;
expand: boolean | undefined;
snapshotFormat: PrettyFormatOptions | undefined;
/**
* only exists for tests, not available in the main process
*/
snapshotEnvironment: SnapshotEnvironment;
};
pool: string;
snapshotSerializers: string[];
chaiConfig: {
includeStack?: boolean;
showDiff?: boolean;
truncateThreshold?: number;
} | undefined;
api: {
allowExec: boolean | undefined;
allowWrite: boolean | undefined;
};
diff: string | SerializedDiffOptions | undefined;
retry: SerializableRetry;
includeTaskLocation: boolean | undefined;
inspect: boolean | string | undefined;
inspectBrk: boolean | string | undefined;
inspector: {
enabled?: boolean;
port?: number;
host?: string;
waitForDebugger?: boolean;
};
watch: boolean;
env: Record<string, any>;
browser: {
name: string;
headless: boolean;
isolate: boolean;
fileParallelism: boolean;
ui: boolean;
viewport: {
width: number;
height: number;
};
locators: {
testIdAttribute: string;
exact: boolean;
};
screenshotFailures: boolean;
providerOptions: {
actionTimeout?: number;
};
trace: BrowserTraceViewMode;
trackUnhandledErrors: boolean;
detailsPanelPosition: "right" | "bottom";
};
standalone: boolean;
logHeapUsage: boolean | undefined;
detectAsyncLeaks: boolean;
coverage: SerializedCoverageConfig;
benchmark: {
includeSamples: boolean;
} | undefined;
serializedDefines: string;
experimental: {
fsModuleCache: boolean;
importDurations: {
print: boolean | "on-warn";
limit: number;
failOnDanger: boolean;
thresholds: {
warn: number;
danger: number;
};
};
viteModuleRunner: boolean;
nodeLoader: boolean;
openTelemetry: {
enabled: boolean;
sdkPath?: string;
browserSdkPath?: string;
} | undefined;
};
tags: TestTagDefinition[];
tagsFilter: string[] | undefined;
strictTags: boolean;
slowTestThreshold: number | undefined;
isAgent: boolean;
}
interface SerializedCoverageConfig {
provider: "istanbul" | "v8" | "custom" | undefined;
reportsDirectory: string;
htmlDir: string | undefined;
enabled: boolean;
customProviderModule: string | undefined;
}
interface SerializedRootConfig extends SerializedConfig {
projects: SerializedConfig[];
}
type RuntimeConfig = Pick<SerializedConfig, "allowOnly" | "testTimeout" | "hookTimeout" | "clearMocks" | "mockReset" | "restoreMocks" | "fakeTimers" | "maxConcurrency" | "expect" | "printConsoleTrace"> & {
sequence?: {
hooks?: SequenceHooks;
};
};
type RuntimeOptions = Partial<RuntimeConfig>;
type BrowserTraceViewMode = "on" | "off" | "on-first-retry" | "on-all-retries" | "retain-on-failure";
export type { BrowserTraceViewMode as B, FakeTimerInstallOpts as F, RuntimeOptions as R, SerializedConfig as S, SerializedCoverageConfig as a, SerializedRootConfig as b, RuntimeConfig as c };
@@ -0,0 +1,53 @@
const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
let _tanstack_router_core_ssr_server = require("@tanstack/router-core/ssr/server");
let react_dom_server = require("react-dom/server");
react_dom_server = require_runtime.__toESM(react_dom_server);
let node_stream = require("node:stream");
let isbot = require("isbot");
//#region src/ssr/renderRouterToStream.tsx
var renderRouterToStream = async ({ request, router, responseHeaders, children }) => {
if (typeof react_dom_server.default.renderToReadableStream === "function") {
const stream = await react_dom_server.default.renderToReadableStream(children, {
signal: request.signal,
nonce: router.options.ssr?.nonce,
progressiveChunkSize: Number.POSITIVE_INFINITY
});
if ((0, isbot.isbot)(request.headers.get("User-Agent"))) await stream.allReady;
const responseStream = (0, _tanstack_router_core_ssr_server.transformReadableStreamWithRouter)(router, stream);
return new Response(responseStream, {
status: router.stores.statusCode.get(),
headers: responseHeaders
});
}
if (typeof react_dom_server.default.renderToPipeableStream === "function") {
const reactAppPassthrough = new node_stream.PassThrough();
try {
const pipeable = react_dom_server.default.renderToPipeableStream(children, {
nonce: router.options.ssr?.nonce,
progressiveChunkSize: Number.POSITIVE_INFINITY,
...(0, isbot.isbot)(request.headers.get("User-Agent")) ? { onAllReady() {
pipeable.pipe(reactAppPassthrough);
} } : { onShellReady() {
pipeable.pipe(reactAppPassthrough);
} },
onError: (error, info) => {
console.error("Error in renderToPipeableStream:", error, info);
if (!reactAppPassthrough.destroyed) reactAppPassthrough.destroy(error instanceof Error ? error : new Error(String(error)));
}
});
} catch (e) {
console.error("Error in renderToPipeableStream:", e);
reactAppPassthrough.destroy(e instanceof Error ? e : new Error(String(e)));
}
const responseStream = (0, _tanstack_router_core_ssr_server.transformPipeableStreamWithRouter)(router, reactAppPassthrough);
return new Response(responseStream, {
status: router.stores.statusCode.get(),
headers: responseHeaders
});
}
throw new Error("No renderToReadableStream or renderToPipeableStream found in react-dom/server. Ensure you are using a version of react-dom that supports streaming.");
};
//#endregion
exports.renderRouterToStream = renderRouterToStream;
//# sourceMappingURL=renderRouterToStream.cjs.map
@@ -0,0 +1,63 @@
'use strict'
const path = require('path')
const log = require('./log')
function findNodeDirectory (scriptLocation, processObj) {
// set dirname and process if not passed in
// this facilitates regression tests
if (scriptLocation === undefined) {
scriptLocation = __dirname
}
if (processObj === undefined) {
processObj = process
}
// Have a look to see what is above us, to try and work out where we are
const npmParentDirectory = path.join(scriptLocation, '../../../..')
log.verbose('node-gyp root', 'npm_parent_directory is ' +
path.basename(npmParentDirectory))
let nodeRootDir = ''
log.verbose('node-gyp root', 'Finding node root directory')
if (path.basename(npmParentDirectory) === 'deps') {
// We are in a build directory where this script lives in
// deps/npm/node_modules/node-gyp/lib
nodeRootDir = path.join(npmParentDirectory, '..')
log.verbose('node-gyp root', 'in build directory, root = ' +
nodeRootDir)
} else if (path.basename(npmParentDirectory) === 'node_modules') {
// We are in a node install directory where this script lives in
// lib/node_modules/npm/node_modules/node-gyp/lib or
// node_modules/npm/node_modules/node-gyp/lib depending on the
// platform
if (processObj.platform === 'win32') {
nodeRootDir = path.join(npmParentDirectory, '..')
} else {
nodeRootDir = path.join(npmParentDirectory, '../..')
}
log.verbose('node-gyp root', 'in install directory, root = ' +
nodeRootDir)
} else {
// We don't know where we are, try working it out from the location
// of the node binary
const nodeDir = path.dirname(processObj.execPath)
const directoryUp = path.basename(nodeDir)
if (directoryUp === 'bin') {
nodeRootDir = path.join(nodeDir, '..')
} else if (directoryUp === 'Release' || directoryUp === 'Debug') {
// If we are a recently built node, and the directory structure
// is that of a repository. If we are on Windows then we only need
// to go one level up, everything else, two
if (processObj.platform === 'win32') {
nodeRootDir = path.join(nodeDir, '..')
} else {
nodeRootDir = path.join(nodeDir, '../..')
}
}
// Else return the default blank, "".
}
return nodeRootDir
}
module.exports = findNodeDirectory
@@ -0,0 +1,122 @@
iMurmurHash.js
==============
An incremental implementation of the MurmurHash3 (32-bit) hashing algorithm for JavaScript based on [Gary Court's implementation](https://github.com/garycourt/murmurhash-js) with [kazuyukitanimura's modifications](https://github.com/kazuyukitanimura/murmurhash-js).
This version works significantly faster than the non-incremental version if you need to hash many small strings into a single hash, since string concatenation (to build the single string to pass the non-incremental version) is fairly costly. In one case tested, using the incremental version was about 50% faster than concatenating 5-10 strings and then hashing.
Installation
------------
To use iMurmurHash in the browser, [download the latest version](https://raw.github.com/jensyt/imurmurhash-js/master/imurmurhash.min.js) and include it as a script on your site.
```html
<script type="text/javascript" src="/scripts/imurmurhash.min.js"></script>
<script>
// Your code here, access iMurmurHash using the global object MurmurHash3
</script>
```
---
To use iMurmurHash in Node.js, install the module using NPM:
```bash
npm install imurmurhash
```
Then simply include it in your scripts:
```javascript
MurmurHash3 = require('imurmurhash');
```
Quick Example
-------------
```javascript
// Create the initial hash
var hashState = MurmurHash3('string');
// Incrementally add text
hashState.hash('more strings');
hashState.hash('even more strings');
// All calls can be chained if desired
hashState.hash('and').hash('some').hash('more');
// Get a result
hashState.result();
// returns 0xe4ccfe6b
```
Functions
---------
### MurmurHash3 ([string], [seed])
Get a hash state object, optionally initialized with the given _string_ and _seed_. _Seed_ must be a positive integer if provided. Calling this function without the `new` keyword will return a cached state object that has been reset. This is safe to use as long as the object is only used from a single thread and no other hashes are created while operating on this one. If this constraint cannot be met, you can use `new` to create a new state object. For example:
```javascript
// Use the cached object, calling the function again will return the same
// object (but reset, so the current state would be lost)
hashState = MurmurHash3();
...
// Create a new object that can be safely used however you wish. Calling the
// function again will simply return a new state object, and no state loss
// will occur, at the cost of creating more objects.
hashState = new MurmurHash3();
```
Both methods can be mixed however you like if you have different use cases.
---
### MurmurHash3.prototype.hash (string)
Incrementally add _string_ to the hash. This can be called as many times as you want for the hash state object, including after a call to `result()`. Returns `this` so calls can be chained.
---
### MurmurHash3.prototype.result ()
Get the result of the hash as a 32-bit positive integer. This performs the tail and finalizer portions of the algorithm, but does not store the result in the state object. This means that it is perfectly safe to get results and then continue adding strings via `hash`.
```javascript
// Do the whole string at once
MurmurHash3('this is a test string').result();
// 0x70529328
// Do part of the string, get a result, then the other part
var m = MurmurHash3('this is a');
m.result();
// 0xbfc4f834
m.hash(' test string').result();
// 0x70529328 (same as above)
```
---
### MurmurHash3.prototype.reset ([seed])
Reset the state object for reuse, optionally using the given _seed_ (defaults to 0 like the constructor). Returns `this` so calls can be chained.
---
License (MIT)
-------------
Copyright (c) 2013 Gary Court, Jens Taylor
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,113 @@
import * as util from "../core/util.js";
const error = () => {
const Sizable = {
string: { unit: "tegn", verb: "å ha" },
file: { unit: "bytes", verb: "å ha" },
array: { unit: "elementer", verb: "å inneholde" },
set: { unit: "elementer", verb: "å inneholde" },
map: { unit: "elementer", verb: "å inneholde" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "input",
email: "e-postadresse",
url: "URL",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "ISO dato- og klokkeslett",
date: "ISO-dato",
time: "ISO-klokkeslett",
duration: "ISO-varighet",
ipv4: "IPv4-adresse",
ipv6: "IPv6-adresse",
mac: "MAC-adresse",
cidrv4: "IPv4-spekter",
cidrv6: "IPv6-spekter",
base64: "base64-enkodet streng",
base64url: "base64url-enkodet streng",
json_string: "JSON-streng",
e164: "E.164-nummer",
credit_card: "kredittkortnummer",
currency_code: "valutakode",
iban: "IBAN",
jwt: "JWT",
template_literal: "input",
};
const TypeDictionary = {
nan: "NaN",
number: "tall",
array: "liste",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (/^[A-Z]/.test(issue.expected)) {
return `Ugyldig input: forventet instanceof ${issue.expected}, fikk ${received}`;
}
return `Ugyldig input: forventet ${expected}, fikk ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Ugyldig verdi: forventet ${util.stringifyPrimitive(issue.values[0])}`;
return `Ugyldig valg: forventet en av ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `For stor(t): forventet ${issue.origin ?? "value"} til å ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementer"}`;
return `For stor(t): forventet ${issue.origin ?? "value"} til å ha ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `For lite(n): forventet ${issue.origin} til å ha ${adj}${issue.minimum.toString()} ${sizing.unit}`;
}
return `For lite(n): forventet ${issue.origin} til å ha ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with")
return `Ugyldig streng: må starte med "${_issue.prefix}"`;
if (_issue.format === "ends_with")
return `Ugyldig streng: må ende med "${_issue.suffix}"`;
if (_issue.format === "includes")
return `Ugyldig streng: må inneholde "${_issue.includes}"`;
if (_issue.format === "regex")
return `Ugyldig streng: må matche mønsteret ${_issue.pattern}`;
return `Ugyldig ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Ugyldig tall: må være et multiplum av ${issue.divisor}`;
case "unrecognized_keys":
return `${issue.keys.length > 1 ? "Ukjente nøkler" : "Ukjent nøkkel"}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Ugyldig nøkkel i ${issue.origin}`;
case "invalid_union":
return "Ugyldig input";
case "invalid_element":
return `Ugyldig verdi i ${issue.origin}`;
default:
return `Ugyldig input`;
}
};
};
export default function () {
return {
localeError: error(),
};
}
@@ -0,0 +1,7 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_headers = require("./headers.cjs");
const require_json = require("./json.cjs");
const require_ssr_client = require("./ssr-client.cjs");
exports.hydrate = require_ssr_client.hydrate;
exports.json = require_json.json;
exports.mergeHeaders = require_headers.mergeHeaders;
@@ -0,0 +1 @@
module.exports={A:{A:{"1":"_V","2":"_MQ","132":"_RJ"},B:{"1":"_J"},C:{"1":"_S"},D:{"1":"_xO","2":"_5"},E:{"1":"_R"},F:{"1":"_c"},G:{"1":"_eB","2":"lC"},H:{"1":"1D"},I:{"1":"_8B","2":"_n"},J:{"1":"A","2":"D"},K:{"1":"_N"},L:{"1":"I"},M:{"1":"YC"},N:{"1":"_A"},O:{"1":"bC"},P:{"1":"_F"},Q:{"1":"JE"},R:{"1":"KE"},S:{"1":"_C"}},B:6,C:"Server Name Indication",D:true};
@@ -0,0 +1 @@
{"version":3,"file":"twitch.js","sources":["../../../src/icons/twitch.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Twitch\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMjEgMkgzdjE2aDV2NGw0LTRoNWw0LTRWMnptLTEwIDlWN201IDRWNyIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/twitch\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n * @deprecated Brand icons have been deprecated and are due to be removed, please refer to https://github.com/lucide-icons/lucide/issues/670. We recommend using https://simpleicons.org/?q=twitch instead. This icon will be removed in v1.0\n */\nconst Twitch = createLucideIcon('Twitch', [\n ['path', { d: 'M21 2H3v16h5v4l4-4h5l4-4V2zm-10 9V7m5 4V7', key: 'c0yzno' }],\n]);\n\nexport default Twitch;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAS,iBAAiB,QAAU,CAAA,CAAA,CAAA;AAAA,CAAA,CACxC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAA6C,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC5E,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,198 @@
<h1 align="center">
<img alt="Standard Schema fire logo" loading="lazy" width="50" height="50" decoding="async" data-nimg="1" style="color:transparent" src="https://standardschema.dev/favicon.svg">
</br>
Standard Schema</h1>
<p align="center">
A family of specs for interoperable TypeScript
<br/>
<a href="https://standardschema.dev">standardschema.dev</a>
</p>
<br/>
<!-- start -->
The Standard Schema project is a set of interfaces that standardize the provision and consumption of shared functionality in the TypeScript ecosystem.
Its goal is to allow tools to accept a single input that includes all the types and capabilities they need— no library-specific adapters, no extra dependencies. The result is an ecosystem that's fair for implementers, friendly for consumers, and open for end users.
## The specifications
The specifications can be found below in their entirety. Libraries wishing to implement a spec can copy/paste the code block below into their codebase. They're also available at `@standard-schema/spec` on [npm](https://www.npmjs.com/package/@standard-schema/spec) and [JSR](https://jsr.io/@standard-schema/spec).
```ts
// #########################
// ### Standard Typed ###
// #########################
/** The Standard Typed interface. This is a base type extended by other specs. */
export interface StandardTypedV1<Input = unknown, Output = Input> {
/** The Standard properties. */
readonly "~standard": StandardTypedV1.Props<Input, Output>;
}
export declare namespace StandardTypedV1 {
/** The Standard Typed properties interface. */
export interface Props<Input = unknown, Output = Input> {
/** The version number of the standard. */
readonly version: 1;
/** The vendor name of the schema library. */
readonly vendor: string;
/** Inferred types associated with the schema. */
readonly types?: Types<Input, Output> | undefined;
}
/** The Standard Typed types interface. */
export interface Types<Input = unknown, Output = Input> {
/** The input type of the schema. */
readonly input: Input;
/** The output type of the schema. */
readonly output: Output;
}
/** Infers the input type of a Standard Typed. */
export type InferInput<Schema extends StandardTypedV1> = NonNullable<
Schema["~standard"]["types"]
>["input"];
/** Infers the output type of a Standard Typed. */
export type InferOutput<Schema extends StandardTypedV1> = NonNullable<
Schema["~standard"]["types"]
>["output"];
}
// ##########################
// ### Standard Schema ###
// ##########################
/** The Standard Schema interface. */
export interface StandardSchemaV1<Input = unknown, Output = Input> {
/** The Standard Schema properties. */
readonly "~standard": StandardSchemaV1.Props<Input, Output>;
}
export declare namespace StandardSchemaV1 {
/** The Standard Schema properties interface. */
export interface Props<Input = unknown, Output = Input>
extends StandardTypedV1.Props<Input, Output> {
/** Validates unknown input values. */
readonly validate: (
value: unknown,
options?: StandardSchemaV1.Options | undefined
) => Result<Output> | Promise<Result<Output>>;
}
/** The result interface of the validate function. */
export type Result<Output> = SuccessResult<Output> | FailureResult;
/** The result interface if validation succeeds. */
export interface SuccessResult<Output> {
/** The typed output value. */
readonly value: Output;
/** A falsy value for `issues` indicates success. */
readonly issues?: undefined;
}
export interface Options {
/** Explicit support for additional vendor-specific parameters, if needed. */
readonly libraryOptions?: Record<string, unknown> | undefined;
}
/** The result interface if validation fails. */
export interface FailureResult {
/** The issues of failed validation. */
readonly issues: ReadonlyArray<Issue>;
}
/** The issue interface of the failure output. */
export interface Issue {
/** The error message of the issue. */
readonly message: string;
/** The path of the issue, if any. */
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
}
/** The path segment interface of the issue. */
export interface PathSegment {
/** The key representing a path segment. */
readonly key: PropertyKey;
}
/** The Standard types interface. */
export interface Types<Input = unknown, Output = Input>
extends StandardTypedV1.Types<Input, Output> {}
/** Infers the input type of a Standard. */
export type InferInput<Schema extends StandardTypedV1> =
StandardTypedV1.InferInput<Schema>;
/** Infers the output type of a Standard. */
export type InferOutput<Schema extends StandardTypedV1> =
StandardTypedV1.InferOutput<Schema>;
}
// ###############################
// ### Standard JSON Schema ###
// ###############################
/** The Standard JSON Schema interface. */
export interface StandardJSONSchemaV1<Input = unknown, Output = Input> {
/** The Standard JSON Schema properties. */
readonly "~standard": StandardJSONSchemaV1.Props<Input, Output>;
}
export declare namespace StandardJSONSchemaV1 {
/** The Standard JSON Schema properties interface. */
export interface Props<Input = unknown, Output = Input>
extends StandardTypedV1.Props<Input, Output> {
/** Methods for generating the input/output JSON Schema. */
readonly jsonSchema: StandardJSONSchemaV1.Converter;
}
/** The Standard JSON Schema converter interface. */
export interface Converter {
/** Converts the input type to JSON Schema. May throw if conversion is not supported. */
readonly input: (
options: StandardJSONSchemaV1.Options
) => Record<string, unknown>;
/** Converts the output type to JSON Schema. May throw if conversion is not supported. */
readonly output: (
options: StandardJSONSchemaV1.Options
) => Record<string, unknown>;
}
/**
* The target version of the generated JSON Schema.
*
* It is *strongly recommended* that implementers support `"draft-2020-12"` and `"draft-07"`, as they are both in wide use. All other targets can be implemented on a best-effort basis. Libraries should throw if they don't support a specified target.
*
* The `"openapi-3.0"` target is intended as a standardized specifier for OpenAPI 3.0 which is a superset of JSON Schema `"draft-04"`.
*/
export type Target =
| "draft-2020-12"
| "draft-07"
| "openapi-3.0"
// Accepts any string for future targets while preserving autocomplete
| ({} & string);
/** The options for the input/output methods. */
export interface Options {
/** Specifies the target version of the generated JSON Schema. Support for all versions is on a best-effort basis. If a given version is not supported, the library should throw. */
readonly target: Target;
/** Explicit support for additional vendor-specific parameters, if needed. */
readonly libraryOptions?: Record<string, unknown> | undefined;
}
/** The Standard types interface. */
export interface Types<Input = unknown, Output = Input>
extends StandardTypedV1.Types<Input, Output> {}
/** Infers the input type of a Standard. */
export type InferInput<Schema extends StandardTypedV1> =
StandardTypedV1.InferInput<Schema>;
/** Infers the output type of a Standard. */
export type InferOutput<Schema extends StandardTypedV1> =
StandardTypedV1.InferOutput<Schema>;
}
```
@@ -0,0 +1,23 @@
import { ConsolaInstance, ConsolaOptions } from './core.cjs';
export { ConfirmPromptOptions, Consola, ConsolaReporter, FormatOptions, InputLogObject, LogLevel, LogLevels, LogObject, LogType, LogTypes, MultiSelectOptions, PromptOptions, SelectPromptOptions, TextPromptOptions } from './core.cjs';
/**
* Creates a new Consola instance configured specifically for browser environments.
* This function sets up default reporters and a prompt method tailored to the browser's dialogue APIs.
*
* @param {Partial<ConsolaOptions>} [options={}] - Optional configuration options.
* The options can override the default reporter and prompt behaviour. See {@link ConsolaOptions}.
* @returns {ConsolaInstance} A new Consola instance optimised for use in browser environments.
*/
declare function createConsola(options?: Partial<ConsolaOptions>): ConsolaInstance;
/**
* A standard Consola instance created with browser-specific configurations.
* This instance can be used throughout a browser-based project.
*
* @type {ConsolaInstance} consola - The default browser-configured Consola instance.
*/
declare const consola: ConsolaInstance;
// @ts-ignore
export = consola;
export { ConsolaInstance, ConsolaOptions, consola, createConsola };
@@ -0,0 +1,13 @@
"use strict"
var hasOwn = typeof Object.hasOwn === "undefined" ? Function.call.bind(Object.prototype.hasOwnProperty) : Object.hasOwn
function mergeModules (target, module) {
for (var key in module) {
if (hasOwn(module, key)) {
target[key] = module[key]
}
}
}
module.exports = mergeModules