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,180 @@
/**
* @fileoverview Rule to flag adding properties to native object's prototypes.
* @author David Nelson
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
defaultOptions: [{ exceptions: [] }],
docs: {
description: "Disallow extending native types",
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-extend-native",
},
schema: [
{
type: "object",
properties: {
exceptions: {
type: "array",
items: {
type: "string",
},
uniqueItems: true,
},
},
additionalProperties: false,
},
],
messages: {
unexpected:
"{{builtin}} prototype is read only, properties should not be added.",
},
},
create(context) {
const sourceCode = context.sourceCode;
const exceptions = new Set(context.options[0].exceptions);
const modifiedBuiltins = new Set(
Object.keys(astUtils.ECMASCRIPT_GLOBALS)
.filter(builtin => builtin[0].toUpperCase() === builtin[0])
.filter(builtin => !exceptions.has(builtin)),
);
/**
* Reports a lint error for the given node.
* @param {ASTNode} node The node to report.
* @param {string} builtin The name of the native builtin being extended.
* @returns {void}
*/
function reportNode(node, builtin) {
context.report({
node,
messageId: "unexpected",
data: {
builtin,
},
});
}
/**
* Check to see if the `prototype` property of the given object
* identifier node is being accessed.
* @param {ASTNode} identifierNode The Identifier representing the object
* to check.
* @returns {boolean} True if the identifier is the object of a
* MemberExpression and its `prototype` property is being accessed,
* false otherwise.
*/
function isPrototypePropertyAccessed(identifierNode) {
return Boolean(
identifierNode &&
identifierNode.parent &&
identifierNode.parent.type === "MemberExpression" &&
identifierNode.parent.object === identifierNode &&
astUtils.getStaticPropertyName(identifierNode.parent) ===
"prototype",
);
}
/**
* Check if it's an assignment to the property of the given node.
* Example: `*.prop = 0` // the `*` is the given node.
* @param {ASTNode} node The node to check.
* @returns {boolean} True if an assignment to the property of the node.
*/
function isAssigningToPropertyOf(node) {
return (
node.parent.type === "MemberExpression" &&
node.parent.object === node &&
node.parent.parent.type === "AssignmentExpression" &&
node.parent.parent.left === node.parent
);
}
/**
* Checks if the given node is at the first argument of the method call of `Object.defineProperty()` or `Object.defineProperties()`.
* @param {ASTNode} node The node to check.
* @returns {boolean} True if the node is at the first argument of the method call of `Object.defineProperty()` or `Object.defineProperties()`.
*/
function isInDefinePropertyCall(node) {
return (
node.parent.type === "CallExpression" &&
node.parent.arguments[0] === node &&
astUtils.isSpecificMemberAccess(
node.parent.callee,
"Object",
/^definePropert(?:y|ies)$/u,
)
);
}
/**
* Check to see if object prototype access is part of a prototype
* extension. There are three ways a prototype can be extended:
* 1. Assignment to prototype property (Object.prototype.foo = 1)
* 2. Object.defineProperty()/Object.defineProperties() on a prototype
* If prototype extension is detected, report the AssignmentExpression
* or CallExpression node.
* @param {ASTNode} identifierNode The Identifier representing the object
* which prototype is being accessed and possibly extended.
* @returns {void}
*/
function checkAndReportPrototypeExtension(identifierNode) {
if (!isPrototypePropertyAccessed(identifierNode)) {
return; // This is not `*.prototype` access.
}
/*
* `identifierNode.parent` is a MemberExpression `*.prototype`.
* If it's an optional member access, it may be wrapped by a `ChainExpression` node.
*/
const prototypeNode =
identifierNode.parent.parent.type === "ChainExpression"
? identifierNode.parent.parent
: identifierNode.parent;
if (isAssigningToPropertyOf(prototypeNode)) {
// `*.prototype` -> MemberExpression -> AssignmentExpression
reportNode(prototypeNode.parent.parent, identifierNode.name);
} else if (isInDefinePropertyCall(prototypeNode)) {
// `*.prototype` -> CallExpression
reportNode(prototypeNode.parent, identifierNode.name);
}
}
return {
"Program:exit"(node) {
const globalScope = sourceCode.getScope(node);
modifiedBuiltins.forEach(builtin => {
const builtinVar = globalScope.set.get(builtin);
if (builtinVar && builtinVar.references) {
builtinVar.references
.map(ref => ref.identifier)
.forEach(checkAndReportPrototypeExtension);
}
});
},
};
},
};
@@ -0,0 +1 @@
{"version":3,"file":"ajvProvider-FOQRM7up.d.cts","names":["URIComponent","_CodeOrName","UsedNames","IDENTIFIER","RegExp","Name","_Code","CodeItem","Record","Code","SafeExpr","nil","CodeArg","_","TemplateStringsArray","str","addCodeArg","strConcat","stringify","safeStringify","getProperty","getEsmExportName","regexpCode","Code","Name","NameGroup","NameValue","ValueReference","ScopeOptions","Set","Scope","ValueScopeOptions","ScopeStore","Record","ScopeValues","ValueScopeName","Map","ScopeValueSets","UsedValueState","UsedScopeValues","varKinds","prefixes","parent","ScopePath","property","itemIndex","VSOptions","ValueScope","ScopeValueSets","NameValue","ValueScope","ValueScopeName","_Code","Code","Name","Scope","_","str","strConcat","nil","getProperty","stringify","regexpCode","ScopeStore","varKinds","SafeExpr","Block","operators","CodeGenOptions","CodeGen","not","T","and","or","AddedKeywordDefinition","_jsonTypes","JSONType","isJSONType","ValidationTypes","RuleGroup","ValidationRules","Rule","getRules","AnySchema","EvaluatedProperties","EvaluatedItems","SchemaCxt","SchemaObjCxt","Code","Name","CodeGen","Rule","ValidationRules","toHash","T","alwaysValidSchema","checkUnknownRules","schemaHasRules","schemaHasRulesButRef","schemaRefOrVal","topSchemaRef","schemaPath","unescapeFragment","escapeFragment","escapeJsonPointer","unescapeJsonPointer","eachItem","SomeEvaluated","MergeEvaluatedFunc","Exclude","MergeEvaluated","mergeEvaluated","evaluatedPropsToName","setEvaluated","useFunc","Type","getErrorPath","checkStrictMode","AnySchema","SchemaObjCxt","Code","Name","Type","JSONType","SubschemaContext","SubschemaArgs","Set","Partial","getSubschema","keyword","schemaProp","schema","schemaPath","errSchemaPath","topSchemaRef","extendSubschemaData","dataProp","dpType","data","dataTypes","propertyName","extendSubschemaMode","jtdDiscriminator","jtdMetadata","compositeRule","createErrors","allErrors","KeywordErrorCxt","KeywordErrorDefinition","CodeGen","Code","Name","keywordError","keyword$DataError","ErrorPaths","reportError","reportExtraError","resetErrorsCount","extendErrors","gen","keyword","schemaValue","data","errsCount","it","AddedKeywordDefinition","AnySchemaObject","KeywordErrorCxt","KeywordCxtParams","SchemaCxt","SchemaObjCxt","SubschemaArgs","Code","Name","CodeGen","JSONType","ErrorPaths","validateFunctionCode","KeywordCxt","getData","dataLevel","dataNames","dataPathArr","StrictNullChecksWrapper","Name","Type","UnionToIntersection","U","SomeJSONSchema","Known","UncheckedJSONSchemaType","UncheckedPartialSchema","T","Partial","PartialSchema","JSONType","IsPartial","NumberKeywords","StringKeywords","K","Nullable","Record","UncheckedPropertiesSchema","Omit","UncheckedRequiredMembers","JSONSchemaType","PropertiesSchema","RequiredMembers","NumberType","StringType","SomeJTDSchemaType","Record","RequiredKeys","T","K","OptionalKeys","IsUnion_","U","IsUnion","TypeEquality","E","NullTypeEquality","EnumString","IsEnum","IsElements","IsValues","IsRecord","Union","IsEmptyRecord","JTDSchemaType","D","Exclude","Date","V","M","Omit","JTDDataDef","S","JTDDataType","ErrorObject","ValidationError","Partial","Error","default","UriResolver","MissingRefError","Error","default","Format","FormatDefinition","AsyncFormatDefinition","KeywordDefinition","KeywordErrorDefinition","CodeKeywordDefinition","MacroKeywordDefinition","FuncKeywordDefinition","Vocabulary","Schema","SchemaObject","AnySchemaObject","AsyncSchema","AnySchema","ValidateFunction","AsyncValidateFunction","AnyValidateFunction","ErrorObject","ErrorNoParams","SchemaCxt","SchemaObjCxt","Plugin","Opts","Ajv","KeywordCxt","DefinedError","JSONType","JSONSchemaType","JTDSchemaType","SomeJTDSchemaType","JTDDataType","_","str","stringify","nil","Name","Code","CodeGen","CodeGenOptions","AddedKeywordDefinition","AddedFormat","RegExpEngine","UriResolver","ValidationError","MissingRefError","ValidationRules","SchemaEnv","ValueScope","Options","CurrentOptions","DeprecatedOptions","Logger","Promise","CodeOptions","InstanceCodeOptions","RequiredInstanceOptions","K","NonNullable","InstanceOptions","T","N","Set","RegExp","separator","dataVar","ErrorsTextOptions","default","AnySchema","AnySchemaObject","UriResolver","Ajv","URIComponent","LocalRefs","inlineRef","getFullPath","_getFullPath","normalizeId","resolveUrl","getSchemaRefs","AnySchema","AnySchemaObject","AnyValidateFunction","EvaluatedProperties","EvaluatedItems","Ajv","InstanceOptions","CodeGen","Name","Code","ValueScopeName","LocalRefs","JSONType","SchemaRefs","SchemaEnv","SchemaCxt","Set","SchemaObjCxt","SchemaEnvArgs","compileSchema","resolveRef","getCompilingSchema","resolveSchema","URIComponent","CodeGen","Code","Name","ScopeValueSets","ValueScopeName","SchemaEnv","SchemaCxt","SchemaObjCxt","JSONType","KeywordCxt","Ajv","_SchemaObject","SchemaObject","AsyncSchema","AnySchemaObject","Schema","AnySchema","SchemaMap","SourceCode","DataValidationCxt","T","Record","ValidateFunction","ErrorObject","Evaluated","JTDParser","EvaluatedPropertieLine truncated
@@ -0,0 +1 @@
module.exports={A:{A:{"1":"B","2":"_z"},B:{"1":"_J"},C:{"1":"_S"},D:{"1":"_NK","2":"_KC"},E:{"2":"_KI","194":"_bE"},F:{"1":"_a","2":"_T"},G:{"2":"_rJ","194":"_TD"},H:{"2":"1D"},I:{"1":"J _X","2":"fC _oK"},J:{"2":"_B"},K:{"1":"H","2":"_D"},L:{"1":"I"},M:{"1":"YC"},N:{"1":"B","2":"A"},O:{"1":"bC"},P:{"1":"_F"},Q:{"1":"JE"},R:{"1":"KE"},S:{"1":"_C"}},B:5,C:"Resource Hints: prefetch",D:true};
@@ -0,0 +1,3 @@
# `@rolldown/binding-linux-x64-gnu`
This is the **x86_64-unknown-linux-gnu** binary for `@rolldown/binding`
@@ -0,0 +1,121 @@
'use strict'
const { InvalidArgumentError, SocketError } = require('../core/errors')
const { AsyncResource } = require('node:async_hooks')
const assert = require('node:assert')
const util = require('../core/util')
const { kHTTP2Stream } = require('../core/symbols')
const { addSignal, removeSignal } = require('./abort-signal')
class UpgradeHandler extends AsyncResource {
constructor (opts, callback) {
if (!opts || typeof opts !== 'object') {
throw new InvalidArgumentError('invalid opts')
}
if (typeof callback !== 'function') {
throw new InvalidArgumentError('invalid callback')
}
const { signal, opaque, responseHeaders } = opts
if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
}
super('UNDICI_UPGRADE')
this.responseHeaders = responseHeaders || null
this.opaque = opaque || null
this.callback = callback
this.abort = null
this.context = null
addSignal(this, signal)
}
onRequestStart (controller, context) {
if (this.reason) {
controller.abort(this.reason)
return
}
assert(this.callback)
this.abort = (reason) => controller.abort(reason)
this.context = context
}
onResponseStart () {
throw new SocketError('bad upgrade', null)
}
onRequestUpgrade (controller, statusCode, headers, socket) {
const expectedStatusCode = socket[kHTTP2Stream] === true ? 200 : 101
if (statusCode !== expectedStatusCode) {
const socketInfo = socket[kHTTP2Stream] === true ? null : util.getSocketInfo(socket)
controller.abort(new SocketError('bad upgrade', socketInfo))
return
}
const { callback, opaque, context } = this
removeSignal(this)
this.callback = null
const rawHeaders = controller?.rawHeaders
const responseHeaders = this.responseHeaders === 'raw'
? util.parseRawHeaders(rawHeaders)
: headers
this.runInAsyncScope(callback, null, null, {
headers: responseHeaders,
socket,
opaque,
context
})
}
onResponseError (_controller, err) {
const { callback, opaque } = this
removeSignal(this)
if (callback) {
this.callback = null
queueMicrotask(() => {
this.runInAsyncScope(callback, null, err, { opaque })
})
}
}
}
function upgrade (opts, callback) {
if (callback === undefined) {
return new Promise((resolve, reject) => {
upgrade.call(this, opts, (err, data) => {
return err ? reject(err) : resolve(data)
})
})
}
try {
const upgradeHandler = new UpgradeHandler(opts, callback)
const upgradeOpts = {
...opts,
method: opts.method || 'GET',
upgrade: opts.protocol || 'Websocket'
}
this.dispatch(upgradeOpts, upgradeHandler)
} catch (err) {
if (typeof callback !== 'function') {
throw err
}
const opaque = opts?.opaque
queueMicrotask(() => callback(err, { opaque }))
}
}
module.exports = upgrade
@@ -0,0 +1,42 @@
{
"name": "@tailwindcss/vite",
"version": "4.2.2",
"description": "A utility-first CSS framework for rapidly building custom user interfaces.",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/tailwindlabs/tailwindcss.git",
"directory": "packages/@tailwindcss-vite"
},
"bugs": "https://github.com/tailwindlabs/tailwindcss/issues",
"homepage": "https://tailwindcss.com",
"files": [
"dist/"
],
"publishConfig": {
"provenance": true,
"access": "public"
},
"exports": {
".": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
}
},
"dependencies": {
"@tailwindcss/node": "4.2.2",
"@tailwindcss/oxide": "4.2.2",
"tailwindcss": "4.2.2"
},
"devDependencies": {
"@types/node": "^20.19.0",
"vite": "^8.0.0"
},
"peerDependencies": {
"vite": "^5.2.0 || ^6 || ^7 || ^8"
},
"scripts": {
"build": "tsup-node",
"dev": "pnpm run build -- --watch"
}
}
@@ -0,0 +1,27 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
const stringSchema = z.string();
test("safeparse fail", () => {
const safe = stringSchema.safeParse(12);
expect(safe.success).toEqual(false);
expect(safe.error).toBeInstanceOf(z.ZodError);
});
test("safeparse pass", () => {
const safe = stringSchema.safeParse("12");
expect(safe.success).toEqual(true);
expect(safe.data).toEqual("12");
});
test("safeparse unexpected error", () => {
expect(() =>
stringSchema
.refine((data) => {
throw new Error(data);
})
.safeParse("12")
).toThrow();
});
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=jtd-schema.js.map
@@ -0,0 +1 @@
{"version":3,"file":"asterisk-square.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;"}
@@ -0,0 +1,22 @@
import type {AnySchemaObject} from "../../types"
import type {SchemaObjCxt} from ".."
import type {JSONType, RuleGroup, Rule} from "../rules"
export function schemaHasRulesForType(
{schema, self}: SchemaObjCxt,
type: JSONType
): boolean | undefined {
const group = self.RULES.types[type]
return group && group !== true && shouldUseGroup(schema, group)
}
export function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean {
return group.rules.some((rule) => shouldUseRule(schema, rule))
}
export function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined {
return (
schema[rule.keyword] !== undefined ||
rule.definition.implements?.some((kwd) => schema[kwd] !== undefined)
)
}
@@ -0,0 +1,113 @@
import * as util from "../core/util.js";
const error = () => {
const Sizable = {
string: { unit: "teikn", verb: "å ha" },
file: { unit: "bytes", verb: "å ha" },
array: { unit: "element", verb: "å innehalde" },
set: { unit: "element", verb: "å innehalde" },
map: { unit: "element", verb: "å innehalde" },
};
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-varigheit",
ipv4: "IPv4-adresse",
ipv6: "IPv6-adresse",
mac: "MAC-adresse",
cidrv4: "IPv4-spekter",
cidrv6: "IPv6-spekter",
base64: "base64-enkoda streng",
base64url: "base64url-enkoda 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: "tal",
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: forventa instanceof ${issue.expected}, fekk ${received}`;
}
return `Ugyldig input: forventa ${expected}, fekk ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Ugyldig verdi: forventa ${util.stringifyPrimitive(issue.values[0])}`;
return `Ugyldig val: forventa eitt av ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `For stor(t): forventa ${issue.origin ?? "value"} til å ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? "element"}`;
return `For stor(t): forventa ${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): forventa ${issue.origin} til å ha ${adj}${issue.minimum.toString()} ${sizing.unit}`;
}
return `For lite(n): forventa ${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å slutte med "${_issue.suffix}"`;
if (_issue.format === "includes")
return `Ugyldig streng: må innehalde "${_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 tal: må vere eit multiplum av ${issue.divisor}`;
case "unrecognized_keys":
return `${issue.keys.length > 1 ? "Ukjende nøklar" : "Ukjend 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,4 @@
const MotionGlobalConfig = {};
export { MotionGlobalConfig };
//# sourceMappingURL=global-config.mjs.map
@@ -0,0 +1,20 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const ServerOff = createLucideIcon("ServerOff", [
["path", { d: "M7 2h13a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-5", key: "bt2siv" }],
["path", { d: "M10 10 2.5 2.5C2 2 2 2.5 2 5v3a2 2 0 0 0 2 2h6z", key: "1hjrv1" }],
["path", { d: "M22 17v-1a2 2 0 0 0-2-2h-1", key: "1iynyr" }],
["path", { d: "M4 14a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16.5l1-.5.5.5-8-8H4z", key: "161ggg" }],
["path", { d: "M6 18h.01", key: "uhywen" }],
["path", { d: "m2 2 20 20", key: "1ooewy" }]
]);
export { ServerOff as default };
//# sourceMappingURL=server-off.js.map
@@ -0,0 +1,391 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/v4";
const args1 = z.tuple([z.string()]);
const returns1 = z.number();
const func1 = z.function({
input: args1,
output: returns1,
});
test("function parsing", () => {
const parsed = func1.implement((arg: any) => arg.length);
const result = parsed("asdf");
expect(result).toBe(4);
});
test("parsed function fail 1", () => {
// @ts-expect-error
const parsed = func1.implement((x: string) => x);
expect(() => parsed("asdf")).toThrow();
});
test("parsed function fail 2", () => {
// @ts-expect-error
const parsed = func1.implement((x: string) => x);
expect(() => parsed(13 as any)).toThrow();
});
test("function inference 1", () => {
type func1 = (typeof func1)["_input"];
expectTypeOf<func1>().toEqualTypeOf<(k: string) => number>();
});
test("method parsing", () => {
const methodObject = z.object({
property: z.number(),
method: z
.function()
.input(z.tuple([z.string()]))
.output(z.number()),
});
const methodInstance = {
property: 3,
method: function (s: string) {
return s.length + this.property;
},
};
const parsed = methodObject.parse(methodInstance);
expect(parsed.method("length=8")).toBe(11); // 8 length + 3 property
});
test("async method parsing", async () => {
const methodObject = z.object({
property: z.number(),
method: z.function().input([z.string()]).output(z.promise(z.number())),
});
const methodInstance = {
property: 3,
method: async function (s: string) {
return s.length + this.property;
},
};
const parsed = methodObject.parse(methodInstance);
expect(await parsed.method("length=8")).toBe(11); // 8 length + 3 property
});
test("args method", () => {
const t1 = z.function();
type t1 = (typeof t1)["_input"];
expectTypeOf<t1>().toEqualTypeOf<(...args_1: never[]) => unknown>();
t1._input;
const t2args = z.tuple([z.string()], z.unknown());
const t2 = t1.input(t2args);
type t2 = (typeof t2)["_input"];
expectTypeOf<t2>().toEqualTypeOf<(arg: string, ...args_1: unknown[]) => unknown>();
const t3 = t2.output(z.boolean());
type t3 = (typeof t3)["_input"];
expectTypeOf<t3>().toEqualTypeOf<(arg: string, ...args_1: unknown[]) => boolean>();
});
// test("custom args", () => {
// const fn = z.function().implement((_a: string, _b: number) => {
// return new Date();
// });
// expectTypeOf(fn).toEqualTypeOf<(a: string, b: number) => Date>();
// });
const args2 = z.tuple([
z.object({
f1: z.number(),
f2: z.string().nullable(),
f3: z.array(z.boolean().optional()).optional(),
}),
]);
const returns2 = z.union([z.string(), z.number()]);
const func2 = z.function({
input: args2,
output: returns2,
});
test("function inference 2", () => {
type func2 = (typeof func2)["_input"];
expectTypeOf<func2>().toEqualTypeOf<
(arg: {
f3?: (boolean | undefined)[] | undefined;
f1: number;
f2: string | null;
}) => string | number
>();
});
test("valid function run", () => {
const validFunc2Instance = func2.implement((_x) => {
_x.f2;
_x.f3![0];
return "adf" as any;
});
validFunc2Instance({
f1: 21,
f2: "asdf",
f3: [true, false],
});
});
const args3 = [
z.object({
f1: z.number(),
f2: z.string().nullable(),
f3: z.array(z.boolean().optional()).optional(),
}),
] as const;
const returns3 = z.union([z.string(), z.number()]);
const func3 = z.function({
input: args3,
output: returns3,
});
test("function inference 3", () => {
type func3 = (typeof func3)["_input"];
expectTypeOf<func3>().toEqualTypeOf<
(arg: {
f3?: (boolean | undefined)[] | undefined;
f1: number;
f2: string | null;
}) => string | number
>();
});
test("valid function run", () => {
const validFunc3Instance = func3.implement((_x) => {
_x.f2;
_x.f3![0];
return "adf" as any;
});
validFunc3Instance({
f1: 21,
f2: "asdf",
f3: [true, false],
});
});
test("input validation error", () => {
const schema = z.function({
input: z.tuple([z.string()]),
output: z.void(),
});
const fn = schema.implement(() => 1234 as any);
// @ts-expect-error
const checker = () => fn();
try {
checker();
} catch (e: any) {
expect(e.issues).toMatchInlineSnapshot(`
[
{
"code": "too_small",
"inclusive": true,
"message": "Too small: expected array to have >=1 items",
"minimum": 1,
"origin": "array",
"path": [],
},
]
`);
}
});
test("array inputs", () => {
const a = z.function({
input: [
z.object({
name: z.string(),
age: z.number().int(),
}),
],
output: z.string(),
});
a.implement((args) => {
return `${args.age}`;
});
const b = z.function({
input: [
z.object({
name: z.string(),
age: z.number().int(),
}),
],
});
b.implement((args) => {
return `${args.age}`;
});
});
test("output validation error", () => {
const schema = z.function({
input: z.tuple([]),
output: z.string(),
});
const fn = schema.implement(() => 1234 as any);
try {
fn();
} catch (e: any) {
expect(e.issues).toMatchInlineSnapshot(`
[
{
"code": "invalid_type",
"expected": "string",
"message": "Invalid input: expected string, received number",
"path": [],
},
]
`);
}
});
test("function with async refinements", async () => {
const schema = z
.function()
.input([z.string().refine(async (val) => val.length > 10)])
.output(z.promise(z.number().refine(async (val) => val > 10)));
const func = schema.implementAsync(async (val) => {
return val.length;
});
const results = [];
try {
await func("asdfasdf");
results.push("success");
} catch (_) {
results.push("fail");
}
try {
await func("asdflkjasdflkjsf");
results.push("success");
} catch (_) {
results.push("fail");
}
expect(results).toEqual(["fail", "success"]);
});
test("implement async with transforms", async () => {
const typeGuard = (data: string): data is "1234" => data === "1234";
const codeSchema = z.string().transform((data, ctx) => {
if (typeGuard(data)) {
return data;
} else {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Invalid code",
});
return z.NEVER;
}
});
const inputSchema = z.object({
code: codeSchema,
});
const outputSchema = z.object({
data: z.array(z.string()).default([]),
});
const fnImplementation = async (data: z.infer<typeof inputSchema>): Promise<z.infer<typeof outputSchema>> => {
return {
data: [data.code],
};
};
const schema = z.function().input([inputSchema]).output(outputSchema);
const func = schema.implementAsync(fnImplementation);
type TheInterface = {
myFunction: (data: z.infer<typeof inputSchema>) => Promise<z.infer<typeof outputSchema>>;
};
const theImplementation: TheInterface = {
myFunction: func,
};
const results = [];
try {
await theImplementation.myFunction({
code: "1234",
});
results.push("success");
} catch (_) {
results.push("fail");
}
try {
await func({ data: "asdflkjasdflkjsf" } as any);
results.push("success");
} catch (_) {
results.push("fail");
}
expect(results).toEqual(["success", "fail"]);
});
test("non async function with async refinements should fail", async () => {
const func = z
.function()
.input([z.string().refine(async (val) => val.length > 10)])
.output(z.number().refine(async (val) => val > 10))
.implement((val) => {
return val.length;
});
const results = [];
try {
await func("asdasdfasdffasdf");
results.push("success");
} catch (_) {
results.push("fail");
}
expect(results).toEqual(["fail"]);
});
test("extra parameters with rest", () => {
const maxLength5 = z
.function()
.input([z.string()], z.unknown())
.output(z.boolean())
.implement((str, _arg, _qewr) => {
return str.length <= 5;
});
const filteredList = ["apple", "orange", "pear", "banana", "strawberry"].filter(maxLength5);
expect(filteredList.length).toEqual(2);
});
test("implement exposes the function schema at runtime", () => {
const schema = z.function({ input: [z.string()], output: z.number() });
const fn = schema.implement((s) => s.length);
// Deliberately absent from implement()'s return type: reaching `_zod` takes a cast, so an implemented function never reads as a schema to TypeScript even though it does at runtime.
type HasZod = "_zod" extends keyof typeof fn ? true : false;
expectTypeOf<HasZod>().toEqualTypeOf<false>();
expect((fn as any)._zod).toBe(schema._zod);
expect((fn as any)._zod.def.input).toBe(schema._def.input);
expect((fn as any)._zod.def.output).toBe(schema._def.output);
expect(Object.keys(fn)).toEqual([]);
expect(Object.getOwnPropertyDescriptor(fn, "_zod")).toMatchObject({ enumerable: false, writable: false });
expect(fn("asdf")).toBe(4);
});
test("implementAsync exposes the function schema at runtime", async () => {
const schema = z.function({ input: [z.string()], output: z.promise(z.number()) });
const fn = schema.implementAsync(async (s) => s.length);
expect((fn as any)._zod).toBe(schema._zod);
await expect(fn("asdf")).resolves.toBe(4);
});
test("parsing through a function schema exposes it the same way", () => {
const schema = z.function({ input: [z.string()], output: z.number() });
const { handler } = z.object({ handler: schema }).parse({ handler: (s: string) => s.length });
expect((handler as any)._zod).toBe(schema._zod);
});
@@ -0,0 +1,218 @@
# @jridgewell/remapping
> Remap sequential sourcemaps through transformations to point at the original source code
Remapping allows you to take the sourcemaps generated through transforming your code and "remap"
them to the original source locations. Think "my minified code, transformed with babel and bundled
with webpack", all pointing to the correct location in your original source code.
With remapping, none of your source code transformations need to be aware of the input's sourcemap,
they only need to generate an output sourcemap. This greatly simplifies building custom
transformations (think a find-and-replace).
## Installation
```sh
npm install @jridgewell/remapping
```
## Usage
```typescript
function remapping(
map: SourceMap | SourceMap[],
loader: (file: string, ctx: LoaderContext) => (SourceMap | null | undefined),
options?: { excludeContent: boolean, decodedMappings: boolean }
): SourceMap;
// LoaderContext gives the loader the importing sourcemap, tree depth, the ability to override the
// "source" location (where child sources are resolved relative to, or the location of original
// source), and the ability to override the "content" of an original source for inclusion in the
// output sourcemap.
type LoaderContext = {
readonly importer: string;
readonly depth: number;
source: string;
content: string | null | undefined;
}
```
`remapping` takes the final output sourcemap, and a `loader` function. For every source file pointer
in the sourcemap, the `loader` will be called with the resolved path. If the path itself represents
a transformed file (it has a sourcmap associated with it), then the `loader` should return that
sourcemap. If not, the path will be treated as an original, untransformed source code.
```js
// Babel transformed "helloworld.js" into "transformed.js"
const transformedMap = JSON.stringify({
file: 'transformed.js',
// 1st column of 2nd line of output file translates into the 1st source
// file, line 3, column 2
mappings: ';CAEE',
sources: ['helloworld.js'],
version: 3,
});
// Uglify minified "transformed.js" into "transformed.min.js"
const minifiedTransformedMap = JSON.stringify({
file: 'transformed.min.js',
// 0th column of 1st line of output file translates into the 1st source
// file, line 2, column 1.
mappings: 'AACC',
names: [],
sources: ['transformed.js'],
version: 3,
});
const remapped = remapping(
minifiedTransformedMap,
(file, ctx) => {
// The "transformed.js" file is an transformed file.
if (file === 'transformed.js') {
// The root importer is empty.
console.assert(ctx.importer === '');
// The depth in the sourcemap tree we're currently loading.
// The root `minifiedTransformedMap` is depth 0, and its source children are depth 1, etc.
console.assert(ctx.depth === 1);
return transformedMap;
}
// Loader will be called to load transformedMap's source file pointers as well.
console.assert(file === 'helloworld.js');
// `transformed.js`'s sourcemap points into `helloworld.js`.
console.assert(ctx.importer === 'transformed.js');
// This is a source child of `transformed`, which is a source child of `minifiedTransformedMap`.
console.assert(ctx.depth === 2);
return null;
}
);
console.log(remapped);
// {
// file: 'transpiled.min.js',
// mappings: 'AAEE',
// sources: ['helloworld.js'],
// version: 3,
// };
```
In this example, `loader` will be called twice:
1. `"transformed.js"`, the first source file pointer in the `minifiedTransformedMap`. We return the
associated sourcemap for it (its a transformed file, after all) so that sourcemap locations can
be traced through it into the source files it represents.
2. `"helloworld.js"`, our original, unmodified source code. This file does not have a sourcemap, so
we return `null`.
The `remapped` sourcemap now points from `transformed.min.js` into locations in `helloworld.js`. If
you were to read the `mappings`, it says "0th column of the first line output line points to the 1st
column of the 2nd line of the file `helloworld.js`".
### Multiple transformations of a file
As a convenience, if you have multiple single-source transformations of a file, you may pass an
array of sourcemap files in the order of most-recent transformation sourcemap first. Note that this
changes the `importer` and `depth` of each call to our loader. So our above example could have been
written as:
```js
const remapped = remapping(
[minifiedTransformedMap, transformedMap],
() => null
);
console.log(remapped);
// {
// file: 'transpiled.min.js',
// mappings: 'AAEE',
// sources: ['helloworld.js'],
// version: 3,
// };
```
### Advanced control of the loading graph
#### `source`
The `source` property can overridden to any value to change the location of the current load. Eg,
for an original source file, it allows us to change the location to the original source regardless
of what the sourcemap source entry says. And for transformed files, it allows us to change the
relative resolving location for child sources of the loaded sourcemap.
```js
const remapped = remapping(
minifiedTransformedMap,
(file, ctx) => {
if (file === 'transformed.js') {
// We pretend the transformed.js file actually exists in the 'src/' directory. When the nested
// source files are loaded, they will now be relative to `src/`.
ctx.source = 'src/transformed.js';
return transformedMap;
}
console.assert(file === 'src/helloworld.js');
// We could futher change the source of this original file, eg, to be inside a nested directory
// itself. This will be reflected in the remapped sourcemap.
ctx.source = 'src/nested/transformed.js';
return null;
}
);
console.log(remapped);
// {
// …,
// sources: ['src/nested/helloworld.js'],
// };
```
#### `content`
The `content` property can be overridden when we encounter an original source file. Eg, this allows
you to manually provide the source content of the original file regardless of whether the
`sourcesContent` field is present in the parent sourcemap. It can also be set to `null` to remove
the source content.
```js
const remapped = remapping(
minifiedTransformedMap,
(file, ctx) => {
if (file === 'transformed.js') {
// transformedMap does not include a `sourcesContent` field, so usually the remapped sourcemap
// would not include any `sourcesContent` values.
return transformedMap;
}
console.assert(file === 'helloworld.js');
// We can read the file to provide the source content.
ctx.content = fs.readFileSync(file, 'utf8');
return null;
}
);
console.log(remapped);
// {
// …,
// sourcesContent: [
// 'console.log("Hello world!")',
// ],
// };
```
### Options
#### excludeContent
By default, `excludeContent` is `false`. Passing `{ excludeContent: true }` will exclude the
`sourcesContent` field from the returned sourcemap. This is mainly useful when you want to reduce
the size out the sourcemap.
#### decodedMappings
By default, `decodedMappings` is `false`. Passing `{ decodedMappings: true }` will leave the
`mappings` field in a [decoded state](https://github.com/rich-harris/sourcemap-codec) instead of
encoding into a VLQ string.
@@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExpiringCache = exports.DEFAULT_TSCONFIG_CACHE_DURATION_SECONDS = void 0;
exports.DEFAULT_TSCONFIG_CACHE_DURATION_SECONDS = 30;
const ZERO_HR_TIME = [0, 0];
/**
* A map with key-level expiration.
*/
class ExpiringCache {
#cacheDurationSeconds;
#map = new Map();
constructor(cacheDurationSeconds) {
this.#cacheDurationSeconds = cacheDurationSeconds;
}
clear() {
this.#map.clear();
}
get(key) {
const entry = this.#map.get(key);
if (entry?.value != null) {
if (this.#cacheDurationSeconds === 'Infinity') {
return entry.value;
}
const ageSeconds = process.hrtime(entry.lastSeen)[0];
if (ageSeconds < this.#cacheDurationSeconds) {
// cache hit woo!
return entry.value;
}
// key has expired - clean it up to free up memory
this.#map.delete(key);
}
// no hit :'(
return undefined;
}
set(key, value) {
this.#map.set(key, {
lastSeen: this.#cacheDurationSeconds === 'Infinity'
? // no need to waste time calculating the hrtime in infinity mode as there's no expiry
ZERO_HR_TIME
: process.hrtime(),
value,
});
return this;
}
}
exports.ExpiringCache = ExpiringCache;
@@ -0,0 +1,652 @@
/**
* @fileoverview Rule to enforce concise object methods and properties.
* @author Jamund Ferguson
*/
"use strict";
const OPTIONS = {
always: "always",
never: "never",
methods: "methods",
properties: "properties",
consistent: "consistent",
consistentAsNeeded: "consistent-as-needed",
};
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
const CTOR_PREFIX_REGEX = /[^_$0-9]/u;
const JSDOC_COMMENT_REGEX = /^\s*\*/u;
/**
* Determines if the first character of the name is a capital letter.
* @param {string} name The name of the node to evaluate.
* @returns {boolean} True if the first character of the property name is a capital letter, false if not.
* @private
*/
function isConstructor(name) {
const match = CTOR_PREFIX_REGEX.exec(name);
// Not a constructor if name has no characters apart from '_', '$' and digits e.g. '_', '$$', '_8'
if (!match) {
return false;
}
const firstChar = name.charAt(match.index);
return firstChar === firstChar.toUpperCase();
}
/**
* Determines if the property can have a shorthand form.
* @param {ASTNode} property Property AST node
* @returns {boolean} True if the property can have a shorthand form
* @private
*/
function canHaveShorthand(property) {
return (
property.kind !== "set" &&
property.kind !== "get" &&
property.type !== "SpreadElement" &&
property.type !== "SpreadProperty" &&
property.type !== "ExperimentalSpreadProperty"
);
}
/**
* Checks whether a node is a string literal.
* @param {ASTNode} node Any AST node.
* @returns {boolean} `true` if it is a string literal.
*/
function isStringLiteral(node) {
return node.type === "Literal" && typeof node.value === "string";
}
/**
* Determines if the property is a shorthand or not.
* @param {ASTNode} property Property AST node
* @returns {boolean} True if the property is considered shorthand, false if not.
* @private
*/
function isShorthand(property) {
// property.method is true when `{a(){}}`.
return property.shorthand || property.method;
}
/**
* Determines if the property's key and method or value are named equally.
* @param {ASTNode} property Property AST node
* @returns {boolean} True if the key and value are named equally, false if not.
* @private
*/
function isRedundant(property) {
const value = property.value;
if (value.type === "FunctionExpression") {
return !value.id; // Only anonymous should be shorthand method.
}
if (value.type === "Identifier") {
return astUtils.getStaticPropertyName(property) === value.name;
}
return false;
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description:
"Require or disallow method and property shorthand syntax for object literals",
recommended: false,
frozen: true,
url: "https://eslint.org/docs/latest/rules/object-shorthand",
},
fixable: "code",
schema: {
anyOf: [
{
type: "array",
items: [
{
enum: [
"always",
"methods",
"properties",
"never",
"consistent",
"consistent-as-needed",
],
},
],
minItems: 0,
maxItems: 1,
},
{
type: "array",
items: [
{
enum: ["always", "methods", "properties"],
},
{
type: "object",
properties: {
avoidQuotes: {
type: "boolean",
},
},
additionalProperties: false,
},
],
minItems: 0,
maxItems: 2,
},
{
type: "array",
items: [
{
enum: ["always", "methods"],
},
{
type: "object",
properties: {
ignoreConstructors: {
type: "boolean",
},
methodsIgnorePattern: {
type: "string",
},
avoidQuotes: {
type: "boolean",
},
avoidExplicitReturnArrows: {
type: "boolean",
},
},
additionalProperties: false,
},
],
minItems: 0,
maxItems: 2,
},
],
},
messages: {
expectedAllPropertiesShorthanded:
"Expected shorthand for all properties.",
expectedLiteralMethodLongform:
"Expected longform method syntax for string literal keys.",
expectedPropertyShorthand: "Expected property shorthand.",
expectedPropertyLongform: "Expected longform property syntax.",
expectedMethodShorthand: "Expected method shorthand.",
expectedMethodLongform: "Expected longform method syntax.",
unexpectedMix:
"Unexpected mix of shorthand and non-shorthand properties.",
},
},
create(context) {
const APPLY = context.options[0] || OPTIONS.always;
const APPLY_TO_METHODS =
APPLY === OPTIONS.methods || APPLY === OPTIONS.always;
const APPLY_TO_PROPS =
APPLY === OPTIONS.properties || APPLY === OPTIONS.always;
const APPLY_NEVER = APPLY === OPTIONS.never;
const APPLY_CONSISTENT = APPLY === OPTIONS.consistent;
const APPLY_CONSISTENT_AS_NEEDED = APPLY === OPTIONS.consistentAsNeeded;
const PARAMS = context.options[1] || {};
const IGNORE_CONSTRUCTORS = PARAMS.ignoreConstructors;
const METHODS_IGNORE_PATTERN = PARAMS.methodsIgnorePattern
? new RegExp(PARAMS.methodsIgnorePattern, "u")
: null;
const AVOID_QUOTES = PARAMS.avoidQuotes;
const AVOID_EXPLICIT_RETURN_ARROWS = !!PARAMS.avoidExplicitReturnArrows;
const sourceCode = context.sourceCode;
/**
* Ensures that an object's properties are consistently shorthand, or not shorthand at all.
* @param {ASTNode} node Property AST node
* @param {boolean} checkRedundancy Whether to check longform redundancy
* @returns {void}
*/
function checkConsistency(node, checkRedundancy) {
// We are excluding getters/setters and spread properties as they are considered neither longform nor shorthand.
const properties = node.properties.filter(canHaveShorthand);
// Do we still have properties left after filtering the getters and setters?
if (properties.length > 0) {
const shorthandProperties = properties.filter(isShorthand);
/*
* If we do not have an equal number of longform properties as
* shorthand properties, we are using the annotations inconsistently
*/
if (shorthandProperties.length !== properties.length) {
// We have at least 1 shorthand property
if (shorthandProperties.length > 0) {
context.report({ node, messageId: "unexpectedMix" });
} else if (checkRedundancy) {
/*
* If all properties of the object contain a method or value with a name matching it's key,
* all the keys are redundant.
*/
const canAlwaysUseShorthand =
properties.every(isRedundant);
if (canAlwaysUseShorthand) {
context.report({
node,
messageId: "expectedAllPropertiesShorthanded",
});
}
}
}
}
}
/**
* Fixes a FunctionExpression node by making it into a shorthand property.
* @param {SourceCodeFixer} fixer The fixer object
* @param {ASTNode} node A `Property` node that has a `FunctionExpression` or `ArrowFunctionExpression` as its value
* @returns {Object} A fix for this node
*/
function makeFunctionShorthand(fixer, node) {
const firstKeyToken = node.computed
? sourceCode.getFirstToken(node, astUtils.isOpeningBracketToken)
: sourceCode.getFirstToken(node.key);
const lastKeyToken = node.computed
? sourceCode.getFirstTokenBetween(
node.key,
node.value,
astUtils.isClosingBracketToken,
)
: sourceCode.getLastToken(node.key);
const keyText = sourceCode.text.slice(
firstKeyToken.range[0],
lastKeyToken.range[1],
);
let keyPrefix = "";
// key: /* */ () => {}
if (sourceCode.commentsExistBetween(lastKeyToken, node.value)) {
return null;
}
if (node.value.async) {
keyPrefix += "async ";
}
if (node.value.generator) {
keyPrefix += "*";
}
const fixRange = [firstKeyToken.range[0], node.range[1]];
const methodPrefix = keyPrefix + keyText;
if (node.value.type === "FunctionExpression") {
const functionToken = sourceCode
.getTokens(node.value)
.find(
token =>
token.type === "Keyword" &&
token.value === "function",
);
const tokenBeforeParams = node.value.generator
? sourceCode.getTokenAfter(functionToken)
: functionToken;
return fixer.replaceTextRange(
fixRange,
methodPrefix +
sourceCode.text.slice(
tokenBeforeParams.range[1],
node.value.range[1],
),
);
}
const arrowToken = sourceCode.getTokenBefore(
node.value.body,
astUtils.isArrowToken,
);
const fnBody = sourceCode.text.slice(
arrowToken.range[1],
node.value.range[1],
);
// First token should not be `async`
const firstValueToken = sourceCode.getFirstToken(node.value, {
skip: node.value.async ? 1 : 0,
});
const sliceStart = firstValueToken.range[0];
const sliceEnd = sourceCode.getTokenBefore(arrowToken).range[1];
const shouldAddParens =
node.value.params.length === 1 &&
node.value.params[0].range[0] === sliceStart;
const oldParamText = sourceCode.text.slice(sliceStart, sliceEnd);
const newParamText = shouldAddParens
? `(${oldParamText})`
: oldParamText;
return fixer.replaceTextRange(
fixRange,
methodPrefix + newParamText + fnBody,
);
}
/**
* Fixes a FunctionExpression node by making it into a longform property.
* @param {SourceCodeFixer} fixer The fixer object
* @param {ASTNode} node A `Property` node that has a `FunctionExpression` as its value
* @returns {Object} A fix for this node
*/
function makeFunctionLongform(fixer, node) {
const firstKeyToken = node.computed
? sourceCode.getTokens(node).find(token => token.value === "[")
: sourceCode.getFirstToken(node.key);
const lastKeyToken = node.computed
? sourceCode
.getTokensBetween(node.key, node.value)
.find(token => token.value === "]")
: sourceCode.getLastToken(node.key);
const keyText = sourceCode.text.slice(
firstKeyToken.range[0],
lastKeyToken.range[1],
);
let functionHeader = "function";
if (node.value.async) {
functionHeader = `async ${functionHeader}`;
}
if (node.value.generator) {
functionHeader = `${functionHeader}*`;
}
return fixer.replaceTextRange(
[node.range[0], lastKeyToken.range[1]],
`${keyText}: ${functionHeader}`,
);
}
/*
* To determine whether a given arrow function has a lexical identifier (`this`, `arguments`, `super`, or `new.target`),
* create a stack of functions that define these identifiers (i.e. all functions except arrow functions) as the AST is
* traversed. Whenever a new function is encountered, create a new entry on the stack (corresponding to a different lexical
* scope of `this`), and whenever a function is exited, pop that entry off the stack. When an arrow function is entered,
* keep a reference to it on the current stack entry, and remove that reference when the arrow function is exited.
* When a lexical identifier is encountered, mark all the arrow functions on the current stack entry by adding them
* to an `arrowsWithLexicalIdentifiers` set. Any arrow function in that set will not be reported by this rule,
* because converting it into a method would change the value of one of the lexical identifiers.
*/
const lexicalScopeStack = [];
const arrowsWithLexicalIdentifiers = new WeakSet();
const argumentsIdentifiers = new WeakSet();
/**
* Enters a function. This creates a new lexical identifier scope, so a new Set of arrow functions is pushed onto the stack.
* Also, this marks all `arguments` identifiers so that they can be detected later.
* @param {ASTNode} node The node representing the function.
* @returns {void}
*/
function enterFunction(node) {
lexicalScopeStack.unshift(new Set());
sourceCode
.getScope(node)
.variables.filter(variable => variable.name === "arguments")
.forEach(variable => {
variable.references
.map(ref => ref.identifier)
.forEach(identifier =>
argumentsIdentifiers.add(identifier),
);
});
}
/**
* Exits a function. This pops the current set of arrow functions off the lexical scope stack.
* @returns {void}
*/
function exitFunction() {
lexicalScopeStack.shift();
}
/**
* Marks the current function as having a lexical keyword. This implies that all arrow functions
* in the current lexical scope contain a reference to this lexical keyword.
* @returns {void}
*/
function reportLexicalIdentifier() {
lexicalScopeStack[0].forEach(arrowFunction =>
arrowsWithLexicalIdentifiers.add(arrowFunction),
);
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
return {
Program: enterFunction,
FunctionDeclaration: enterFunction,
FunctionExpression: enterFunction,
"Program:exit": exitFunction,
"FunctionDeclaration:exit": exitFunction,
"FunctionExpression:exit": exitFunction,
ArrowFunctionExpression(node) {
lexicalScopeStack[0].add(node);
},
"ArrowFunctionExpression:exit"(node) {
lexicalScopeStack[0].delete(node);
},
ThisExpression: reportLexicalIdentifier,
Super: reportLexicalIdentifier,
MetaProperty(node) {
if (
node.meta.name === "new" &&
node.property.name === "target"
) {
reportLexicalIdentifier();
}
},
Identifier(node) {
if (argumentsIdentifiers.has(node)) {
reportLexicalIdentifier();
}
},
ObjectExpression(node) {
if (APPLY_CONSISTENT) {
checkConsistency(node, false);
} else if (APPLY_CONSISTENT_AS_NEEDED) {
checkConsistency(node, true);
}
},
"Property:exit"(node) {
const isConciseProperty = node.method || node.shorthand;
// Ignore destructuring assignment
if (node.parent.type === "ObjectPattern") {
return;
}
// getters and setters are ignored
if (node.kind === "get" || node.kind === "set") {
return;
}
// only computed methods can fail the following checks
if (
node.computed &&
node.value.type !== "FunctionExpression" &&
node.value.type !== "ArrowFunctionExpression"
) {
return;
}
//--------------------------------------------------------------
// Checks for property/method shorthand.
if (isConciseProperty) {
if (
node.method &&
(APPLY_NEVER ||
(AVOID_QUOTES && isStringLiteral(node.key)))
) {
const messageId = APPLY_NEVER
? "expectedMethodLongform"
: "expectedLiteralMethodLongform";
// { x() {} } should be written as { x: function() {} }
context.report({
node,
messageId,
fix: fixer => makeFunctionLongform(fixer, node),
});
} else if (APPLY_NEVER) {
// { x } should be written as { x: x }
context.report({
node,
messageId: "expectedPropertyLongform",
fix: fixer =>
fixer.insertTextAfter(
node.key,
`: ${node.key.name}`,
),
});
}
} else if (
APPLY_TO_METHODS &&
!node.value.id &&
(node.value.type === "FunctionExpression" ||
node.value.type === "ArrowFunctionExpression")
) {
if (
IGNORE_CONSTRUCTORS &&
node.key.type === "Identifier" &&
isConstructor(node.key.name)
) {
return;
}
if (METHODS_IGNORE_PATTERN) {
const propertyName =
astUtils.getStaticPropertyName(node);
if (
propertyName !== null &&
METHODS_IGNORE_PATTERN.test(propertyName)
) {
return;
}
}
if (AVOID_QUOTES && isStringLiteral(node.key)) {
return;
}
// {[x]: function(){}} should be written as {[x]() {}}
if (
node.value.type === "FunctionExpression" ||
(node.value.type === "ArrowFunctionExpression" &&
node.value.body.type === "BlockStatement" &&
AVOID_EXPLICIT_RETURN_ARROWS &&
!arrowsWithLexicalIdentifiers.has(node.value))
) {
context.report({
node,
messageId: "expectedMethodShorthand",
fix: fixer => makeFunctionShorthand(fixer, node),
});
}
} else if (
node.value.type === "Identifier" &&
node.key.name === node.value.name &&
APPLY_TO_PROPS
) {
// Skip if there are JSDoc comments inside the property (e.g., JSDoc type annotations)
const comments = sourceCode.getCommentsInside(node);
if (
comments.some(
comment =>
comment.type === "Block" &&
JSDOC_COMMENT_REGEX.test(comment.value) &&
comment.value.includes("@type"),
)
) {
return;
}
// {x: x} should be written as {x}
context.report({
node,
messageId: "expectedPropertyShorthand",
fix(fixer) {
// x: /* */ x
// x: (/* */ x)
if (sourceCode.getCommentsInside(node).length > 0) {
return null;
}
return fixer.replaceText(node, node.value.name);
},
});
} else if (
node.value.type === "Identifier" &&
node.key.type === "Literal" &&
node.key.value === node.value.name &&
APPLY_TO_PROPS
) {
if (AVOID_QUOTES) {
return;
}
const comments = sourceCode.getCommentsInside(node);
if (
comments.some(
comment =>
comment.type === "Block" &&
comment.value.startsWith("*") &&
comment.value.includes("@type"),
)
) {
return;
}
// {"x": x} should be written as {x}
context.report({
node,
messageId: "expectedPropertyShorthand",
fix(fixer) {
// "x": /* */ x
// "x": (/* */ x)
if (sourceCode.getCommentsInside(node).length > 0) {
return null;
}
return fixer.replaceText(node, node.value.name);
},
});
}
},
};
},
};
@@ -0,0 +1 @@
{"version":3,"file":"index.mjs","names":["messageExtra: MessageExtraInfo","resolve!: (response: Response) => void","reject!: (error: Error) => void","controller!: ReadableStreamDefaultController<Uint8Array>","error: { code: number; message: string; data?: string }","streamController: ReadableStreamDefaultController<Uint8Array>","keepAliveTimer: ReturnType<typeof setInterval> | undefined","headers: Record<string, string>","streamId: string | undefined","replayedStreamId: string | undefined","messages: JSONRPCMessage[]","scopeChallengeResponse: Response | undefined","closeSSEStream: (() => void) | undefined","closeStandaloneSSEStream: (() => void) | undefined","eventId: string | undefined","body: unknown","bodyText: string","bus: ServerEventBus","legacyHandler: LegacyHttpHandler | undefined","hostname: string","hostname: string","scheme: string","cryptoKey: ReturnType<typeof subtle.importKey> | undefined","envelope: { p: T; exp: number; b?: string }","macBytes: Uint8Array<ArrayBuffer>","_defaultValidator: jsonSchemaValidator | undefined","coreFromJsonSchema"],"sources":["../src/server/perRequestTransport.ts","../src/server/invoke.ts","../src/server/requestBody.ts","../src/server/streamableHttp.ts","../src/server/createMcpHandler.ts","../src/server/middleware/hostHeaderValidation.ts","../src/server/middleware/originValidation.ts","../src/server/requestStateCodec.ts","../src/fromJsonSchema.ts"],"sourcesContent":["/**\n * A single-exchange, per-request HTTP server transport for modern-era\n * (protocol revision 2026-07-28) serving.\n *\n * One transport instance serves exactly one already-classified inbound\n * JSON-RPC message and produces exactly one HTTP `Response`:\n *\n * - a `202` with no body for notifications,\n * - a single JSON body for requests whose handler produces no streamed\n * output, or\n * - a lazily-opened SSE stream when the handler emits related messages\n * (notifications or server-to-client requests) before its result — the\n * stream carries those messages and finally the terminal result, then\n * closes.\n *\n * The transport is constructed already-classified: the entry parses and\n * classifies the request body exactly once and hands the classification in via\n * the constructor; the transport attaches it (together with the original\n * request and any caller-provided auth info) to every message it delivers, and\n * the protocol layer validates it against the serving instance's negotiated\n * era. `authInfo` is strictly pass-through — it is never derived from the\n * inbound request's headers here.\n *\n * Deliberately NOT carried over from the session-oriented streamable HTTP\n * transport: session ids and session headers, resumability (event ids,\n * priming events, `Last-Event-ID` replay, retry hints), the standalone GET\n * stream, and request-header validation (which belongs to middleware). The\n * exchange is single-use; serving another request requires a new transport\n * (and, in the per-request serving model, a fresh server instance).\n *\n * Consumers wiring this transport into a custom entry (instead of\n * `createMcpHandler`) inherit the spec's per-error HTTP mandate with it: a\n * terminal `MissingRequiredClientCapabilityError` (-32021) MUST answer 400,\n * which this transport applies whenever the response is still uncommitted.\n * A custom entry must also reject POSTs whose Content-Type media type is not\n * `application/json` (415) before parsing the body — use `isJsonContentType`\n * from the package root; this transport never sees the HTTP headers, so it\n * cannot perform that validation itself.\n */\nimport type {\n AuthInfo,\n JSONRPCMessage,\n JSONRPCNotification,\n JSONRPCRequest,\n MessageClassification,\n MessageExtraInfo,\n RequestId,\n Transport,\n TransportSendOptions\n} from '@modelcontextprotocol/core-internal';\nimport {\n isJSONRPCErrorResponse,\n isJSONRPCRequest,\n isJSONRPCResultResponse,\n LADDER_ERROR_HTTP_STATUS,\n ProtocolErrorCode,\n SdkError,\n SdkErrorCode\n} from '@modelcontextprotocol/core-internal';\n\nimport { armSseKeepAlive, DEFAULT_SSE_KEEP_ALIVE_MS } from './sseKeepAlive';\n\n/**\n * How the transport shapes its HTTP response for a request:\n *\n * - `auto` (default): answer with a single JSON body unless the handler emits\n * a related message before its result, in which case the response upgrades\n * to an SSE stream.\n * - `sse`: always answer handler output over an SSE stream. The stream opens\n * once the request has passed the pre-dispatch validation gates, so ladder\n * rejections keep their mapped HTTP status instead of being framed onto a\n * 200 stream.\n * - `json`: never stream; related messages other than the terminal response\n * are dropped.\n */\nexport type PerRequestResponseMode = 'auto' | 'sse' | 'json';\n\n/** Constructor options for {@linkcode PerRequestHTTPServerTransport}. */\nexport interface PerRequestHTTPServerTransportOptions {\n /**Line truncated
@@ -0,0 +1,15 @@
function decompress(encodedString) {
const decompressedArray = encodedString.split(/([A-Z])/g);
const decompressedData = [];
let last = "";
let i;
for (i = 1; i < decompressedArray.length; i += 2) {
last = last.slice(0, decompressedArray[i].charCodeAt(0) - 65) + decompressedArray[i + 1];
decompressedData.push(last);
}
return decompressedData;
}
export {
decompress as default
};
//# sourceMappingURL=decompress.mjs.map
@@ -0,0 +1,81 @@
// Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134
const decodeMap = new Map([
[0, 65_533],
// C1 Unicode control character reference replacements
[128, 8364],
[130, 8218],
[131, 402],
[132, 8222],
[133, 8230],
[134, 8224],
[135, 8225],
[136, 710],
[137, 8240],
[138, 352],
[139, 8249],
[140, 338],
[142, 381],
[145, 8216],
[146, 8217],
[147, 8220],
[148, 8221],
[149, 8226],
[150, 8211],
[151, 8212],
[152, 732],
[153, 8482],
[154, 353],
[155, 8250],
[156, 339],
[158, 382],
[159, 376],
]);
/**
* Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point.
*/
export const fromCodePoint: (...codePoints: number[]) => string =
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, n/no-unsupported-features/es-builtins
String.fromCodePoint ??
function (codePoint: number): string {
let output = "";
if (codePoint > 0xff_ff) {
codePoint -= 0x1_00_00;
output += String.fromCharCode(
((codePoint >>> 10) & 0x3_ff) | 0xd8_00,
);
codePoint = 0xdc_00 | (codePoint & 0x3_ff);
}
output += String.fromCharCode(codePoint);
return output;
};
/**
* Replace the given code point with a replacement character if it is a
* surrogate or is outside the valid range. Otherwise return the code
* point unchanged.
*/
export function replaceCodePoint(codePoint: number): number {
if (
(codePoint >= 0xd8_00 && codePoint <= 0xdf_ff) ||
codePoint > 0x10_ff_ff
) {
return 0xff_fd;
}
return decodeMap.get(codePoint) ?? codePoint;
}
/**
* Replace the code point if relevant, then convert it to a string.
*
* @deprecated Use `fromCodePoint(replaceCodePoint(codePoint))` instead.
* @param codePoint The code point to decode.
* @returns The decoded code point.
*/
export function decodeCodePoint(codePoint: number): string {
return fromCodePoint(replaceCodePoint(codePoint));
}
@@ -0,0 +1,117 @@
"use strict";
/* eslint consistent-return: 0 -- no default case */
const messages = {
env: `
A config object is using the "env" key, which is not supported in flat config system.
Flat config uses "languageOptions.globals" to define global variables for your files.
Please see the following page for information on how to convert your config object into the correct format:
https://eslint.org/docs/latest/use/configure/migration-guide#configure-language-options
If you're not using "env" directly (it may be coming from a plugin), please see the following:
https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config
`,
extends: `
A config object is using the "extends" key, which is not supported in flat config system.
Instead of "extends", you can include config objects that you'd like to extend from directly in the flat config array.
If you're using "extends" in your config file, please see the following:
https://eslint.org/docs/latest/use/configure/migration-guide#predefined-and-shareable-configs
If you're not using "extends" directly (it may be coming from a plugin), please see the following:
https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config
`,
globals: `
A config object is using the "globals" key, which is not supported in flat config system.
Flat config uses "languageOptions.globals" to define global variables for your files.
Please see the following page for information on how to convert your config object into the correct format:
https://eslint.org/docs/latest/use/configure/migration-guide#configure-language-options
If you're not using "globals" directly (it may be coming from a plugin), please see the following:
https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config
`,
ignorePatterns: `
A config object is using the "ignorePatterns" key, which is not supported in flat config system.
Flat config uses "ignores" to specify files to ignore.
Please see the following page for information on how to convert your config object into the correct format:
https://eslint.org/docs/latest/use/configure/migration-guide#ignore-files
If you're not using "ignorePatterns" directly (it may be coming from a plugin), please see the following:
https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config
`,
noInlineConfig: `
A config object is using the "noInlineConfig" key, which is not supported in flat config system.
Flat config uses "linterOptions.noInlineConfig" to specify files to ignore.
Please see the following page for information on how to convert your config object into the correct format:
https://eslint.org/docs/latest/use/configure/migration-guide#linter-options
`,
overrides: `
A config object is using the "overrides" key, which is not supported in flat config system.
Flat config is an array that acts like the eslintrc "overrides" array.
Please see the following page for information on how to convert your config object into the correct format:
https://eslint.org/docs/latest/use/configure/migration-guide#glob-based-configs
If you're not using "overrides" directly (it may be coming from a plugin), please see the following:
https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config
`,
parser: `
A config object is using the "parser" key, which is not supported in flat config system.
Flat config uses "languageOptions.parser" to override the default parser.
Please see the following page for information on how to convert your config object into the correct format:
https://eslint.org/docs/latest/use/configure/migration-guide#custom-parsers
If you're not using "parser" directly (it may be coming from a plugin), please see the following:
https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config
`,
parserOptions: `
A config object is using the "parserOptions" key, which is not supported in flat config system.
Flat config uses "languageOptions.parserOptions" to specify parser options.
Please see the following page for information on how to convert your config object into the correct format:
https://eslint.org/docs/latest/use/configure/migration-guide#configure-language-options
If you're not using "parserOptions" directly (it may be coming from a plugin), please see the following:
https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config
`,
reportUnusedDisableDirectives: `
A config object is using the "reportUnusedDisableDirectives" key, which is not supported in flat config system.
Flat config uses "linterOptions.reportUnusedDisableDirectives" to specify files to ignore.
Please see the following page for information on how to convert your config object into the correct format:
https://eslint.org/docs/latest/use/configure/migration-guide#linter-options
`,
root: `
A config object is using the "root" key, which is not supported in flat config system.
Flat configs always act as if they are the root config file, so this key can be safely removed.
`,
};
module.exports = function ({ key }) {
return messages[key].trim();
};
@@ -0,0 +1,5 @@
/** Default interval between SSE keep-alive comment frames. */
export declare const DEFAULT_SSE_KEEP_ALIVE_MS = 15000;
/** Arms an unref'd timer, or disables keep-alive for invalid delays. */
export declare function armSseKeepAlive(intervalMs: number, onTick: () => void): ReturnType<typeof setInterval> | undefined;
//# sourceMappingURL=sseKeepAlive.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"arrow-up-narrow-wide.js","sources":["../../../src/icons/arrow-up-narrow-wide.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name ArrowUpNarrowWide\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJtMyA4IDQtNCA0IDQiIC8+CiAgPHBhdGggZD0iTTcgNHYxNiIgLz4KICA8cGF0aCBkPSJNMTEgMTJoNCIgLz4KICA8cGF0aCBkPSJNMTEgMTZoNyIgLz4KICA8cGF0aCBkPSJNMTEgMjBoMTAiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/arrow-up-narrow-wide\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 ArrowUpNarrowWide = createLucideIcon('ArrowUpNarrowWide', [\n ['path', { d: 'm3 8 4-4 4 4', key: '11wl7u' }],\n ['path', { d: 'M7 4v16', key: '1glfcx' }],\n ['path', { d: 'M11 12h4', key: 'q8tih4' }],\n ['path', { d: 'M11 16h7', key: 'uosisv' }],\n ['path', { d: 'M11 20h10', key: 'jvxblo' }],\n]);\n\nexport default ArrowUpNarrowWide;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAoB,iBAAiB,mBAAqB,CAAA,CAAA,CAAA;AAAA,CAAA,CAC9D,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAgB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC7C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,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,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,CAAA;AAAA,CAAA,CACzC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAa,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC5C,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,23 @@
'use strict';
var inspect = require('../');
var Buffer = require('safer-buffer').Buffer;
var holes = ['a', 'b'];
holes[4] = 'e';
holes[6] = 'g';
var obj = {
a: 1,
b: [3, 4, undefined, null],
c: undefined,
d: null,
e: {
regex: /^x/i,
buf: Buffer.from('abc'),
holes: holes
},
now: new Date()
};
obj.self = obj;
console.log(inspect(obj));
@@ -0,0 +1 @@
{"version":3,"file":"minimize.js","sources":["../../../src/icons/minimize.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Minimize\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNOCAzdjNhMiAyIDAgMCAxLTIgMkgzIiAvPgogIDxwYXRoIGQ9Ik0yMSA4aC0zYTIgMiAwIDAgMS0yLTJWMyIgLz4KICA8cGF0aCBkPSJNMyAxNmgzYTIgMiAwIDAgMSAyIDJ2MyIgLz4KICA8cGF0aCBkPSJNMTYgMjF2LTNhMiAyIDAgMCAxIDItMmgzIiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/minimize\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 Minimize = createLucideIcon('Minimize', [\n ['path', { d: 'M8 3v3a2 2 0 0 1-2 2H3', key: 'hohbtr' }],\n ['path', { d: 'M21 8h-3a2 2 0 0 1-2-2V3', key: '5jw1f3' }],\n ['path', { d: 'M3 16h3a2 2 0 0 1 2 2v3', key: '198tvr' }],\n ['path', { d: 'M16 21v-3a2 2 0 0 1 2-2h3', key: 'ph8mxp' }],\n]);\n\nexport default Minimize;\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,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAA0B,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACvD,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAA4B,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACzD,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAA2B,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACxD,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,428 @@
3.0.2 / 2025-11-20
===================
* Fix: update JSDoc to reflect that functions return only `false` or `string`, not `boolean|string`.
* Fix: refined mime-score logic so `.mp4` resolves correctly
* Fix:reflect the current Node.js version supported to ≥ 18 (See 3.0.0 for more details).
3.0.1 / 2025-03-26
===================
* deps: mime-db@1.54.0
3.0.0 / 2024-08-31
===================
* Drop support for node <18
* deps: mime-db@1.53.0
* resolve extension conflicts with mime-score (#119)
* asc -> application/pgp-signature is now application/pgp-keys
* mpp -> application/vnd.ms-project is now application/dash-patch+xml
* ac -> application/vnd.nokia.n-gage.ac+xml is now application/pkix-attr-cert
* bdoc -> application/x-bdoc is now application/bdoc
* wmz -> application/x-msmetafile is now application/x-ms-wmz
* xsl -> application/xslt+xml is now application/xml
* wav -> audio/wave is now audio/wav
* rtf -> text/rtf is now application/rtf
* xml -> text/xml is now application/xml
* mp4 -> video/mp4 is now application/mp4
* mpg4 -> video/mp4 is now application/mp4
2.1.35 / 2022-03-12
===================
* deps: mime-db@1.52.0
- Add extensions from IANA for more `image/*` types
- Add extension `.asc` to `application/pgp-keys`
- Add extensions to various XML types
- Add new upstream MIME types
2.1.34 / 2021-11-08
===================
* deps: mime-db@1.51.0
- Add new upstream MIME types
2.1.33 / 2021-10-01
===================
* deps: mime-db@1.50.0
- Add deprecated iWorks mime types and extensions
- Add new upstream MIME types
2.1.32 / 2021-07-27
===================
* deps: mime-db@1.49.0
- Add extension `.trig` to `application/trig`
- Add new upstream MIME types
2.1.31 / 2021-06-01
===================
* deps: mime-db@1.48.0
- Add extension `.mvt` to `application/vnd.mapbox-vector-tile`
- Add new upstream MIME types
2.1.30 / 2021-04-02
===================
* deps: mime-db@1.47.0
- Add extension `.amr` to `audio/amr`
- Remove ambigious extensions from IANA for `application/*+xml` types
- Update primary extension to `.es` for `application/ecmascript`
2.1.29 / 2021-02-17
===================
* deps: mime-db@1.46.0
- Add extension `.amr` to `audio/amr`
- Add extension `.m4s` to `video/iso.segment`
- Add extension `.opus` to `audio/ogg`
- Add new upstream MIME types
2.1.28 / 2021-01-01
===================
* deps: mime-db@1.45.0
- Add `application/ubjson` with extension `.ubj`
- Add `image/avif` with extension `.avif`
- Add `image/ktx2` with extension `.ktx2`
- Add extension `.dbf` to `application/vnd.dbf`
- Add extension `.rar` to `application/vnd.rar`
- Add extension `.td` to `application/urc-targetdesc+xml`
- Add new upstream MIME types
- Fix extension of `application/vnd.apple.keynote` to be `.key`
2.1.27 / 2020-04-23
===================
* deps: mime-db@1.44.0
- Add charsets from IANA
- Add extension `.cjs` to `application/node`
- Add new upstream MIME types
2.1.26 / 2020-01-05
===================
* deps: mime-db@1.43.0
- Add `application/x-keepass2` with extension `.kdbx`
- Add extension `.mxmf` to `audio/mobile-xmf`
- Add extensions from IANA for `application/*+xml` types
- Add new upstream MIME types
2.1.25 / 2019-11-12
===================
* deps: mime-db@1.42.0
- Add new upstream MIME types
- Add `application/toml` with extension `.toml`
- Add `image/vnd.ms-dds` with extension `.dds`
2.1.24 / 2019-04-20
===================
* deps: mime-db@1.40.0
- Add extensions from IANA for `model/*` types
- Add `text/mdx` with extension `.mdx`
2.1.23 / 2019-04-17
===================
* deps: mime-db@~1.39.0
- Add extensions `.siv` and `.sieve` to `application/sieve`
- Add new upstream MIME types
2.1.22 / 2019-02-14
===================
* deps: mime-db@~1.38.0
- Add extension `.nq` to `application/n-quads`
- Add extension `.nt` to `application/n-triples`
- Add new upstream MIME types
2.1.21 / 2018-10-19
===================
* deps: mime-db@~1.37.0
- Add extensions to HEIC image types
- Add new upstream MIME types
2.1.20 / 2018-08-26
===================
* deps: mime-db@~1.36.0
- Add Apple file extensions from IANA
- Add extensions from IANA for `image/*` types
- Add new upstream MIME types
2.1.19 / 2018-07-17
===================
* deps: mime-db@~1.35.0
- Add extension `.csl` to `application/vnd.citationstyles.style+xml`
- Add extension `.es` to `application/ecmascript`
- Add extension `.owl` to `application/rdf+xml`
- Add new upstream MIME types
- Add UTF-8 as default charset for `text/turtle`
2.1.18 / 2018-02-16
===================
* deps: mime-db@~1.33.0
- Add `application/raml+yaml` with extension `.raml`
- Add `application/wasm` with extension `.wasm`
- Add `text/shex` with extension `.shex`
- Add extensions for JPEG-2000 images
- Add extensions from IANA for `message/*` types
- Add new upstream MIME types
- Update font MIME types
- Update `text/hjson` to registered `application/hjson`
2.1.17 / 2017-09-01
===================
* deps: mime-db@~1.30.0
- Add `application/vnd.ms-outlook`
- Add `application/x-arj`
- Add extension `.mjs` to `application/javascript`
- Add glTF types and extensions
- Add new upstream MIME types
- Add `text/x-org`
- Add VirtualBox MIME types
- Fix `source` records for `video/*` types that are IANA
- Update `font/opentype` to registered `font/otf`
2.1.16 / 2017-07-24
===================
* deps: mime-db@~1.29.0
- Add `application/fido.trusted-apps+json`
- Add extension `.wadl` to `application/vnd.sun.wadl+xml`
- Add extension `.gz` to `application/gzip`
- Add new upstream MIME types
- Update extensions `.md` and `.markdown` to be `text/markdown`
2.1.15 / 2017-03-23
===================
* deps: mime-db@~1.27.0
- Add new mime types
- Add `image/apng`
2.1.14 / 2017-01-14
===================
* deps: mime-db@~1.26.0
- Add new mime types
2.1.13 / 2016-11-18
===================
* deps: mime-db@~1.25.0
- Add new mime types
2.1.12 / 2016-09-18
===================
* deps: mime-db@~1.24.0
- Add new mime types
- Add `audio/mp3`
2.1.11 / 2016-05-01
===================
* deps: mime-db@~1.23.0
- Add new mime types
2.1.10 / 2016-02-15
===================
* deps: mime-db@~1.22.0
- Add new mime types
- Fix extension of `application/dash+xml`
- Update primary extension for `audio/mp4`
2.1.9 / 2016-01-06
==================
* deps: mime-db@~1.21.0
- Add new mime types
2.1.8 / 2015-11-30
==================
* deps: mime-db@~1.20.0
- Add new mime types
2.1.7 / 2015-09-20
==================
* deps: mime-db@~1.19.0
- Add new mime types
2.1.6 / 2015-09-03
==================
* deps: mime-db@~1.18.0
- Add new mime types
2.1.5 / 2015-08-20
==================
* deps: mime-db@~1.17.0
- Add new mime types
2.1.4 / 2015-07-30
==================
* deps: mime-db@~1.16.0
- Add new mime types
2.1.3 / 2015-07-13
==================
* deps: mime-db@~1.15.0
- Add new mime types
2.1.2 / 2015-06-25
==================
* deps: mime-db@~1.14.0
- Add new mime types
2.1.1 / 2015-06-08
==================
* perf: fix deopt during mapping
2.1.0 / 2015-06-07
==================
* Fix incorrectly treating extension-less file name as extension
- i.e. `'path/to/json'` will no longer return `application/json`
* Fix `.charset(type)` to accept parameters
* Fix `.charset(type)` to match case-insensitive
* Improve generation of extension to MIME mapping
* Refactor internals for readability and no argument reassignment
* Prefer `application/*` MIME types from the same source
* Prefer any type over `application/octet-stream`
* deps: mime-db@~1.13.0
- Add nginx as a source
- Add new mime types
2.0.14 / 2015-06-06
===================
* deps: mime-db@~1.12.0
- Add new mime types
2.0.13 / 2015-05-31
===================
* deps: mime-db@~1.11.0
- Add new mime types
2.0.12 / 2015-05-19
===================
* deps: mime-db@~1.10.0
- Add new mime types
2.0.11 / 2015-05-05
===================
* deps: mime-db@~1.9.1
- Add new mime types
2.0.10 / 2015-03-13
===================
* deps: mime-db@~1.8.0
- Add new mime types
2.0.9 / 2015-02-09
==================
* deps: mime-db@~1.7.0
- Add new mime types
- Community extensions ownership transferred from `node-mime`
2.0.8 / 2015-01-29
==================
* deps: mime-db@~1.6.0
- Add new mime types
2.0.7 / 2014-12-30
==================
* deps: mime-db@~1.5.0
- Add new mime types
- Fix various invalid MIME type entries
2.0.6 / 2014-12-30
==================
* deps: mime-db@~1.4.0
- Add new mime types
- Fix various invalid MIME type entries
- Remove example template MIME types
2.0.5 / 2014-12-29
==================
* deps: mime-db@~1.3.1
- Fix missing extensions
2.0.4 / 2014-12-10
==================
* deps: mime-db@~1.3.0
- Add new mime types
2.0.3 / 2014-11-09
==================
* deps: mime-db@~1.2.0
- Add new mime types
2.0.2 / 2014-09-28
==================
* deps: mime-db@~1.1.0
- Add new mime types
- Update charsets
2.0.1 / 2014-09-07
==================
* Support Node.js 0.6
2.0.0 / 2014-09-02
==================
* Use `mime-db`
* Remove `.define()`
1.0.2 / 2014-08-04
==================
* Set charset=utf-8 for `text/javascript`
1.0.1 / 2014-06-24
==================
* Add `text/jsx` type
1.0.0 / 2014-05-12
==================
* Return `false` for unknown types
* Set charset=utf-8 for `application/json`
0.1.0 / 2014-05-02
==================
* Initial release
@@ -0,0 +1,15 @@
export type Options = [
{
allowArgumentsExplicitlyTypedAsAny?: boolean;
allowDirectConstAssertionInArrowFunctions?: boolean;
allowedNames?: string[];
allowHigherOrderFunctions?: boolean;
allowTypedFunctionExpressions?: boolean;
allowOverloadFunctions?: boolean;
}
];
export type MessageIds = 'anyTypedArg' | 'anyTypedArgUnnamed' | 'missingArgType' | 'missingArgTypeUnnamed' | 'missingReturnType';
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<MessageIds, Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
name: string;
};
export default _default;
@@ -0,0 +1 @@
{"version":3,"file":"pyramid.js","sources":["../../../src/icons/pyramid.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Pyramid\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMi41IDE2Ljg4YTEgMSAwIDAgMS0uMzItMS40M2w5LTEzLjAyYTEgMSAwIDAgMSAxLjY0IDBsOSAxMy4wMWExIDEgMCAwIDEtLjMyIDEuNDRsLTguNTEgNC44NmEyIDIgMCAwIDEtMS45OCAwWiIgLz4KICA8cGF0aCBkPSJNMTIgMnYyMCIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/pyramid\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 Pyramid = createLucideIcon('Pyramid', [\n [\n 'path',\n {\n d: 'M2.5 16.88a1 1 0 0 1-.32-1.43l9-13.02a1 1 0 0 1 1.64 0l9 13.01a1 1 0 0 1-.32 1.44l-8.51 4.86a2 2 0 0 1-1.98 0Z',\n key: 'aenxs0',\n },\n ],\n ['path', { d: 'M12 2v20', key: 't6zp3m' }],\n]);\n\nexport default Pyramid;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAU,iBAAiB,SAAW,CAAA,CAAA,CAAA;AAAA,CAC1C,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;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,CAAY,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC3C,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClassStaticBlockScope = void 0;
const ScopeBase_1 = require("./ScopeBase");
const ScopeType_1 = require("./ScopeType");
class ClassStaticBlockScope extends ScopeBase_1.ScopeBase {
constructor(scopeManager, upperScope, block) {
super(scopeManager, ScopeType_1.ScopeType.classStaticBlock, upperScope, block, false);
}
}
exports.ClassStaticBlockScope = ClassStaticBlockScope;
@@ -0,0 +1 @@
{"version":3,"file":"instagram.js","sources":["../../../src/icons/instagram.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Instagram\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cmVjdCB3aWR0aD0iMjAiIGhlaWdodD0iMjAiIHg9IjIiIHk9IjIiIHJ4PSI1IiByeT0iNSIgLz4KICA8cGF0aCBkPSJNMTYgMTEuMzdBNCA0IDAgMSAxIDEyLjYzIDggNCA0IDAgMCAxIDE2IDExLjM3eiIgLz4KICA8bGluZSB4MT0iMTcuNSIgeDI9IjE3LjUxIiB5MT0iNi41IiB5Mj0iNi41IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/instagram\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=instagram instead. This icon will be removed in v1.0\n */\nconst Instagram = createLucideIcon('Instagram', [\n ['rect', { width: '20', height: '20', x: '2', y: '2', rx: '5', ry: '5', key: '2e1cvw' }],\n ['path', { d: 'M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z', key: '9exkf1' }],\n ['line', { x1: '17.5', x2: '17.51', y1: '6.5', y2: '6.5', key: 'r4j83e' }],\n]);\n\nexport default Instagram;\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,KAAO,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAQ,CAAA,CAAA,CAAA,CAAA,CAAM,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,CACvF,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAmD,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAChF,CAAA,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAE,CAAA,CAAA,CAAA,EAAI,CAAQ,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAI,CAAS,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,CAAI,CAAA,CAAA,CAAA,CAAA,CAAA,CAAO,CAAA,CAAA,CAAA,CAAA,CAAI,CAAA,CAAA,CAAA,CAAA,CAAA,CAAO,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC3E,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,17 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const AlignHorizontalJustifyStart = createLucideIcon("AlignHorizontalJustifyStart", [
["rect", { width: "6", height: "14", x: "6", y: "5", rx: "2", key: "hsirpf" }],
["rect", { width: "6", height: "10", x: "16", y: "7", rx: "2", key: "13zkjt" }],
["path", { d: "M2 2v20", key: "1ivd8o" }]
]);
export { AlignHorizontalJustifyStart as default };
//# sourceMappingURL=align-horizontal-justify-start.js.map
@@ -0,0 +1,16 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_jsx_base = require("./base.js");
//#region src/jsx/jsx-dev-runtime.ts
function jsxDEV(tag, props, key) {
let node;
if (!props || !("children" in props)) node = require_jsx_base.jsxFn(tag, props, []);
else {
const children = props.children;
node = Array.isArray(children) ? require_jsx_base.jsxFn(tag, props, children) : require_jsx_base.jsxFn(tag, props, [children]);
}
node.key = key;
return node;
}
//#endregion
exports.Fragment = require_jsx_base.Fragment;
exports.jsxDEV = jsxDEV;
@@ -0,0 +1,19 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const PanelRightDashed = createLucideIcon("PanelRightDashed", [
["rect", { width: "18", height: "18", x: "3", y: "3", rx: "2", key: "afitv7" }],
["path", { d: "M15 14v1", key: "ilsfch" }],
["path", { d: "M15 19v2", key: "1fst2f" }],
["path", { d: "M15 3v2", key: "z204g4" }],
["path", { d: "M15 9v1", key: "z2a8b1" }]
]);
export { PanelRightDashed as default };
//# sourceMappingURL=panel-right-dashed.js.map
@@ -0,0 +1,443 @@
/*! *****************************************************************************
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" />
/// <reference lib="es2015.iterable" />
/**
* A typed array of 16-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
interface Float16Array<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> {
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: TArrayBuffer;
/**
* The length in bytes of the array.
*/
readonly byteLength: number;
/**
* The offset in bytes of the array.
*/
readonly byteOffset: number;
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param predicate A function that accepts up to three arguments. The every method calls
* the predicate function for each element in the array until the predicate returns a value
* which is coercible to the Boolean value false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean;
/**
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: number, start?: number, end?: number): this;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param predicate A function that accepts up to three arguments. The filter method calls
* the predicate function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Float16Array<ArrayBuffer>;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number;
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: this,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLastIndex(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void;
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: number, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: number, fromIndex?: number): number;
/**
* The length of the array.
*/
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (value: number, index: number, array: this) => number, thisArg?: any): Float16Array<ArrayBuffer>;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number;
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number;
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U;
/**
* Reverses the elements in an Array.
*/
reverse(): this;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
*/
slice(start?: number, end?: number): Float16Array<ArrayBuffer>;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param predicate A function that accepts up to three arguments. The some method calls
* the predicate function for each element in the array until the predicate returns a value
* which is coercible to the Boolean value true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean;
/**
* Sorts an array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if first argument is less than second argument, zero if they're equal and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* [11,2,22,1].sort((a, b) => a - b)
* ```
*/
sort(compareFn?: (a: number, b: number) => number): this;
/**
* Gets a new Float16Array view of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray(begin?: number, end?: number): Float16Array<TArrayBuffer>;
/**
* Converts a number to a string by using the current locale.
*/
toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Float16Array<ArrayBuffer>;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Float16Array.from([11.25, 2, -22.5, 1]);
* myNums.toSorted((a, b) => a - b) // Float16Array(4) [-22.5, 1, 2, 11.5]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Float16Array<ArrayBuffer>;
/**
* Returns a string representation of an array.
*/
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): this;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Float16Array<ArrayBuffer>;
[index: number]: number;
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): ArrayIterator<number>;
readonly [Symbol.toStringTag]: "Float16Array";
}
interface Float16ArrayConstructor {
readonly prototype: Float16Array<ArrayBufferLike>;
new (length?: number): Float16Array<ArrayBuffer>;
new (array: ArrayLike<number> | Iterable<number>): Float16Array<ArrayBuffer>;
new <TArrayBuffer extends ArrayBufferLike = ArrayBuffer>(buffer: TArrayBuffer, byteOffset?: number, length?: number): Float16Array<TArrayBuffer>;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float16Array<ArrayBuffer>;
new (array: ArrayLike<number> | ArrayBuffer): Float16Array<ArrayBuffer>;
/**
* The size in bytes of each element in the array.
*/
readonly BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Float16Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like object to convert to an array.
*/
from(arrayLike: ArrayLike<number>): Float16Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Float16Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
*/
from(elements: Iterable<number>): Float16Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(elements: Iterable<T>, mapfn?: (v: T, k: number) => number, thisArg?: any): Float16Array<ArrayBuffer>;
}
declare var Float16Array: Float16ArrayConstructor;
interface Math {
/**
* Returns the nearest half precision float representation of a number.
* @param x A numeric expression.
*/
f16round(x: number): number;
}
interface DataView<TArrayBuffer extends ArrayBufferLike> {
/**
* Gets the Float16 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
* @param littleEndian If false or undefined, a big-endian value should be read.
*/
getFloat16(byteOffset: number, littleEndian?: boolean): number;
/**
* Stores an Float16 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written.
*/
setFloat16(byteOffset: number, value: number, littleEndian?: boolean): void;
}
@@ -0,0 +1,72 @@
'use strict';
// do not edit .js files directly - edit src/index.jst
var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';
module.exports = function equal(a, b) {
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
if (a.constructor !== b.constructor) return false;
var length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
if ((a instanceof Map) && (b instanceof Map)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
for (i of a.entries())
if (!equal(i[1], b.get(i[0]))) return false;
return true;
}
if ((a instanceof Set) && (b instanceof Set)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
return true;
}
if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (a[i] !== b[i]) return false;
return true;
}
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0;)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for (i = length; i-- !== 0;) {
var key = keys[i];
if (!equal(a[key], b[key])) return false;
}
return true;
}
// true if both NaN, false otherwise
return a!==a && b!==b;
};
@@ -0,0 +1,28 @@
declare const pathExists: {
/**
Check if a path exists.
@returns Whether the path exists.
@example
```
// foo.ts
import pathExists = require('path-exists');
(async () => {
console.log(await pathExists('foo.ts'));
//=> true
})();
```
*/
(path: string): Promise<boolean>;
/**
Synchronously check if a path exists.
@returns Whether the path exists.
*/
sync(path: string): boolean;
};
export = pathExists;
@@ -0,0 +1,421 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = applyDecs2301;
var _checkInRHS = require("checkInRHS");
var _setFunctionName = require("setFunctionName");
var _toPropertyKey = require("toPropertyKey");
function applyDecs2301Factory() {
function createAddInitializerMethod(initializers, decoratorFinishedRef) {
return function addInitializer(initializer) {
assertNotFinished(decoratorFinishedRef, "addInitializer");
assertCallable(initializer, "An initializer");
initializers.push(initializer);
};
}
function assertInstanceIfPrivate(has, target) {
if (!has(target)) {
throw new TypeError("Attempted to access private element on non-instance");
}
}
function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, value, hasPrivateBrand) {
var kindStr;
switch (kind) {
case 1:
kindStr = "accessor";
break;
case 2:
kindStr = "method";
break;
case 3:
kindStr = "getter";
break;
case 4:
kindStr = "setter";
break;
default:
kindStr = "field";
}
var ctx = {
kind: kindStr,
name: isPrivate ? "#" + name : _toPropertyKey(name),
static: isStatic,
private: isPrivate
};
var decoratorFinishedRef = {
v: false
};
if (kind !== 0) {
ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
}
var get, set;
if (!isPrivate && (kind === 0 || kind === 2)) {
get = function (target) {
return target[name];
};
if (kind === 0) {
set = function (target, v) {
target[name] = v;
};
}
} else if (kind === 2) {
get = function (target) {
assertInstanceIfPrivate(hasPrivateBrand, target);
return desc.value;
};
} else {
var t = kind === 0 || kind === 1;
if (t || kind === 3) {
if (isPrivate) {
get = function (target) {
assertInstanceIfPrivate(hasPrivateBrand, target);
return desc.get.call(target);
};
} else {
get = function (target) {
return desc.get.call(target);
};
}
}
if (t || kind === 4) {
if (isPrivate) {
set = function (target, value) {
assertInstanceIfPrivate(hasPrivateBrand, target);
desc.set.call(target, value);
};
} else {
set = function (target, value) {
desc.set.call(target, value);
};
}
}
}
var has = isPrivate ? hasPrivateBrand.bind() : function (target) {
return name in target;
};
ctx.access = get && set ? {
get: get,
set: set,
has: has
} : get ? {
get: get,
has: has
} : {
set: set,
has: has
};
try {
return dec(value, ctx);
} finally {
decoratorFinishedRef.v = true;
}
}
function assertNotFinished(decoratorFinishedRef, fnName) {
if (decoratorFinishedRef.v) {
throw new Error("attempted to call " + fnName + " after decoration was finished");
}
}
function assertCallable(fn, hint) {
if (typeof fn !== "function") {
throw new TypeError(hint + " must be a function");
}
}
function assertValidReturnValue(kind, value) {
var type = typeof value;
if (kind === 1) {
if (type !== "object" || value === null) {
throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
}
if (value.get !== undefined) {
assertCallable(value.get, "accessor.get");
}
if (value.set !== undefined) {
assertCallable(value.set, "accessor.set");
}
if (value.init !== undefined) {
assertCallable(value.init, "accessor.init");
}
} else if (type !== "function") {
var hint;
if (kind === 0) {
hint = "field";
} else if (kind === 10) {
hint = "class";
} else {
hint = "method";
}
throw new TypeError(hint + " decorators must return a function or void 0");
}
}
function curryThis1(fn) {
return function () {
return fn(this);
};
}
function curryThis2(fn) {
return function (value) {
fn(this, value);
};
}
function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, hasPrivateBrand) {
var decs = decInfo[0];
var desc, init, prefix, value;
if (isPrivate) {
if (kind === 0 || kind === 1) {
desc = {
get: curryThis1(decInfo[3]),
set: curryThis2(decInfo[4])
};
prefix = "get";
} else {
if (kind === 3) {
desc = {
get: decInfo[3]
};
prefix = "get";
} else if (kind === 4) {
desc = {
set: decInfo[3]
};
prefix = "set";
} else {
desc = {
value: decInfo[3]
};
}
}
if (kind !== 0) {
if (kind === 1) {
_setFunctionName(desc.set, "#" + name, "set");
}
_setFunctionName(desc[prefix || "value"], "#" + name, prefix);
}
} else if (kind !== 0) {
desc = Object.getOwnPropertyDescriptor(base, name);
}
if (kind === 1) {
value = {
get: desc.get,
set: desc.set
};
} else if (kind === 2) {
value = desc.value;
} else if (kind === 3) {
value = desc.get;
} else if (kind === 4) {
value = desc.set;
}
var newValue, get, set;
if (typeof decs === "function") {
newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, value, hasPrivateBrand);
if (newValue !== void 0) {
assertValidReturnValue(kind, newValue);
if (kind === 0) {
init = newValue;
} else if (kind === 1) {
init = newValue.init;
get = newValue.get || value.get;
set = newValue.set || value.set;
value = {
get: get,
set: set
};
} else {
value = newValue;
}
}
} else {
for (var i = decs.length - 1; i >= 0; i--) {
var dec = decs[i];
newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, value, hasPrivateBrand);
if (newValue !== void 0) {
assertValidReturnValue(kind, newValue);
var newInit;
if (kind === 0) {
newInit = newValue;
} else if (kind === 1) {
newInit = newValue.init;
get = newValue.get || value.get;
set = newValue.set || value.set;
value = {
get: get,
set: set
};
} else {
value = newValue;
}
if (newInit !== void 0) {
if (init === void 0) {
init = newInit;
} else if (typeof init === "function") {
init = [init, newInit];
} else {
init.push(newInit);
}
}
}
}
}
if (kind === 0 || kind === 1) {
if (init === void 0) {
init = function (instance, init) {
return init;
};
} else if (typeof init !== "function") {
var ownInitializers = init;
init = function (instance, init) {
var value = init;
for (var i = 0; i < ownInitializers.length; i++) {
value = ownInitializers[i].call(instance, value);
}
return value;
};
} else {
var originalInitializer = init;
init = function (instance, init) {
return originalInitializer.call(instance, init);
};
}
ret.push(init);
}
if (kind !== 0) {
if (kind === 1) {
desc.get = value.get;
desc.set = value.set;
} else if (kind === 2) {
desc.value = value;
} else if (kind === 3) {
desc.get = value;
} else if (kind === 4) {
desc.set = value;
}
if (isPrivate) {
if (kind === 1) {
ret.push(function (instance, args) {
return value.get.call(instance, args);
});
ret.push(function (instance, args) {
return value.set.call(instance, args);
});
} else if (kind === 2) {
ret.push(value);
} else {
ret.push(function (instance, args) {
return value.call(instance, args);
});
}
} else {
Object.defineProperty(base, name, desc);
}
}
}
function applyMemberDecs(Class, decInfos, instanceBrand) {
var ret = [];
var protoInitializers;
var staticInitializers;
var staticBrand;
var existingProtoNonFields = new Map();
var existingStaticNonFields = new Map();
for (var i = 0; i < decInfos.length; i++) {
var decInfo = decInfos[i];
if (!Array.isArray(decInfo)) continue;
var kind = decInfo[1];
var name = decInfo[2];
var isPrivate = decInfo.length > 3;
var isStatic = kind >= 5;
var base;
var initializers;
var hasPrivateBrand = instanceBrand;
if (isStatic) {
base = Class;
kind = kind - 5;
if (kind !== 0) {
staticInitializers = staticInitializers || [];
initializers = staticInitializers;
}
if (isPrivate && !staticBrand) {
staticBrand = function (_) {
return _checkInRHS(_) === Class;
};
}
hasPrivateBrand = staticBrand;
} else {
base = Class.prototype;
if (kind !== 0) {
protoInitializers = protoInitializers || [];
initializers = protoInitializers;
}
}
if (kind !== 0 && !isPrivate) {
var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
var existingKind = existingNonFields.get(name) || 0;
if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) {
throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name);
} else if (!existingKind && kind > 2) {
existingNonFields.set(name, kind);
} else {
existingNonFields.set(name, true);
}
}
applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, hasPrivateBrand);
}
pushInitializers(ret, protoInitializers);
pushInitializers(ret, staticInitializers);
return ret;
}
function pushInitializers(ret, initializers) {
if (initializers) {
ret.push(function (instance) {
for (var i = 0; i < initializers.length; i++) {
initializers[i].call(instance);
}
return instance;
});
}
}
function applyClassDecs(targetClass, classDecs) {
if (classDecs.length > 0) {
var initializers = [];
var newClass = targetClass;
var name = targetClass.name;
for (var i = classDecs.length - 1; i >= 0; i--) {
var decoratorFinishedRef = {
v: false
};
try {
var nextNewClass = classDecs[i](newClass, {
kind: "class",
name: name,
addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef)
});
} finally {
decoratorFinishedRef.v = true;
}
if (nextNewClass !== undefined) {
assertValidReturnValue(10, nextNewClass);
newClass = nextNewClass;
}
}
return [newClass, function () {
for (var i = 0; i < initializers.length; i++) {
initializers[i].call(newClass);
}
}];
}
}
return function applyDecs2301(targetClass, memberDecs, classDecs, instanceBrand) {
return {
e: applyMemberDecs(targetClass, memberDecs, instanceBrand),
get c() {
return applyClassDecs(targetClass, classDecs);
}
};
};
}
function applyDecs2301(targetClass, memberDecs, classDecs, instanceBrand) {
return (exports.default = applyDecs2301 = applyDecs2301Factory())(targetClass, memberDecs, classDecs, instanceBrand);
}
//# sourceMappingURL=applyDecs2301.js.map
@@ -0,0 +1,115 @@
import * as util from "../core/util.js";
const error = () => {
const Sizable = {
string: { unit: "tecken", verb: "att ha" },
file: { unit: "bytes", verb: "att ha" },
array: { unit: "objekt", verb: "att innehålla" },
set: { unit: "objekt", verb: "att innehålla" },
map: { unit: "objekt", verb: "att innehålla" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "reguljärt uttryck",
email: "e-postadress",
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-datum och tid",
date: "ISO-datum",
time: "ISO-tid",
duration: "ISO-varaktighet",
ipv4: "IPv4-adress",
ipv6: "IPv6-adress",
mac: "MAC-adress",
cidrv4: "IPv4-spektrum",
cidrv6: "IPv6-spektrum",
base64: "base64-kodad sträng",
base64url: "base64url-kodad sträng",
json_string: "JSON-sträng",
e164: "E.164-nummer",
credit_card: "kreditkortsnummer",
currency_code: "valutakod",
iban: "IBAN",
jwt: "JWT",
template_literal: "mall-literal",
};
const TypeDictionary = {
nan: "NaN",
number: "antal",
array: "lista",
};
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 `Ogiltig inmatning: förväntat instanceof ${issue.expected}, fick ${received}`;
}
return `Ogiltig inmatning: förväntat ${expected}, fick ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Ogiltig inmatning: förväntat ${util.stringifyPrimitive(issue.values[0])}`;
return `Ogiltigt val: förväntade en av ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing) {
return `För stor(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? "element"}`;
}
return `För stor(t): förväntat ${issue.origin ?? "värdet"} att ha ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `För lite(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.minimum.toString()} ${sizing.unit}`;
}
return `För lite(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with") {
return `Ogiltig sträng: måste börja med "${_issue.prefix}"`;
}
if (_issue.format === "ends_with")
return `Ogiltig sträng: måste sluta med "${_issue.suffix}"`;
if (_issue.format === "includes")
return `Ogiltig sträng: måste innehålla "${_issue.includes}"`;
if (_issue.format === "regex")
return `Ogiltig sträng: måste matcha mönstret "${_issue.pattern}"`;
return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Ogiltigt tal: måste vara en multipel av ${issue.divisor}`;
case "unrecognized_keys":
return `${issue.keys.length > 1 ? "Okända nycklar" : "Okänd nyckel"}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Ogiltig nyckel i ${issue.origin ?? "värdet"}`;
case "invalid_union":
return "Ogiltig input";
case "invalid_element":
return `Ogiltigt värde i ${issue.origin ?? "värdet"}`;
default:
return `Ogiltig input`;
}
};
};
export default function () {
return {
localeError: error(),
};
}
@@ -0,0 +1,907 @@
//! otpauth 9.5.1 | (c) Héctor Molinero Fernández | MIT | https://github.com/hectorm/otpauth
//! noble-hashes 2.2.0 | (c) Paul Miller | MIT | https://github.com/paulmillr/noble-hashes
/// <reference types="./otpauth.d.ts" />
// @ts-nocheck
import { hmac } from '@noble/hashes/hmac.js';
import { sha1 } from '@noble/hashes/legacy.js';
import { sha512, sha384, sha256, sha224 } from '@noble/hashes/sha2.js';
import { sha3_512, sha3_384, sha3_256, sha3_224 } from '@noble/hashes/sha3.js';
/**
* Converts an integer to an Uint8Array.
* @param {number} num Integer.
* @returns {Uint8Array} Uint8Array.
*/ const uintDecode = (num)=>{
const buf = new ArrayBuffer(8);
const arr = new Uint8Array(buf);
let acc = num;
for(let i = 7; i >= 0; i--){
if (acc === 0) break;
arr[i] = acc & 255;
acc -= arr[i];
acc /= 256;
}
return arr;
};
/**
* "globalThis" ponyfill.
* @see [A horrifying globalThis polyfill in universal JavaScript](https://mathiasbynens.be/notes/globalthis)
* @type {Object.<string, *>}
*/ const globalScope = (()=>{
if (typeof globalThis === "object") return globalThis;
else {
Object.defineProperty(Object.prototype, "__GLOBALTHIS__", {
get () {
return this;
},
configurable: true
});
try {
// @ts-expect-error
// eslint-disable-next-line no-undef
if (typeof __GLOBALTHIS__ !== "undefined") return __GLOBALTHIS__;
} finally{
// @ts-expect-error
delete Object.prototype.__GLOBALTHIS__;
}
}
// Still unable to determine "globalThis", fall back to a naive method.
if (typeof self !== "undefined") return self;
else if (typeof window !== "undefined") return window;
else if (typeof global !== "undefined") return global;
return undefined;
})();
/**
* @noble/hashes hash functions.
* @type {Object.<string, sha1|sha224|sha256|sha384|sha512|sha3_224|sha3_256|sha3_384|sha3_512>}
*/ const nobleHashes = {
SHA1: sha1,
SHA224: sha224,
SHA256: sha256,
SHA384: sha384,
SHA512: sha512,
"SHA3-224": sha3_224,
"SHA3-256": sha3_256,
"SHA3-384": sha3_384,
"SHA3-512": sha3_512
};
/**
* Canonicalizes a hash algorithm name.
* @param {string} algorithm Hash algorithm name.
* @returns {"SHA1"|"SHA224"|"SHA256"|"SHA384"|"SHA512"|"SHA3-224"|"SHA3-256"|"SHA3-384"|"SHA3-512"} Canonicalized hash algorithm name.
*/ const canonicalizeAlgorithm = (algorithm)=>{
switch(true){
case /^(?:SHA-?1|SSL3-SHA1)$/i.test(algorithm):
return "SHA1";
case /^SHA(?:2?-)?224$/i.test(algorithm):
return "SHA224";
case /^SHA(?:2?-)?256$/i.test(algorithm):
return "SHA256";
case /^SHA(?:2?-)?384$/i.test(algorithm):
return "SHA384";
case /^SHA(?:2?-)?512$/i.test(algorithm):
return "SHA512";
case /^SHA3-224$/i.test(algorithm):
return "SHA3-224";
case /^SHA3-256$/i.test(algorithm):
return "SHA3-256";
case /^SHA3-384$/i.test(algorithm):
return "SHA3-384";
case /^SHA3-512$/i.test(algorithm):
return "SHA3-512";
default:
throw new TypeError(`Unknown hash algorithm: ${algorithm}`);
}
};
/**
* Calculates an HMAC digest.
* @param {string} algorithm Algorithm.
* @param {Uint8Array} key Key.
* @param {Uint8Array} message Message.
* @returns {Uint8Array} Digest.
*/ const hmacDigest = (algorithm, key, message)=>{
if (hmac) {
const hash = nobleHashes[algorithm] ?? nobleHashes[canonicalizeAlgorithm(algorithm)];
return hmac(hash, key, message);
} else {
throw new Error("Missing HMAC function");
}
};
/**
* RFC 4648 base32 alphabet without pad.
* @type {string}
*/ const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
/**
* Converts a base32 string to an Uint8Array (RFC 4648).
* @see [LinusU/base32-decode](https://github.com/LinusU/base32-decode)
* @param {string} str Base32 string.
* @returns {Uint8Array} Uint8Array.
*/ const base32Decode = (str)=>{
// Remove spaces (although they are not allowed by the spec, some issuers add them for readability).
str = str.replace(/ /g, "");
// Canonicalize to all upper case and remove padding if it exists.
let end = str.length;
while(str[end - 1] === "=")--end;
str = (end < str.length ? str.substring(0, end) : str).toUpperCase();
const buf = new ArrayBuffer(str.length * 5 / 8 | 0);
const arr = new Uint8Array(buf);
let bits = 0;
let value = 0;
let index = 0;
for(let i = 0; i < str.length; i++){
const idx = ALPHABET.indexOf(str[i]);
if (idx === -1) throw new TypeError(`Invalid character found: ${str[i]}`);
value = value << 5 | idx;
bits += 5;
if (bits >= 8) {
bits -= 8;
arr[index++] = value >>> bits;
}
}
return arr;
};
/**
* Converts an Uint8Array to a base32 string (RFC 4648).
* @see [LinusU/base32-encode](https://github.com/LinusU/base32-encode)
* @param {Uint8Array} arr Uint8Array.
* @returns {string} Base32 string.
*/ const base32Encode = (arr)=>{
let bits = 0;
let value = 0;
let str = "";
for(let i = 0; i < arr.length; i++){
value = value << 8 | arr[i];
bits += 8;
while(bits >= 5){
str += ALPHABET[value >>> bits - 5 & 31];
bits -= 5;
}
}
if (bits > 0) {
str += ALPHABET[value << 5 - bits & 31];
}
return str;
};
/**
* Converts a hexadecimal string to an Uint8Array.
* @param {string} str Hexadecimal string.
* @returns {Uint8Array} Uint8Array.
*/ const hexDecode = (str)=>{
// Remove spaces (although they are not allowed by the spec, some issuers add them for readability).
str = str.replace(/ /g, "");
const buf = new ArrayBuffer(str.length / 2);
const arr = new Uint8Array(buf);
for(let i = 0; i < str.length; i += 2){
arr[i / 2] = parseInt(str.substring(i, i + 2), 16);
}
return arr;
};
/**
* Converts an Uint8Array to a hexadecimal string.
* @param {Uint8Array} arr Uint8Array.
* @returns {string} Hexadecimal string.
*/ const hexEncode = (arr)=>{
let str = "";
for(let i = 0; i < arr.length; i++){
const hex = arr[i].toString(16);
if (hex.length === 1) str += "0";
str += hex;
}
return str.toUpperCase();
};
/**
* Converts a Latin-1 string to an Uint8Array.
* @param {string} str Latin-1 string.
* @returns {Uint8Array} Uint8Array.
*/ const latin1Decode = (str)=>{
const buf = new ArrayBuffer(str.length);
const arr = new Uint8Array(buf);
for(let i = 0; i < str.length; i++){
arr[i] = str.charCodeAt(i) & 0xff;
}
return arr;
};
/**
* Converts an Uint8Array to a Latin-1 string.
* @param {Uint8Array} arr Uint8Array.
* @returns {string} Latin-1 string.
*/ const latin1Encode = (arr)=>{
let str = "";
for(let i = 0; i < arr.length; i++){
str += String.fromCharCode(arr[i]);
}
return str;
};
/**
* TextEncoder instance.
* @type {TextEncoder|null}
*/ const ENCODER = globalScope.TextEncoder ? new globalScope.TextEncoder() : null;
/**
* TextDecoder instance.
* @type {TextDecoder|null}
*/ const DECODER = globalScope.TextDecoder ? new globalScope.TextDecoder() : null;
/**
* Converts an UTF-8 string to an Uint8Array.
* @param {string} str String.
* @returns {Uint8Array} Uint8Array.
*/ const utf8Decode = (str)=>{
if (!ENCODER) {
throw new Error("Encoding API not available");
}
return ENCODER.encode(str);
};
/**
* Converts an Uint8Array to an UTF-8 string.
* @param {Uint8Array} arr Uint8Array.
* @returns {string} String.
*/ const utf8Encode = (arr)=>{
if (!DECODER) {
throw new Error("Encoding API not available");
}
return DECODER.decode(arr);
};
/**
* Returns random bytes.
* @param {number} size Size.
* @returns {Uint8Array} Random bytes.
*/ const randomBytes = (size)=>{
if (globalScope.crypto?.getRandomValues) {
return globalScope.crypto.getRandomValues(new Uint8Array(size));
} else {
throw new Error("Cryptography API not available");
}
};
/**
* OTP secret key.
*/ class Secret {
/**
* Converts a Latin-1 string to a Secret object.
* @param {string} str Latin-1 string.
* @returns {Secret} Secret object.
*/ static fromLatin1(str) {
return new Secret({
buffer: latin1Decode(str).buffer
});
}
/**
* Converts an UTF-8 string to a Secret object.
* @param {string} str UTF-8 string.
* @returns {Secret} Secret object.
*/ static fromUTF8(str) {
return new Secret({
buffer: utf8Decode(str).buffer
});
}
/**
* Converts a base32 string to a Secret object.
* @param {string} str Base32 string.
* @returns {Secret} Secret object.
*/ static fromBase32(str) {
return new Secret({
buffer: base32Decode(str).buffer
});
}
/**
* Converts a hexadecimal string to a Secret object.
* @param {string} str Hexadecimal string.
* @returns {Secret} Secret object.
*/ static fromHex(str) {
return new Secret({
buffer: hexDecode(str).buffer
});
}
/**
* Secret key buffer.
* @deprecated For backward compatibility, the "bytes" property should be used instead.
* @type {ArrayBufferLike}
*/ get buffer() {
return this.bytes.buffer;
}
/**
* Latin-1 string representation of secret key.
* @type {string}
*/ get latin1() {
Object.defineProperty(this, "latin1", {
enumerable: true,
writable: false,
configurable: false,
value: latin1Encode(this.bytes)
});
return this.latin1;
}
/**
* UTF-8 string representation of secret key.
* @type {string}
*/ get utf8() {
Object.defineProperty(this, "utf8", {
enumerable: true,
writable: false,
configurable: false,
value: utf8Encode(this.bytes)
});
return this.utf8;
}
/**
* Base32 string representation of secret key.
* @type {string}
*/ get base32() {
Object.defineProperty(this, "base32", {
enumerable: true,
writable: false,
configurable: false,
value: base32Encode(this.bytes)
});
return this.base32;
}
/**
* Hexadecimal string representation of secret key.
* @type {string}
*/ get hex() {
Object.defineProperty(this, "hex", {
enumerable: true,
writable: false,
configurable: false,
value: hexEncode(this.bytes)
});
return this.hex;
}
/**
* Creates a secret key object.
* @param {Object} [config] Configuration options.
* @param {ArrayBufferLike} [config.buffer] Secret key buffer.
* @param {number} [config.size=20] Number of random bytes to generate, ignored if 'buffer' is provided.
*/ constructor({ buffer, size = 20 } = {}){
/**
* Secret key.
* @type {Uint8Array}
* @readonly
*/ this.bytes = typeof buffer === "undefined" ? randomBytes(size) : new Uint8Array(buffer);
// Prevent the "bytes" property from being modified.
Object.defineProperty(this, "bytes", {
enumerable: true,
writable: false,
configurable: false,
value: this.bytes
});
}
}
/**
* Returns true if a is equal to b, without leaking timing information that would allow an attacker to guess one of the values.
* @param {string} a String a.
* @param {string} b String b.
* @returns {boolean} Equality result.
*/ const timingSafeEqual = (a, b)=>{
{
if (a.length !== b.length) {
throw new TypeError("Input strings must have the same length");
}
let i = -1;
let out = 0;
while(++i < a.length){
out |= a.charCodeAt(i) ^ b.charCodeAt(i);
}
return out === 0;
}
};
/**
* HOTP: An HMAC-based One-time Password Algorithm.
* @see [RFC 4226](https://datatracker.ietf.org/doc/html/rfc4226)
*/ class HOTP {
/**
* Default configuration.
* @type {{
* issuer: string,
* label: string,
* issuerInLabel: boolean,
* algorithm: string,
* digits: number,
* counter: number
* window: number
* }}
*/ static get defaults() {
return {
issuer: "",
label: "OTPAuth",
issuerInLabel: true,
algorithm: "SHA1",
digits: 6,
counter: 0,
window: 1
};
}
/**
* Generates an HOTP token.
* @param {Object} config Configuration options.
* @param {Secret} config.secret Secret key.
* @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
* @param {number} [config.digits=6] Token length.
* @param {number} [config.counter=0] Counter value.
* @param {(algorithm: string, key: Uint8Array, message: Uint8Array) => Uint8Array} [config.hmac] Custom HMAC function.
* @returns {string} Token.
*/ static generate({ secret, algorithm = HOTP.defaults.algorithm, digits = HOTP.defaults.digits, counter = HOTP.defaults.counter, hmac = hmacDigest }) {
const message = uintDecode(counter);
const digest = hmac(algorithm, secret.bytes, message);
if (!digest?.byteLength || digest.byteLength < 19) {
throw new TypeError("Return value must be at least 19 bytes");
}
const offset = digest[digest.byteLength - 1] & 15;
const otp = ((digest[offset] & 127) << 24 | (digest[offset + 1] & 255) << 16 | (digest[offset + 2] & 255) << 8 | digest[offset + 3] & 255) % 10 ** digits;
return otp.toString().padStart(digits, "0");
}
/**
* Generates an HOTP token.
* @param {Object} [config] Configuration options.
* @param {number} [config.counter=this.counter++] Counter value.
* @returns {string} Token.
*/ generate({ counter = this.counter++ } = {}) {
return HOTP.generate({
secret: this.secret,
algorithm: this.algorithm,
digits: this.digits,
counter,
hmac: this.hmac
});
}
/**
* Validates an HOTP token.
* @param {Object} config Configuration options.
* @param {string} config.token Token value.
* @param {Secret} config.secret Secret key.
* @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
* @param {number} [config.digits=6] Token length.
* @param {number} [config.counter=0] Counter value.
* @param {number} [config.window=1] Window of counter values to test.
* @param {(algorithm: string, key: Uint8Array, message: Uint8Array) => Uint8Array} [config.hmac] Custom HMAC function.
* @returns {number|null} Token delta or null if it is not found in the search window, in which case it should be considered invalid.
*/ static validate({ token, secret, algorithm, digits = HOTP.defaults.digits, counter = HOTP.defaults.counter, window = HOTP.defaults.window, hmac = hmacDigest }) {
// Return early if the token length does not match the digit number.
if (token.length !== digits) return null;
let delta = null;
const check = (/** @type {number} */ i)=>{
const generatedToken = HOTP.generate({
secret,
algorithm,
digits,
counter: i,
hmac
});
if (timingSafeEqual(token, generatedToken)) {
delta = i - counter;
}
};
check(counter);
for(let i = 1; i <= window && delta === null; ++i){
check(counter - i);
if (delta !== null) break;
check(counter + i);
if (delta !== null) break;
}
return delta;
}
/**
* Validates an HOTP token.
* @param {Object} config Configuration options.
* @param {string} config.token Token value.
* @param {number} [config.counter=this.counter] Counter value.
* @param {number} [config.window=1] Window of counter values to test.
* @returns {number|null} Token delta or null if it is not found in the search window, in which case it should be considered invalid.
*/ validate({ token, counter = this.counter, window }) {
return HOTP.validate({
token,
secret: this.secret,
algorithm: this.algorithm,
digits: this.digits,
counter,
window,
hmac: this.hmac
});
}
/**
* Returns a Google Authenticator key URI.
* @returns {string} URI.
*/ toString() {
const e = encodeURIComponent;
return "otpauth://hotp/" + `${this.issuer.length > 0 ? this.issuerInLabel ? `${e(this.issuer)}:${e(this.label)}?issuer=${e(this.issuer)}&` : `${e(this.label)}?issuer=${e(this.issuer)}&` : `${e(this.label)}?`}` + `secret=${e(this.secret.base32)}&` + `algorithm=${e(this.algorithm)}&` + `digits=${e(this.digits)}&` + `counter=${e(this.counter)}`;
}
/**
* Creates an HOTP object.
* @param {Object} [config] Configuration options.
* @param {string} [config.issuer=''] Account provider.
* @param {string} [config.label='OTPAuth'] Account label.
* @param {boolean} [config.issuerInLabel=true] Include issuer prefix in label.
* @param {Secret|string} [config.secret=Secret] Secret key.
* @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
* @param {number} [config.digits=6] Token length.
* @param {number} [config.counter=0] Initial counter value.
* @param {(algorithm: string, key: Uint8Array, message: Uint8Array) => Uint8Array} [config.hmac] Custom HMAC function.
*/ constructor({ issuer = HOTP.defaults.issuer, label = HOTP.defaults.label, issuerInLabel = HOTP.defaults.issuerInLabel, secret = new Secret(), algorithm = HOTP.defaults.algorithm, digits = HOTP.defaults.digits, counter = HOTP.defaults.counter, hmac } = {}){
/**
* Account provider.
* @type {string}
*/ this.issuer = issuer;
/**
* Account label.
* @type {string}
*/ this.label = label;
/**
* Include issuer prefix in label.
* @type {boolean}
*/ this.issuerInLabel = issuerInLabel;
/**
* Secret key.
* @type {Secret}
*/ this.secret = typeof secret === "string" ? Secret.fromBase32(secret) : secret;
/**
* HMAC hashing algorithm.
* @type {string}
*/ this.algorithm = hmac ? algorithm : canonicalizeAlgorithm(algorithm);
/**
* Token length.
* @type {number}
*/ this.digits = digits;
/**
* Initial counter value.
* @type {number}
*/ this.counter = counter;
/**
* Custom HMAC function.
* @type {((algorithm: string, key: Uint8Array, message: Uint8Array) => Uint8Array)|undefined}
*/ this.hmac = hmac;
}
}
/**
* TOTP: Time-Based One-Time Password Algorithm.
* @see [RFC 6238](https://datatracker.ietf.org/doc/html/rfc6238)
*/ class TOTP {
/**
* Default configuration.
* @type {{
* issuer: string,
* label: string,
* issuerInLabel: boolean,
* algorithm: string,
* digits: number,
* period: number
* window: number
* }}
*/ static get defaults() {
return {
issuer: "",
label: "OTPAuth",
issuerInLabel: true,
algorithm: "SHA1",
digits: 6,
period: 30,
window: 1
};
}
/**
* Calculates the counter. i.e. the number of periods since timestamp 0.
* @param {Object} [config] Configuration options.
* @param {number} [config.period=30] Token time-step duration.
* @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
* @returns {number} Counter.
*/ static counter({ period = TOTP.defaults.period, timestamp = Date.now() } = {}) {
return Math.floor(timestamp / 1000 / period);
}
/**
* Calculates the counter. i.e. the number of periods since timestamp 0.
* @param {Object} [config] Configuration options.
* @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
* @returns {number} Counter.
*/ counter({ timestamp = Date.now() } = {}) {
return TOTP.counter({
period: this.period,
timestamp
});
}
/**
* Calculates the remaining time in milliseconds until the next token is generated.
* @param {Object} [config] Configuration options.
* @param {number} [config.period=30] Token time-step duration.
* @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
* @returns {number} counter.
*/ static remaining({ period = TOTP.defaults.period, timestamp = Date.now() } = {}) {
return period * 1000 - timestamp % (period * 1000);
}
/**
* Calculates the remaining time in milliseconds until the next token is generated.
* @param {Object} [config] Configuration options.
* @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
* @returns {number} counter.
*/ remaining({ timestamp = Date.now() } = {}) {
return TOTP.remaining({
period: this.period,
timestamp
});
}
/**
* Generates a TOTP token.
* @param {Object} config Configuration options.
* @param {Secret} config.secret Secret key.
* @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
* @param {number} [config.digits=6] Token length.
* @param {number} [config.period=30] Token time-step duration.
* @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
* @param {(algorithm: string, key: Uint8Array, message: Uint8Array) => Uint8Array} [config.hmac] Custom HMAC function.
* @returns {string} Token.
*/ static generate({ secret, algorithm, digits, period = TOTP.defaults.period, timestamp = Date.now(), hmac }) {
return HOTP.generate({
secret,
algorithm,
digits,
counter: TOTP.counter({
period,
timestamp
}),
hmac
});
}
/**
* Generates a TOTP token.
* @param {Object} [config] Configuration options.
* @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
* @returns {string} Token.
*/ generate({ timestamp = Date.now() } = {}) {
return TOTP.generate({
secret: this.secret,
algorithm: this.algorithm,
digits: this.digits,
period: this.period,
timestamp,
hmac: this.hmac
});
}
/**
* Validates a TOTP token.
* @param {Object} config Configuration options.
* @param {string} config.token Token value.
* @param {Secret} config.secret Secret key.
* @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
* @param {number} [config.digits=6] Token length.
* @param {number} [config.period=30] Token time-step duration.
* @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
* @param {number} [config.window=1] Window of counter values to test.
* @param {(algorithm: string, key: Uint8Array, message: Uint8Array) => Uint8Array} [config.hmac] Custom HMAC function.
* @returns {number|null} Token delta or null if it is not found in the search window, in which case it should be considered invalid.
*/ static validate({ token, secret, algorithm, digits, period = TOTP.defaults.period, timestamp = Date.now(), window, hmac }) {
return HOTP.validate({
token,
secret,
algorithm,
digits,
counter: TOTP.counter({
period,
timestamp
}),
window,
hmac
});
}
/**
* Validates a TOTP token.
* @param {Object} config Configuration options.
* @param {string} config.token Token value.
* @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds.
* @param {number} [config.window=1] Window of counter values to test.
* @returns {number|null} Token delta or null if it is not found in the search window, in which case it should be considered invalid.
*/ validate({ token, timestamp, window }) {
return TOTP.validate({
token,
secret: this.secret,
algorithm: this.algorithm,
digits: this.digits,
period: this.period,
timestamp,
window,
hmac: this.hmac
});
}
/**
* Returns a Google Authenticator key URI.
* @returns {string} URI.
*/ toString() {
const e = encodeURIComponent;
return "otpauth://totp/" + `${this.issuer.length > 0 ? this.issuerInLabel ? `${e(this.issuer)}:${e(this.label)}?issuer=${e(this.issuer)}&` : `${e(this.label)}?issuer=${e(this.issuer)}&` : `${e(this.label)}?`}` + `secret=${e(this.secret.base32)}&` + `algorithm=${e(this.algorithm)}&` + `digits=${e(this.digits)}&` + `period=${e(this.period)}`;
}
/**
* Creates a TOTP object.
* @param {Object} [config] Configuration options.
* @param {string} [config.issuer=''] Account provider.
* @param {string} [config.label='OTPAuth'] Account label.
* @param {boolean} [config.issuerInLabel=true] Include issuer prefix in label.
* @param {Secret|string} [config.secret=Secret] Secret key.
* @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm.
* @param {number} [config.digits=6] Token length.
* @param {number} [config.period=30] Token time-step duration.
* @param {(algorithm: string, key: Uint8Array, message: Uint8Array) => Uint8Array} [config.hmac] Custom HMAC function.
*/ constructor({ issuer = TOTP.defaults.issuer, label = TOTP.defaults.label, issuerInLabel = TOTP.defaults.issuerInLabel, secret = new Secret(), algorithm = TOTP.defaults.algorithm, digits = TOTP.defaults.digits, period = TOTP.defaults.period, hmac } = {}){
/**
* Account provider.
* @type {string}
*/ this.issuer = issuer;
/**
* Account label.
* @type {string}
*/ this.label = label;
/**
* Include issuer prefix in label.
* @type {boolean}
*/ this.issuerInLabel = issuerInLabel;
/**
* Secret key.
* @type {Secret}
*/ this.secret = typeof secret === "string" ? Secret.fromBase32(secret) : secret;
/**
* HMAC hashing algorithm.
* @type {string}
*/ this.algorithm = hmac ? algorithm : canonicalizeAlgorithm(algorithm);
/**
* Token length.
* @type {number}
*/ this.digits = digits;
/**
* Token time-step duration.
* @type {number}
*/ this.period = period;
/**
* Custom HMAC function.
* @type {((algorithm: string, key: Uint8Array, message: Uint8Array) => Uint8Array)|undefined}
*/ this.hmac = hmac;
}
}
/**
* Key URI regex (otpauth://TYPE/[ISSUER:]LABEL?PARAMETERS).
* @type {RegExp}
*/ const OTPURI_REGEX = /^otpauth:\/\/([ht]otp)\/(.+)\?([A-Z0-9.~_-]+=[^?&]*(?:&[A-Z0-9.~_-]+=[^?&]*)*)$/i;
/**
* RFC 4648 base32 alphabet with pad.
* @type {RegExp}
*/ const SECRET_REGEX = /^[2-7A-Z]+=*$/i;
/**
* Regex for supported algorithms in built-in HMAC function.
* @type {RegExp}
*/ const ALGORITHM_REGEX = /^SHA(?:1|224|256|384|512|3-224|3-256|3-384|3-512)$/i;
/**
* Regex for custom algorithms in user-defined HMAC function.
* @type {RegExp}
*/ const ALGORITHM_CUSTOM_REGEX = /^[A-Z0-9]+(?:[_-][A-Z0-9]+)*$/i;
/**
* Integer regex.
* @type {RegExp}
*/ const INTEGER_REGEX = /^[+-]?\d+$/;
/**
* Positive integer regex.
* @type {RegExp}
*/ const POSITIVE_INTEGER_REGEX = /^\+?[1-9]\d*$/;
/**
* HOTP/TOTP object/string conversion.
* @see [Key URI Format](https://github.com/google/google-authenticator/wiki/Key-Uri-Format)
*/ class URI {
/**
* Parses a Google Authenticator key URI and returns an HOTP/TOTP object.
* @param {string} uri Google Authenticator Key URI.
* @param {Object} [config] Configuration options.
* @param {(algorithm: string, key: Uint8Array, message: Uint8Array) => Uint8Array} [config.hmac] Custom HMAC function.
* @returns {HOTP|TOTP} HOTP/TOTP object.
*/ static parse(uri, { hmac } = {}) {
let uriGroups;
try {
uriGroups = uri.match(OTPURI_REGEX);
// eslint-disable-next-line no-unused-vars
} catch (_) {
/* Handled below */ }
if (!Array.isArray(uriGroups)) {
throw new URIError("Invalid URI format");
}
// Extract URI groups.
const uriType = uriGroups[1].toLowerCase();
const uriLabel = uriGroups[2].split(/(?::|%3A) *(.+)/i, 2).map(decodeURIComponent);
/** @type {Object.<string, string>} */ const uriParams = uriGroups[3].split("&").reduce((acc, cur)=>{
const pairArr = cur.split(/=(.*)/, 2).map(decodeURIComponent);
const pairKey = pairArr[0].toLowerCase();
const pairVal = pairArr[1];
/** @type {Object.<string, string>} */ const pairAcc = acc;
pairAcc[pairKey] = pairVal;
return pairAcc;
}, {});
// 'OTP' will be instantiated with 'config' argument.
let OTP;
const config = {};
if (uriType === "hotp") {
OTP = HOTP;
// Counter: required
if (typeof uriParams.counter !== "undefined" && INTEGER_REGEX.test(uriParams.counter)) {
config.counter = parseInt(uriParams.counter, 10);
} else {
throw new TypeError("Missing or invalid 'counter' parameter");
}
} else if (uriType === "totp") {
OTP = TOTP;
// Period: optional
if (typeof uriParams.period !== "undefined") {
if (POSITIVE_INTEGER_REGEX.test(uriParams.period)) {
config.period = parseInt(uriParams.period, 10);
} else {
throw new TypeError("Invalid 'period' parameter");
}
}
} else {
throw new TypeError("Unknown OTP type");
}
// Label: required
// Issuer: optional
if (typeof uriParams.issuer !== "undefined") {
config.issuer = uriParams.issuer;
}
if (uriLabel.length === 2) {
config.label = uriLabel[1];
if (typeof config.issuer === "undefined" || config.issuer === "") {
config.issuer = uriLabel[0];
} else if (uriLabel[0] === "") {
config.issuerInLabel = false;
}
} else {
config.label = uriLabel[0];
if (typeof config.issuer !== "undefined" && config.issuer !== "") {
config.issuerInLabel = false;
}
}
// Secret: required
if (typeof uriParams.secret !== "undefined" && SECRET_REGEX.test(uriParams.secret)) {
config.secret = uriParams.secret;
} else {
throw new TypeError("Missing or invalid 'secret' parameter");
}
// Algorithm: optional
if (typeof uriParams.algorithm !== "undefined") {
if ((hmac ? ALGORITHM_CUSTOM_REGEX : ALGORITHM_REGEX).test(uriParams.algorithm)) {
config.algorithm = uriParams.algorithm;
} else {
throw new TypeError("Invalid 'algorithm' parameter");
}
}
// Digits: optional
if (typeof uriParams.digits !== "undefined") {
if (POSITIVE_INTEGER_REGEX.test(uriParams.digits)) {
config.digits = parseInt(uriParams.digits, 10);
} else {
throw new TypeError("Invalid 'digits' parameter");
}
}
// HMAC: optional
if (typeof hmac !== "undefined") {
config.hmac = hmac;
}
return new OTP(config);
}
/**
* Converts an HOTP/TOTP object to a Google Authenticator key URI.
* @param {HOTP|TOTP} otp HOTP/TOTP object.
* @returns {string} Google Authenticator Key URI.
*/ static stringify(otp) {
if (otp instanceof HOTP || otp instanceof TOTP) {
return otp.toString();
}
throw new TypeError("Invalid 'HOTP/TOTP' object");
}
}
/**
* Library version.
* @type {string}
*/ const version = "9.5.1";
export { HOTP, Secret, TOTP, URI, version };
@@ -0,0 +1,794 @@
import { EntityDecoder, DecodingMode, htmlDecodeTree, xmlDecodeTree, } from "entities/decode";
var CharCodes;
(function (CharCodes) {
CharCodes[CharCodes["Tab"] = 9] = "Tab";
CharCodes[CharCodes["NewLine"] = 10] = "NewLine";
CharCodes[CharCodes["FormFeed"] = 12] = "FormFeed";
CharCodes[CharCodes["CarriageReturn"] = 13] = "CarriageReturn";
CharCodes[CharCodes["Space"] = 32] = "Space";
CharCodes[CharCodes["ExclamationMark"] = 33] = "ExclamationMark";
CharCodes[CharCodes["Number"] = 35] = "Number";
CharCodes[CharCodes["Amp"] = 38] = "Amp";
CharCodes[CharCodes["SingleQuote"] = 39] = "SingleQuote";
CharCodes[CharCodes["DoubleQuote"] = 34] = "DoubleQuote";
CharCodes[CharCodes["Dash"] = 45] = "Dash";
CharCodes[CharCodes["Slash"] = 47] = "Slash";
CharCodes[CharCodes["Zero"] = 48] = "Zero";
CharCodes[CharCodes["Nine"] = 57] = "Nine";
CharCodes[CharCodes["Semi"] = 59] = "Semi";
CharCodes[CharCodes["Lt"] = 60] = "Lt";
CharCodes[CharCodes["Eq"] = 61] = "Eq";
CharCodes[CharCodes["Gt"] = 62] = "Gt";
CharCodes[CharCodes["Questionmark"] = 63] = "Questionmark";
CharCodes[CharCodes["UpperA"] = 65] = "UpperA";
CharCodes[CharCodes["LowerA"] = 97] = "LowerA";
CharCodes[CharCodes["UpperF"] = 70] = "UpperF";
CharCodes[CharCodes["LowerF"] = 102] = "LowerF";
CharCodes[CharCodes["UpperZ"] = 90] = "UpperZ";
CharCodes[CharCodes["LowerZ"] = 122] = "LowerZ";
CharCodes[CharCodes["LowerX"] = 120] = "LowerX";
CharCodes[CharCodes["OpeningSquareBracket"] = 91] = "OpeningSquareBracket";
})(CharCodes || (CharCodes = {}));
/** All the states the tokenizer can be in. */
var State;
(function (State) {
State[State["Text"] = 1] = "Text";
State[State["BeforeTagName"] = 2] = "BeforeTagName";
State[State["InTagName"] = 3] = "InTagName";
State[State["InSelfClosingTag"] = 4] = "InSelfClosingTag";
State[State["BeforeClosingTagName"] = 5] = "BeforeClosingTagName";
State[State["InClosingTagName"] = 6] = "InClosingTagName";
State[State["AfterClosingTagName"] = 7] = "AfterClosingTagName";
// Attributes
State[State["BeforeAttributeName"] = 8] = "BeforeAttributeName";
State[State["InAttributeName"] = 9] = "InAttributeName";
State[State["AfterAttributeName"] = 10] = "AfterAttributeName";
State[State["BeforeAttributeValue"] = 11] = "BeforeAttributeValue";
State[State["InAttributeValueDq"] = 12] = "InAttributeValueDq";
State[State["InAttributeValueSq"] = 13] = "InAttributeValueSq";
State[State["InAttributeValueNq"] = 14] = "InAttributeValueNq";
// Declarations
State[State["BeforeDeclaration"] = 15] = "BeforeDeclaration";
State[State["InDeclaration"] = 16] = "InDeclaration";
// Processing instructions
State[State["InProcessingInstruction"] = 17] = "InProcessingInstruction";
// Comments & CDATA
State[State["BeforeComment"] = 18] = "BeforeComment";
State[State["CDATASequence"] = 19] = "CDATASequence";
State[State["InSpecialComment"] = 20] = "InSpecialComment";
State[State["InCommentLike"] = 21] = "InCommentLike";
// Special tags
State[State["BeforeSpecialS"] = 22] = "BeforeSpecialS";
State[State["BeforeSpecialT"] = 23] = "BeforeSpecialT";
State[State["SpecialStartSequence"] = 24] = "SpecialStartSequence";
State[State["InSpecialTag"] = 25] = "InSpecialTag";
State[State["InEntity"] = 26] = "InEntity";
})(State || (State = {}));
function isWhitespace(c) {
return (c === CharCodes.Space ||
c === CharCodes.NewLine ||
c === CharCodes.Tab ||
c === CharCodes.FormFeed ||
c === CharCodes.CarriageReturn);
}
function isEndOfTagSection(c) {
return c === CharCodes.Slash || c === CharCodes.Gt || isWhitespace(c);
}
function isASCIIAlpha(c) {
return ((c >= CharCodes.LowerA && c <= CharCodes.LowerZ) ||
(c >= CharCodes.UpperA && c <= CharCodes.UpperZ));
}
export var QuoteType;
(function (QuoteType) {
QuoteType[QuoteType["NoValue"] = 0] = "NoValue";
QuoteType[QuoteType["Unquoted"] = 1] = "Unquoted";
QuoteType[QuoteType["Single"] = 2] = "Single";
QuoteType[QuoteType["Double"] = 3] = "Double";
})(QuoteType || (QuoteType = {}));
/**
* Sequences used to match longer strings.
*
* We don't have `Script`, `Style`, or `Title` here. Instead, we re-use the *End
* sequences with an increased offset.
*/
const Sequences = {
Cdata: new Uint8Array([0x43, 0x44, 0x41, 0x54, 0x41, 0x5b]), // CDATA[
CdataEnd: new Uint8Array([0x5d, 0x5d, 0x3e]), // ]]>
CommentEnd: new Uint8Array([0x2d, 0x2d, 0x3e]), // `-->`
ScriptEnd: new Uint8Array([0x3c, 0x2f, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74]), // `</script`
StyleEnd: new Uint8Array([0x3c, 0x2f, 0x73, 0x74, 0x79, 0x6c, 0x65]), // `</style`
TitleEnd: new Uint8Array([0x3c, 0x2f, 0x74, 0x69, 0x74, 0x6c, 0x65]), // `</title`
TextareaEnd: new Uint8Array([
0x3c, 0x2f, 0x74, 0x65, 0x78, 0x74, 0x61, 0x72, 0x65, 0x61,
]), // `</textarea`
XmpEnd: new Uint8Array([0x3c, 0x2f, 0x78, 0x6d, 0x70]), // `</xmp`
};
export default class Tokenizer {
constructor({ xmlMode = false, decodeEntities = true, }, cbs) {
this.cbs = cbs;
/** The current state the tokenizer is in. */
this.state = State.Text;
/** The read buffer. */
this.buffer = "";
/** The beginning of the section that is currently being read. */
this.sectionStart = 0;
/** The index within the buffer that we are currently looking at. */
this.index = 0;
/** The start of the last entity. */
this.entityStart = 0;
/** Some behavior, eg. when decoding entities, is done while we are in another state. This keeps track of the other state type. */
this.baseState = State.Text;
/** For special parsing behavior inside of script and style tags. */
this.isSpecial = false;
/** Indicates whether the tokenizer has been paused. */
this.running = true;
/** The offset of the current buffer. */
this.offset = 0;
this.currentSequence = undefined;
this.sequenceIndex = 0;
this.xmlMode = xmlMode;
this.decodeEntities = decodeEntities;
this.entityDecoder = new EntityDecoder(xmlMode ? xmlDecodeTree : htmlDecodeTree, (cp, consumed) => this.emitCodePoint(cp, consumed));
}
reset() {
this.state = State.Text;
this.buffer = "";
this.sectionStart = 0;
this.index = 0;
this.baseState = State.Text;
this.currentSequence = undefined;
this.running = true;
this.offset = 0;
}
write(chunk) {
this.offset += this.buffer.length;
this.buffer = chunk;
this.parse();
}
end() {
if (this.running)
this.finish();
}
pause() {
this.running = false;
}
resume() {
this.running = true;
if (this.index < this.buffer.length + this.offset) {
this.parse();
}
}
stateText(c) {
if (c === CharCodes.Lt ||
(!this.decodeEntities && this.fastForwardTo(CharCodes.Lt))) {
if (this.index > this.sectionStart) {
this.cbs.ontext(this.sectionStart, this.index);
}
this.state = State.BeforeTagName;
this.sectionStart = this.index;
}
else if (this.decodeEntities && c === CharCodes.Amp) {
this.startEntity();
}
}
stateSpecialStartSequence(c) {
const isEnd = this.sequenceIndex === this.currentSequence.length;
const isMatch = isEnd
? // If we are at the end of the sequence, make sure the tag name has ended
isEndOfTagSection(c)
: // Otherwise, do a case-insensitive comparison
(c | 0x20) === this.currentSequence[this.sequenceIndex];
if (!isMatch) {
this.isSpecial = false;
}
else if (!isEnd) {
this.sequenceIndex++;
return;
}
this.sequenceIndex = 0;
this.state = State.InTagName;
this.stateInTagName(c);
}
/** Look for an end tag. For <title> tags, also decode entities. */
stateInSpecialTag(c) {
if (this.sequenceIndex === this.currentSequence.length) {
if (c === CharCodes.Gt || isWhitespace(c)) {
const endOfText = this.index - this.currentSequence.length;
if (this.sectionStart < endOfText) {
// Spoof the index so that reported locations match up.
const actualIndex = this.index;
this.index = endOfText;
this.cbs.ontext(this.sectionStart, endOfText);
this.index = actualIndex;
}
this.isSpecial = false;
this.sectionStart = endOfText + 2; // Skip over the `</`
this.stateInClosingTagName(c);
return; // We are done; skip the rest of the function.
}
this.sequenceIndex = 0;
}
if ((c | 0x20) === this.currentSequence[this.sequenceIndex]) {
this.sequenceIndex += 1;
}
else if (this.sequenceIndex === 0) {
if (this.currentSequence === Sequences.TitleEnd) {
// We have to parse entities in <title> tags.
if (this.decodeEntities && c === CharCodes.Amp) {
this.startEntity();
}
}
else if (this.fastForwardTo(CharCodes.Lt)) {
// Outside of <title> tags, we can fast-forward.
this.sequenceIndex = 1;
}
}
else {
// If we see a `<`, set the sequence index to 1; useful for eg. `<</script>`.
this.sequenceIndex = Number(c === CharCodes.Lt);
}
}
stateCDATASequence(c) {
if (c === Sequences.Cdata[this.sequenceIndex]) {
if (++this.sequenceIndex === Sequences.Cdata.length) {
this.state = State.InCommentLike;
this.currentSequence = Sequences.CdataEnd;
this.sequenceIndex = 0;
this.sectionStart = this.index + 1;
}
}
else {
this.sequenceIndex = 0;
this.state = State.InDeclaration;
this.stateInDeclaration(c); // Reconsume the character
}
}
/**
* When we wait for one specific character, we can speed things up
* by skipping through the buffer until we find it.
*
* @returns Whether the character was found.
*/
fastForwardTo(c) {
while (++this.index < this.buffer.length + this.offset) {
if (this.buffer.charCodeAt(this.index - this.offset) === c) {
return true;
}
}
/*
* We increment the index at the end of the `parse` loop,
* so set it to `buffer.length - 1` here.
*
* TODO: Refactor `parse` to increment index before calling states.
*/
this.index = this.buffer.length + this.offset - 1;
return false;
}
/**
* Comments and CDATA end with `-->` and `]]>`.
*
* Their common qualities are:
* - Their end sequences have a distinct character they start with.
* - That character is then repeated, so we have to check multiple repeats.
* - All characters but the start character of the sequence can be skipped.
*/
stateInCommentLike(c) {
if (c === this.currentSequence[this.sequenceIndex]) {
if (++this.sequenceIndex === this.currentSequence.length) {
if (this.currentSequence === Sequences.CdataEnd) {
this.cbs.oncdata(this.sectionStart, this.index, 2);
}
else {
this.cbs.oncomment(this.sectionStart, this.index, 2);
}
this.sequenceIndex = 0;
this.sectionStart = this.index + 1;
this.state = State.Text;
}
}
else if (this.sequenceIndex === 0) {
// Fast-forward to the first character of the sequence
if (this.fastForwardTo(this.currentSequence[0])) {
this.sequenceIndex = 1;
}
}
else if (c !== this.currentSequence[this.sequenceIndex - 1]) {
// Allow long sequences, eg. --->, ]]]>
this.sequenceIndex = 0;
}
}
/**
* HTML only allows ASCII alpha characters (a-z and A-Z) at the beginning of a tag name.
*
* XML allows a lot more characters here (@see https://www.w3.org/TR/REC-xml/#NT-NameStartChar).
* We allow anything that wouldn't end the tag.
*/
isTagStartChar(c) {
return this.xmlMode ? !isEndOfTagSection(c) : isASCIIAlpha(c);
}
startSpecial(sequence, offset) {
this.isSpecial = true;
this.currentSequence = sequence;
this.sequenceIndex = offset;
this.state = State.SpecialStartSequence;
}
stateBeforeTagName(c) {
if (c === CharCodes.ExclamationMark) {
this.state = State.BeforeDeclaration;
this.sectionStart = this.index + 1;
}
else if (c === CharCodes.Questionmark) {
this.state = State.InProcessingInstruction;
this.sectionStart = this.index + 1;
}
else if (this.isTagStartChar(c)) {
const lower = c | 0x20;
this.sectionStart = this.index;
if (this.xmlMode) {
this.state = State.InTagName;
}
else if (lower === Sequences.ScriptEnd[2]) {
this.state = State.BeforeSpecialS;
}
else if (lower === Sequences.TitleEnd[2] ||
lower === Sequences.XmpEnd[2]) {
this.state = State.BeforeSpecialT;
}
else {
this.state = State.InTagName;
}
}
else if (c === CharCodes.Slash) {
this.state = State.BeforeClosingTagName;
}
else {
this.state = State.Text;
this.stateText(c);
}
}
stateInTagName(c) {
if (isEndOfTagSection(c)) {
this.cbs.onopentagname(this.sectionStart, this.index);
this.sectionStart = -1;
this.state = State.BeforeAttributeName;
this.stateBeforeAttributeName(c);
}
}
stateBeforeClosingTagName(c) {
if (isWhitespace(c)) {
// Ignore
}
else if (c === CharCodes.Gt) {
this.state = State.Text;
}
else {
this.state = this.isTagStartChar(c)
? State.InClosingTagName
: State.InSpecialComment;
this.sectionStart = this.index;
}
}
stateInClosingTagName(c) {
if (c === CharCodes.Gt || isWhitespace(c)) {
this.cbs.onclosetag(this.sectionStart, this.index);
this.sectionStart = -1;
this.state = State.AfterClosingTagName;
this.stateAfterClosingTagName(c);
}
}
stateAfterClosingTagName(c) {
// Skip everything until ">"
if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) {
this.state = State.Text;
this.sectionStart = this.index + 1;
}
}
stateBeforeAttributeName(c) {
if (c === CharCodes.Gt) {
this.cbs.onopentagend(this.index);
if (this.isSpecial) {
this.state = State.InSpecialTag;
this.sequenceIndex = 0;
}
else {
this.state = State.Text;
}
this.sectionStart = this.index + 1;
}
else if (c === CharCodes.Slash) {
this.state = State.InSelfClosingTag;
}
else if (!isWhitespace(c)) {
this.state = State.InAttributeName;
this.sectionStart = this.index;
}
}
stateInSelfClosingTag(c) {
if (c === CharCodes.Gt) {
this.cbs.onselfclosingtag(this.index);
this.state = State.Text;
this.sectionStart = this.index + 1;
this.isSpecial = false; // Reset special state, in case of self-closing special tags
}
else if (!isWhitespace(c)) {
this.state = State.BeforeAttributeName;
this.stateBeforeAttributeName(c);
}
}
stateInAttributeName(c) {
if (c === CharCodes.Eq || isEndOfTagSection(c)) {
this.cbs.onattribname(this.sectionStart, this.index);
this.sectionStart = this.index;
this.state = State.AfterAttributeName;
this.stateAfterAttributeName(c);
}
}
stateAfterAttributeName(c) {
if (c === CharCodes.Eq) {
this.state = State.BeforeAttributeValue;
}
else if (c === CharCodes.Slash || c === CharCodes.Gt) {
this.cbs.onattribend(QuoteType.NoValue, this.sectionStart);
this.sectionStart = -1;
this.state = State.BeforeAttributeName;
this.stateBeforeAttributeName(c);
}
else if (!isWhitespace(c)) {
this.cbs.onattribend(QuoteType.NoValue, this.sectionStart);
this.state = State.InAttributeName;
this.sectionStart = this.index;
}
}
stateBeforeAttributeValue(c) {
if (c === CharCodes.DoubleQuote) {
this.state = State.InAttributeValueDq;
this.sectionStart = this.index + 1;
}
else if (c === CharCodes.SingleQuote) {
this.state = State.InAttributeValueSq;
this.sectionStart = this.index + 1;
}
else if (!isWhitespace(c)) {
this.sectionStart = this.index;
this.state = State.InAttributeValueNq;
this.stateInAttributeValueNoQuotes(c); // Reconsume token
}
}
handleInAttributeValue(c, quote) {
if (c === quote ||
(!this.decodeEntities && this.fastForwardTo(quote))) {
this.cbs.onattribdata(this.sectionStart, this.index);
this.sectionStart = -1;
this.cbs.onattribend(quote === CharCodes.DoubleQuote
? QuoteType.Double
: QuoteType.Single, this.index + 1);
this.state = State.BeforeAttributeName;
}
else if (this.decodeEntities && c === CharCodes.Amp) {
this.startEntity();
}
}
stateInAttributeValueDoubleQuotes(c) {
this.handleInAttributeValue(c, CharCodes.DoubleQuote);
}
stateInAttributeValueSingleQuotes(c) {
this.handleInAttributeValue(c, CharCodes.SingleQuote);
}
stateInAttributeValueNoQuotes(c) {
if (isWhitespace(c) || c === CharCodes.Gt) {
this.cbs.onattribdata(this.sectionStart, this.index);
this.sectionStart = -1;
this.cbs.onattribend(QuoteType.Unquoted, this.index);
this.state = State.BeforeAttributeName;
this.stateBeforeAttributeName(c);
}
else if (this.decodeEntities && c === CharCodes.Amp) {
this.startEntity();
}
}
stateBeforeDeclaration(c) {
if (c === CharCodes.OpeningSquareBracket) {
this.state = State.CDATASequence;
this.sequenceIndex = 0;
}
else {
this.state =
c === CharCodes.Dash
? State.BeforeComment
: State.InDeclaration;
}
}
stateInDeclaration(c) {
if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) {
this.cbs.ondeclaration(this.sectionStart, this.index);
this.state = State.Text;
this.sectionStart = this.index + 1;
}
}
stateInProcessingInstruction(c) {
if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) {
this.cbs.onprocessinginstruction(this.sectionStart, this.index);
this.state = State.Text;
this.sectionStart = this.index + 1;
}
}
stateBeforeComment(c) {
if (c === CharCodes.Dash) {
this.state = State.InCommentLike;
this.currentSequence = Sequences.CommentEnd;
// Allow short comments (eg. <!-->)
this.sequenceIndex = 2;
this.sectionStart = this.index + 1;
}
else {
this.state = State.InDeclaration;
}
}
stateInSpecialComment(c) {
if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) {
this.cbs.oncomment(this.sectionStart, this.index, 0);
this.state = State.Text;
this.sectionStart = this.index + 1;
}
}
stateBeforeSpecialS(c) {
const lower = c | 0x20;
if (lower === Sequences.ScriptEnd[3]) {
this.startSpecial(Sequences.ScriptEnd, 4);
}
else if (lower === Sequences.StyleEnd[3]) {
this.startSpecial(Sequences.StyleEnd, 4);
}
else {
this.state = State.InTagName;
this.stateInTagName(c); // Consume the token again
}
}
stateBeforeSpecialT(c) {
const lower = c | 0x20;
switch (lower) {
case Sequences.TitleEnd[3]: {
this.startSpecial(Sequences.TitleEnd, 4);
break;
}
case Sequences.TextareaEnd[3]: {
this.startSpecial(Sequences.TextareaEnd, 4);
break;
}
case Sequences.XmpEnd[3]: {
this.startSpecial(Sequences.XmpEnd, 4);
break;
}
default: {
this.state = State.InTagName;
this.stateInTagName(c); // Consume the token again
}
}
}
startEntity() {
this.baseState = this.state;
this.state = State.InEntity;
this.entityStart = this.index;
this.entityDecoder.startEntity(this.xmlMode
? DecodingMode.Strict
: this.baseState === State.Text ||
this.baseState === State.InSpecialTag
? DecodingMode.Legacy
: DecodingMode.Attribute);
}
stateInEntity() {
const length = this.entityDecoder.write(this.buffer, this.index - this.offset);
// If `length` is positive, we are done with the entity.
if (length >= 0) {
this.state = this.baseState;
if (length === 0) {
this.index = this.entityStart;
}
}
else {
// Mark buffer as consumed.
this.index = this.offset + this.buffer.length - 1;
}
}
/**
* Remove data that has already been consumed from the buffer.
*/
cleanup() {
// If we are inside of text or attributes, emit what we already have.
if (this.running && this.sectionStart !== this.index) {
if (this.state === State.Text ||
(this.state === State.InSpecialTag && this.sequenceIndex === 0)) {
this.cbs.ontext(this.sectionStart, this.index);
this.sectionStart = this.index;
}
else if (this.state === State.InAttributeValueDq ||
this.state === State.InAttributeValueSq ||
this.state === State.InAttributeValueNq) {
this.cbs.onattribdata(this.sectionStart, this.index);
this.sectionStart = this.index;
}
}
}
shouldContinue() {
return this.index < this.buffer.length + this.offset && this.running;
}
/**
* Iterates through the buffer, calling the function corresponding to the current state.
*
* States that are more likely to be hit are higher up, as a performance improvement.
*/
parse() {
while (this.shouldContinue()) {
const c = this.buffer.charCodeAt(this.index - this.offset);
switch (this.state) {
case State.Text: {
this.stateText(c);
break;
}
case State.SpecialStartSequence: {
this.stateSpecialStartSequence(c);
break;
}
case State.InSpecialTag: {
this.stateInSpecialTag(c);
break;
}
case State.CDATASequence: {
this.stateCDATASequence(c);
break;
}
case State.InAttributeValueDq: {
this.stateInAttributeValueDoubleQuotes(c);
break;
}
case State.InAttributeName: {
this.stateInAttributeName(c);
break;
}
case State.InCommentLike: {
this.stateInCommentLike(c);
break;
}
case State.InSpecialComment: {
this.stateInSpecialComment(c);
break;
}
case State.BeforeAttributeName: {
this.stateBeforeAttributeName(c);
break;
}
case State.InTagName: {
this.stateInTagName(c);
break;
}
case State.InClosingTagName: {
this.stateInClosingTagName(c);
break;
}
case State.BeforeTagName: {
this.stateBeforeTagName(c);
break;
}
case State.AfterAttributeName: {
this.stateAfterAttributeName(c);
break;
}
case State.InAttributeValueSq: {
this.stateInAttributeValueSingleQuotes(c);
break;
}
case State.BeforeAttributeValue: {
this.stateBeforeAttributeValue(c);
break;
}
case State.BeforeClosingTagName: {
this.stateBeforeClosingTagName(c);
break;
}
case State.AfterClosingTagName: {
this.stateAfterClosingTagName(c);
break;
}
case State.BeforeSpecialS: {
this.stateBeforeSpecialS(c);
break;
}
case State.BeforeSpecialT: {
this.stateBeforeSpecialT(c);
break;
}
case State.InAttributeValueNq: {
this.stateInAttributeValueNoQuotes(c);
break;
}
case State.InSelfClosingTag: {
this.stateInSelfClosingTag(c);
break;
}
case State.InDeclaration: {
this.stateInDeclaration(c);
break;
}
case State.BeforeDeclaration: {
this.stateBeforeDeclaration(c);
break;
}
case State.BeforeComment: {
this.stateBeforeComment(c);
break;
}
case State.InProcessingInstruction: {
this.stateInProcessingInstruction(c);
break;
}
case State.InEntity: {
this.stateInEntity();
break;
}
}
this.index++;
}
this.cleanup();
}
finish() {
if (this.state === State.InEntity) {
this.entityDecoder.end();
this.state = this.baseState;
}
this.handleTrailingData();
this.cbs.onend();
}
/** Handle any trailing data. */
handleTrailingData() {
const endIndex = this.buffer.length + this.offset;
// If there is no remaining data, we are done.
if (this.sectionStart >= endIndex) {
return;
}
if (this.state === State.InCommentLike) {
if (this.currentSequence === Sequences.CdataEnd) {
this.cbs.oncdata(this.sectionStart, endIndex, 0);
}
else {
this.cbs.oncomment(this.sectionStart, endIndex, 0);
}
}
else if (this.state === State.InTagName ||
this.state === State.BeforeAttributeName ||
this.state === State.BeforeAttributeValue ||
this.state === State.AfterAttributeName ||
this.state === State.InAttributeName ||
this.state === State.InAttributeValueSq ||
this.state === State.InAttributeValueDq ||
this.state === State.InAttributeValueNq ||
this.state === State.InClosingTagName) {
/*
* If we are currently in an opening or closing tag, us not calling the
* respective callback signals that the tag should be ignored.
*/
}
else {
this.cbs.ontext(this.sectionStart, endIndex);
}
}
emitCodePoint(cp, consumed) {
if (this.baseState !== State.Text &&
this.baseState !== State.InSpecialTag) {
if (this.sectionStart < this.entityStart) {
this.cbs.onattribdata(this.sectionStart, this.entityStart);
}
this.sectionStart = this.entityStart + consumed;
this.index = this.sectionStart - 1;
this.cbs.onattribentity(cp);
}
else {
if (this.sectionStart < this.entityStart) {
this.cbs.ontext(this.sectionStart, this.entityStart);
}
this.sectionStart = this.entityStart + consumed;
this.index = this.sectionStart - 1;
this.cbs.ontextentity(cp, this.sectionStart);
}
}
}
//# sourceMappingURL=Tokenizer.js.map
@@ -0,0 +1,15 @@
var test = require('tape');
var inspect = require('../');
var xs = ['a', 'b'];
xs[5] = 'f';
xs[7] = 'j';
xs[8] = 'k';
test('holes', function (t) {
t.plan(1);
t.equal(
inspect(xs),
"[ 'a', 'b', , , , 'f', , 'j', 'k' ]"
);
});
@@ -0,0 +1,469 @@
import * as React from 'react'
import { useStore } from '@tanstack/react-store'
import {
deepEqual,
escapeHtml,
getAssetCrossOrigin,
isInlinableStylesheet,
resolveManifestAssetLink,
} from '@tanstack/router-core'
import { isServer } from '@tanstack/router-core/isServer'
import { useRouter } from './useRouter'
import type {
AssetCrossOriginConfig,
RouterManagedTag,
} from '@tanstack/router-core'
function buildTagsFromMatches(
router: ReturnType<typeof useRouter>,
nonce: string | undefined,
matches: Array<any>,
assetCrossOrigin?: AssetCrossOriginConfig,
): Array<RouterManagedTag> {
const routeMeta = matches.map((match) => match.meta!).filter(Boolean)
const resultMeta: Array<RouterManagedTag> = []
const metaByAttribute: Record<string, true> = {}
let title: RouterManagedTag | undefined
for (let i = routeMeta.length - 1; i >= 0; i--) {
const metas = routeMeta[i]!
for (let j = metas.length - 1; j >= 0; j--) {
const m = metas[j]
if (!m) continue
if (m.title) {
if (!title) {
title = {
tag: 'title',
children: m.title,
}
}
} else if ('script:ld+json' in m) {
try {
const json = JSON.stringify(m['script:ld+json'])
resultMeta.push({
tag: 'script',
attrs: {
type: 'application/ld+json',
},
children: escapeHtml(json),
})
} catch {
// Skip invalid JSON-LD objects
}
} else {
const attribute = m.name ?? m.property
if (attribute) {
if (metaByAttribute[attribute]) {
continue
} else {
metaByAttribute[attribute] = true
}
}
resultMeta.push({
tag: 'meta',
attrs: {
...m,
nonce,
},
})
}
}
}
if (title) {
resultMeta.push(title)
}
if (nonce) {
resultMeta.push({
tag: 'meta',
attrs: {
property: 'csp-nonce',
content: nonce,
},
})
}
resultMeta.reverse()
const constructedLinks = matches
.map((match) => match.links!)
.filter(Boolean)
.flat(1)
.map((link) => ({
tag: 'link',
attrs: {
...link,
nonce,
},
})) satisfies Array<RouterManagedTag>
const manifest = router.ssr?.manifest
const assetLinks = matches
.map((match) => manifest?.routes[match.routeId]?.assets ?? [])
.filter(Boolean)
.flat(1)
.flatMap((asset): Array<RouterManagedTag> => {
if (asset.tag === 'link') {
if (isInlinableStylesheet(manifest, asset)) {
return []
}
return [
{
tag: 'link',
attrs: {
...asset.attrs,
crossOrigin:
getAssetCrossOrigin(assetCrossOrigin, 'stylesheet') ??
asset.attrs?.crossOrigin,
suppressHydrationWarning: true,
nonce,
},
},
]
}
if (asset.tag === 'style') {
return [
{
tag: 'style',
attrs: {
...asset.attrs,
nonce,
},
children: asset.children,
...(asset.inlineCss ? { inlineCss: true as const } : {}),
},
]
}
return []
})
const preloadLinks: Array<RouterManagedTag> = []
matches
.map((match) => router.looseRoutesById[match.routeId]!)
.forEach((route) =>
router.ssr?.manifest?.routes[route.id]?.preloads
?.filter(Boolean)
.forEach((preload) => {
const preloadLink = resolveManifestAssetLink(preload)
preloadLinks.push({
tag: 'link',
attrs: {
rel: 'modulepreload',
href: preloadLink.href,
crossOrigin:
getAssetCrossOrigin(assetCrossOrigin, 'modulepreload') ??
preloadLink.crossOrigin,
nonce,
},
})
}),
)
const styles = (
matches
.map((match) => match.styles!)
.flat(1)
.filter(Boolean) as Array<RouterManagedTag>
).map(({ children, ...attrs }) => ({
tag: 'style',
attrs: {
...attrs,
nonce,
},
children,
}))
const headScripts = (
matches
.map((match) => match.headScripts!)
.flat(1)
.filter(Boolean) as Array<RouterManagedTag>
).map(({ children, ...script }) => ({
tag: 'script',
attrs: {
...script,
nonce,
},
children,
}))
return uniqBy(
[
...resultMeta,
...preloadLinks,
...constructedLinks,
...assetLinks,
...styles,
...headScripts,
] as Array<RouterManagedTag>,
(d) => JSON.stringify(d),
)
}
/**
* Build the list of head/link/meta/script tags to render for active matches.
* Used internally by `HeadContent`.
*/
export const useTags = (assetCrossOrigin?: AssetCrossOriginConfig) => {
const router = useRouter()
const nonce = router.options.ssr?.nonce
if (isServer ?? router.isServer) {
return buildTagsFromMatches(
router,
nonce,
router.stores.matches.get(),
assetCrossOrigin,
)
}
// eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
const routeMeta = useStore(
router.stores.matches,
(matches) => {
return matches.map((match) => match.meta!).filter(Boolean)
},
deepEqual,
)
// eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
const meta: Array<RouterManagedTag> = React.useMemo(() => {
const resultMeta: Array<RouterManagedTag> = []
const metaByAttribute: Record<string, true> = {}
let title: RouterManagedTag | undefined
for (let i = routeMeta.length - 1; i >= 0; i--) {
const metas = routeMeta[i]!
for (let j = metas.length - 1; j >= 0; j--) {
const m = metas[j]
if (!m) continue
if (m.title) {
if (!title) {
title = {
tag: 'title',
children: m.title,
}
}
} else if ('script:ld+json' in m) {
// Handle JSON-LD structured data
// Content is HTML-escaped to prevent XSS when injected via dangerouslySetInnerHTML
try {
const json = JSON.stringify(m['script:ld+json'])
resultMeta.push({
tag: 'script',
attrs: {
type: 'application/ld+json',
},
children: escapeHtml(json),
})
} catch {
// Skip invalid JSON-LD objects
}
} else {
const attribute = m.name ?? m.property
if (attribute) {
if (metaByAttribute[attribute]) {
continue
} else {
metaByAttribute[attribute] = true
}
}
resultMeta.push({
tag: 'meta',
attrs: {
...m,
nonce,
},
})
}
}
}
if (title) {
resultMeta.push(title)
}
if (nonce) {
resultMeta.push({
tag: 'meta',
attrs: {
property: 'csp-nonce',
content: nonce,
},
})
}
resultMeta.reverse()
return resultMeta
}, [routeMeta, nonce])
// eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
const links = useStore(
router.stores.matches,
(matches) => {
const constructed = matches
.map((match) => match.links!)
.filter(Boolean)
.flat(1)
.map((link) => ({
tag: 'link',
attrs: {
...link,
nonce,
},
})) satisfies Array<RouterManagedTag>
const manifest = router.ssr?.manifest
// These are the assets extracted from the ViteManifest
// using the `startManifestPlugin`
const assets = matches
.map((match) => manifest?.routes[match.routeId]?.assets ?? [])
.filter(Boolean)
.flat(1)
.flatMap((asset): Array<RouterManagedTag> => {
if (asset.tag === 'link') {
if (isInlinableStylesheet(manifest, asset)) {
return []
}
return [
{
tag: 'link',
attrs: {
...asset.attrs,
crossOrigin:
getAssetCrossOrigin(assetCrossOrigin, 'stylesheet') ??
asset.attrs?.crossOrigin,
suppressHydrationWarning: true,
nonce,
},
},
]
}
if (asset.tag === 'style') {
return [
{
tag: 'style',
attrs: {
...asset.attrs,
nonce,
},
children: asset.children,
...(asset.inlineCss ? { inlineCss: true as const } : {}),
},
]
}
return []
})
return [...constructed, ...assets]
},
deepEqual,
)
// eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
const preloadLinks = useStore(
router.stores.matches,
(matches) => {
const preloadLinks: Array<RouterManagedTag> = []
matches
.map((match) => router.looseRoutesById[match.routeId]!)
.forEach((route) =>
router.ssr?.manifest?.routes[route.id]?.preloads
?.filter(Boolean)
.forEach((preload) => {
const preloadLink = resolveManifestAssetLink(preload)
preloadLinks.push({
tag: 'link',
attrs: {
rel: 'modulepreload',
href: preloadLink.href,
crossOrigin:
getAssetCrossOrigin(assetCrossOrigin, 'modulepreload') ??
preloadLink.crossOrigin,
nonce,
},
})
}),
)
return preloadLinks
},
deepEqual,
)
// eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
const styles = useStore(
router.stores.matches,
(matches) =>
(
matches
.map((match) => match.styles!)
.flat(1)
.filter(Boolean) as Array<RouterManagedTag>
).map(({ children, ...attrs }) => ({
tag: 'style',
attrs: {
...attrs,
nonce,
},
children,
})),
deepEqual,
)
// eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
const headScripts: Array<RouterManagedTag> = useStore(
router.stores.matches,
(matches) =>
(
matches
.map((match) => match.headScripts!)
.flat(1)
.filter(Boolean) as Array<RouterManagedTag>
).map(({ children, ...script }) => ({
tag: 'script',
attrs: {
...script,
nonce,
},
children,
})),
deepEqual,
)
return uniqBy(
[
...meta,
...preloadLinks,
...links,
...styles,
...headScripts,
] as Array<RouterManagedTag>,
(d) => {
return JSON.stringify(d)
},
)
}
export function uniqBy<T>(arr: Array<T>, fn: (item: T) => string) {
const seen = new Set<string>()
return arr.filter((item) => {
const key = fn(item)
if (seen.has(key)) {
return false
}
seen.add(key)
return true
})
}
@@ -0,0 +1,37 @@
'use strict';
var metaSchema = require('./refs/json-schema-draft-07.json');
module.exports = {
$id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js',
definitions: {
simpleTypes: metaSchema.definitions.simpleTypes
},
type: 'object',
dependencies: {
schema: ['validate'],
$data: ['validate'],
statements: ['inline'],
valid: {not: {required: ['macro']}}
},
properties: {
type: metaSchema.properties.type,
schema: {type: 'boolean'},
statements: {type: 'boolean'},
dependencies: {
type: 'array',
items: {type: 'string'}
},
metaSchema: {type: 'object'},
modifying: {type: 'boolean'},
valid: {type: 'boolean'},
$data: {type: 'boolean'},
async: {type: 'boolean'},
errors: {
anyOf: [
{type: 'boolean'},
{const: 'full'}
]
}
}
};
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,mDAAmD;AACnD,oBAAY,WAAW;IACnB,8CAA8C;IAC9C,IAAI,SAAS;IACb,oBAAoB;IACpB,IAAI,SAAS;IACb,yBAAyB;IACzB,SAAS,cAAc;IACvB,4BAA4B;IAC5B,OAAO,YAAY;IACnB,6BAA6B;IAC7B,MAAM,WAAW;IACjB,4BAA4B;IAC5B,KAAK,UAAU;IACf,uBAAuB;IACvB,GAAG,QAAQ;IACX,iCAAiC;IACjC,KAAK,UAAU;IACf,8BAA8B;IAC9B,OAAO,YAAY;CACtB;AAED;;;;GAIG;AACH,wBAAgB,KAAK,CAAC,IAAI,EAAE;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,GAAG,OAAO,CAM1D;AAGD,8CAA8C;AAC9C,eAAO,MAAM,IAAI,mBAAmB,CAAC;AACrC,oBAAoB;AACpB,eAAO,MAAM,IAAI,mBAAmB,CAAC;AACrC,yBAAyB;AACzB,eAAO,MAAM,SAAS,wBAAwB,CAAC;AAC/C,4BAA4B;AAC5B,eAAO,MAAM,OAAO,sBAAsB,CAAC;AAC3C,6BAA6B;AAC7B,eAAO,MAAM,MAAM,qBAAqB,CAAC;AACzC,4BAA4B;AAC5B,eAAO,MAAM,KAAK,oBAAoB,CAAC;AACvC,uBAAuB;AACvB,eAAO,MAAM,GAAG,kBAAkB,CAAC;AACnC,iCAAiC;AACjC,eAAO,MAAM,KAAK,oBAAoB,CAAC;AACvC,8BAA8B;AAC9B,eAAO,MAAM,OAAO,sBAAsB,CAAC"}
@@ -0,0 +1 @@
{"version":3,"file":"lamp-ceiling.js","sources":["../../../src/icons/lamp-ceiling.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name LampCeiling\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMTIgMnY1IiAvPgogIDxwYXRoIGQ9Ik02IDdoMTJsNCA5SDJsNC05WiIgLz4KICA8cGF0aCBkPSJNOS4xNyAxNmEzIDMgMCAxIDAgNS42NiAwIiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/lamp-ceiling\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 LampCeiling = createLucideIcon('LampCeiling', [\n ['path', { d: 'M12 2v5', key: 'nd4vlx' }],\n ['path', { d: 'M6 7h12l4 9H2l4-9Z', key: '123d64' }],\n ['path', { d: 'M9.17 16a3 3 0 1 0 5.66 0', key: '1061mw' }],\n]);\n\nexport default LampCeiling;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAc,iBAAiB,aAAe,CAAA,CAAA,CAAA;AAAA,CAAA,CAClD,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,CAAsB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACnD,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,82 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const DescriptionFileUtils = require("./DescriptionFileUtils");
/** @typedef {import("./Resolver")} Resolver */
/** @typedef {import("./Resolver").JsonObject} JsonObject */
/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
const slashCode = "/".charCodeAt(0);
module.exports = class SelfReferencePlugin {
/**
* @param {string | ResolveStepHook} source source
* @param {string | string[]} fieldNamePath name path
* @param {string | ResolveStepHook} target target
*/
constructor(source, fieldNamePath, target) {
this.source = source;
this.target = target;
this.fieldName = fieldNamePath;
}
/**
* @param {Resolver} resolver the resolver
* @returns {void}
*/
apply(resolver) {
const target = resolver.ensureHook(this.target);
resolver
.getHook(this.source)
.tapAsync("SelfReferencePlugin", (request, resolveContext, callback) => {
if (!request.descriptionFilePath) return callback();
const req = request.request;
if (!req) return callback();
// Feature is only enabled when an exports field is present
const exportsField = DescriptionFileUtils.getField(
/** @type {JsonObject} */ (request.descriptionFileData),
this.fieldName,
);
if (!exportsField) return callback();
const name = DescriptionFileUtils.getField(
/** @type {JsonObject} */ (request.descriptionFileData),
"name",
);
if (typeof name !== "string") return callback();
if (
req.startsWith(name) &&
(req.length === name.length ||
req.charCodeAt(name.length) === slashCode)
) {
const remainingRequest = `.${req.slice(name.length)}`;
/** @type {ResolveRequest} */
const obj = {
...request,
request: remainingRequest,
path: /** @type {string} */ (request.descriptionFileRoot),
relativePath: ".",
};
resolver.doResolve(
target,
obj,
"self reference",
resolveContext,
callback,
);
} else {
return callback();
}
});
}
};
@@ -0,0 +1 @@
export type { DebugLevel, EcmaVersion, ParserOptions, SourceType, } from '@typescript-eslint/types';
@@ -0,0 +1,20 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_RouterServer = require("./RouterServer.cjs");
const require_renderRouterToString = require("./renderRouterToString.cjs");
const require_defaultRenderHandler = require("./defaultRenderHandler.cjs");
const require_renderRouterToStream = require("./renderRouterToStream.cjs");
const require_defaultStreamHandler = require("./defaultStreamHandler.cjs");
exports.RouterServer = require_RouterServer.RouterServer;
exports.defaultRenderHandler = require_defaultRenderHandler.defaultRenderHandler;
exports.defaultStreamHandler = require_defaultStreamHandler.defaultStreamHandler;
exports.renderRouterToStream = require_renderRouterToStream.renderRouterToStream;
exports.renderRouterToString = require_renderRouterToString.renderRouterToString;
var _tanstack_router_core_ssr_server = require("@tanstack/router-core/ssr/server");
Object.keys(_tanstack_router_core_ssr_server).forEach(function(k) {
if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function() {
return _tanstack_router_core_ssr_server[k];
}
});
});
@@ -0,0 +1,65 @@
import { F as isDecimalIntegerNumericToken, f as createRule, g as import_ast_utils } from "../utils.js";
var dot_location_default = createRule({
name: "dot-location",
meta: {
type: "layout",
docs: { description: "Enforce consistent newlines before and after dots" },
fixable: "code",
schema: [{
type: "string",
enum: ["object", "property"]
}],
defaultOptions: ["object"],
messages: {
expectedDotAfterObject: "Expected dot to be on same line as object.",
expectedDotBeforeProperty: "Expected dot to be on same line as property."
}
},
create(context, [config]) {
const onObject = config === "object";
const sourceCode = context.sourceCode;
function getProperty(node) {
if (node.type === "TSImportType") return node.qualifier;
if (node.type === "TSQualifiedName") return node.right;
return node.property;
}
function checkDotLocation(node) {
const property = getProperty(node);
if (!property) return;
const dotToken = sourceCode.getTokenBefore(property);
if (!dotToken) return;
if (onObject) {
const tokenBeforeDot = sourceCode.getTokenBefore(dotToken);
if (tokenBeforeDot && !(0, import_ast_utils.isTokenOnSameLine)(tokenBeforeDot, dotToken)) context.report({
node,
loc: dotToken.loc,
messageId: "expectedDotAfterObject",
*fix(fixer) {
if (dotToken.value.startsWith(".") && isDecimalIntegerNumericToken(tokenBeforeDot)) yield fixer.insertTextAfter(tokenBeforeDot, ` ${dotToken.value}`);
else yield fixer.insertTextAfter(tokenBeforeDot, dotToken.value);
yield fixer.remove(dotToken);
}
});
} else if (!(0, import_ast_utils.isTokenOnSameLine)(dotToken, property)) context.report({
node,
loc: dotToken.loc,
messageId: "expectedDotBeforeProperty",
*fix(fixer) {
yield fixer.remove(dotToken);
yield fixer.insertTextBefore(property, dotToken.value);
}
});
}
return {
MemberExpression(node) {
if (node.computed) return;
checkDotLocation(node);
},
MetaProperty: checkDotLocation,
JSXMemberExpression: checkDotLocation,
TSQualifiedName: checkDotLocation,
TSImportType: checkDotLocation
};
}
});
export { dot_location_default as t };
@@ -0,0 +1,43 @@
export { default as add } from './add';
export { default as addDays } from './addDays';
export { default as addHours } from './addHours';
export { default as addMilliseconds } from './addMilliseconds';
export { default as addMinutes } from './addMinutes';
export { default as addMonths } from './addMonths';
export { default as addSeconds } from './addSeconds';
export { default as addYears } from './addYears';
export { default as compile } from './compile';
export { default as dayOfYear } from './dayOfYear';
export { default as daysInMonth } from './daysInMonth';
export { default as diff } from './diff';
export { default as diffInDays } from './diffInDays';
export { default as diffInHours } from './diffInHours';
export { default as diffInMilliseconds } from './diffInMilliseconds';
export { default as diffInMinutes } from './diffInMinutes';
export { default as diffInMonths } from './diffInMonths';
export { default as diffInSeconds } from './diffInSeconds';
export { default as diffInYears } from './diffInYears';
export { default as endOf } from './endOf';
export { default as format } from './format';
export { default as get } from './get';
export { default as isAfter } from './isAfter';
export { default as isBefore } from './isBefore';
export { default as isBetween } from './isBetween';
export { default as isLeapYear } from './isLeapYear';
export { default as isSame } from './isSame';
export { default as isSameOrAfter } from './isSameOrAfter';
export { default as isSameOrBefore } from './isSameOrBefore';
export { default as isValid } from './isValid';
export { default as parse } from './parse';
export { default as set } from './set';
export { default as startOf } from './startOf';
export { default as subDays } from './subDays';
export { default as subHours } from './subHours';
export { default as subMilliseconds } from './subMilliseconds';
export { default as subMinutes } from './subMinutes';
export { default as subMonths } from './subMonths';
export { default as subSeconds } from './subSeconds';
export { default as subYears } from './subYears';
export { default as subtract } from './subtract';
export { default as units } from './units';
export * from './types';
@@ -0,0 +1,93 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
exports.default = (0, util_1.createRule)({
name: 'no-non-null-assertion',
meta: {
type: 'problem',
docs: {
description: 'Disallow non-null assertions using the `!` postfix operator',
recommended: 'strict',
},
hasSuggestions: true,
messages: {
noNonNull: 'Forbidden non-null assertion.',
suggestOptionalChain: 'Consider using the optional chain operator `?.` instead. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator.',
},
schema: [],
},
defaultOptions: [],
create(context) {
return {
TSNonNullExpression(node) {
const suggest = [];
// it always exists in non-null assertion
const nonNullOperator = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(node.expression, util_1.isNonNullAssertionPunctuator), util_1.NullThrowsReasons.MissingToken('!', 'expression'));
function replaceTokenWithOptional() {
return fixer => fixer.replaceText(nonNullOperator, '?.');
}
function removeToken() {
return fixer => fixer.remove(nonNullOperator);
}
if (node.parent.type === utils_1.AST_NODE_TYPES.MemberExpression &&
node.parent.object === node &&
!(0, util_1.isAssignee)(node.parent)) {
if (!node.parent.optional) {
if (node.parent.computed) {
// it is x![y]?.z
suggest.push({
messageId: 'suggestOptionalChain',
fix: replaceTokenWithOptional(),
});
}
else {
// it is x!.y?.z
suggest.push({
messageId: 'suggestOptionalChain',
fix(fixer) {
// x!.y?.z
// ^ punctuator
const punctuator = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(nonNullOperator), util_1.NullThrowsReasons.MissingToken('.', '!'));
return [
fixer.remove(nonNullOperator),
fixer.insertTextBefore(punctuator, '?'),
];
},
});
}
}
else {
// it is x!?.[y].z or x!?.y.z
suggest.push({
messageId: 'suggestOptionalChain',
fix: removeToken(),
});
}
}
else if (node.parent.type === utils_1.AST_NODE_TYPES.CallExpression &&
node.parent.callee === node) {
if (!node.parent.optional) {
// it is x.y?.z!()
suggest.push({
messageId: 'suggestOptionalChain',
fix: replaceTokenWithOptional(),
});
}
else {
// it is x.y.z!?.()
suggest.push({
messageId: 'suggestOptionalChain',
fix: removeToken(),
});
}
}
context.report({
node,
messageId: 'noNonNull',
suggest,
});
},
};
},
});
@@ -0,0 +1,149 @@
import { randomUUID } from 'node:crypto';
import { McpServer } from '../../server/mcp.js';
import { createMcpExpressApp } from '../../server/express.js';
import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js';
import { isInitializeRequest } from '../../types.js';
import { InMemoryEventStore } from '../shared/inMemoryEventStore.js';
import cors from 'cors';
// Factory to create a new MCP server per session.
// Each session needs its own server+transport pair to avoid cross-session contamination.
const getServer = () => {
const server = new McpServer({
name: 'sse-polling-example',
version: '1.0.0'
}, {
capabilities: { logging: {} }
});
// Register a long-running tool that demonstrates server-initiated disconnect
server.tool('long-task', 'A long-running task that sends progress updates. Server will disconnect mid-task to demonstrate polling.', {}, async (_args, extra) => {
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
console.log(`[${extra.sessionId}] Starting long-task...`);
// Send first progress notification
await server.sendLoggingMessage({
level: 'info',
data: 'Progress: 25% - Starting work...'
}, extra.sessionId);
await sleep(1000);
// Send second progress notification
await server.sendLoggingMessage({
level: 'info',
data: 'Progress: 50% - Halfway there...'
}, extra.sessionId);
await sleep(1000);
// Server decides to disconnect the client to free resources
// Client will reconnect via GET with Last-Event-ID after the transport's retryInterval
// Use extra.closeSSEStream callback - available when eventStore is configured
if (extra.closeSSEStream) {
console.log(`[${extra.sessionId}] Closing SSE stream to trigger client polling...`);
extra.closeSSEStream();
}
// Continue processing while client is disconnected
// Events are stored in eventStore and will be replayed on reconnect
await sleep(500);
await server.sendLoggingMessage({
level: 'info',
data: 'Progress: 75% - Almost done (sent while client disconnected)...'
}, extra.sessionId);
await sleep(500);
await server.sendLoggingMessage({
level: 'info',
data: 'Progress: 100% - Complete!'
}, extra.sessionId);
console.log(`[${extra.sessionId}] Task complete`);
return {
content: [
{
type: 'text',
text: 'Long task completed successfully!'
}
]
};
});
return server;
};
// Set up Express app
const app = createMcpExpressApp();
app.use(cors());
// Create event store for resumability
const eventStore = new InMemoryEventStore();
// Close sessions that have been idle for IDLE_MS, and keep at most MAX_SESSIONS open
const IDLE_MS = 30 * 60000;
const MAX_SESSIONS = 1000;
const sessions = new Map();
// Count open responses so a long-running request or a listening SSE stream is not treated as idle
const trackResponse = (session, res) => {
if (!res.socket || res.destroyed)
return;
session.open++;
res.on('close', () => {
session.open--;
session.lastActive = Date.now();
});
};
// Close sessions with nothing open and no activity for IDLE_MS
setInterval(() => {
const cutoff = Date.now() - IDLE_MS;
for (const { transport, open, lastActive } of sessions.values()) {
if (open === 0 && lastActive < cutoff)
transport.close().catch(console.error);
}
}, 60000).unref();
// Handle all MCP requests
app.all('/mcp', async (req, res) => {
const sessionId = req.headers['mcp-session-id'];
// Reuse the existing transport for a known session
const session = sessionId ? sessions.get(sessionId) : undefined;
if (session) {
trackResponse(session, res);
await session.transport.handleRequest(req, res, req.body);
return;
}
if (sessionId) {
// Unknown or expired session ID - the client should start a new session
res.status(404).json({ jsonrpc: '2.0', error: { code: -32001, message: 'Session not found' }, id: null });
return;
}
if (!isInitializeRequest(req.body)) {
// Invalid request - no session ID and not an initialization request
res.status(400).json({ jsonrpc: '2.0', error: { code: -32000, message: 'Bad Request: No valid session ID provided' }, id: null });
return;
}
if (sessions.size >= MAX_SESSIONS) {
res.status(503).json({ jsonrpc: '2.0', error: { code: -32000, message: 'Too many open sessions' }, id: null });
return;
}
// New initialization request - create a transport for the session
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: () => randomUUID(),
eventStore,
retryInterval: 2000, // Default retry interval for priming events
onsessioninitialized: id => {
console.log(`[${id}] Session initialized`);
sessions.set(id, { transport, open: 0, lastActive: Date.now() });
}
});
// Set up onclose handler to clean up transport when closed
transport.onclose = () => {
const sid = transport.sessionId;
if (sid && sessions.has(sid)) {
console.log(`[${sid}] Transport closed, removing from sessions map`);
sessions.delete(sid);
}
};
// Create a new server per session and connect it to the transport
const server = getServer();
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
});
// Start the server
const PORT = 3001;
app.listen(PORT, () => {
console.log(`SSE Polling Example Server running on http://localhost:${PORT}/mcp`);
console.log('');
console.log('This server demonstrates SEP-1699 SSE polling:');
console.log('- retryInterval: 2000ms (client waits 2s before reconnecting)');
console.log('- eventStore: InMemoryEventStore (events are persisted for replay)');
console.log('');
console.log('Try calling the "long-task" tool to see server-initiated disconnect in action.');
});
//# sourceMappingURL=ssePollingExample.js.map
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"_E"},B:{"1":"_K","2":"_aB","257":"_AC"},C:{"1":"_H _cI _bH _p","2":"_o _tL _L","578":"_nT _LD _8P"},D:{"1":"_H _bK _uH","2":"_7N","194":"_TC _KD _TG"},E:{"1":"_jN","2":"_UB","33":"_V _5B QD _lL"},F:{"1":"_8F","2":"_HP","194":"_iE _dC _5N _sB"},G:{"1":"_sE","2":"_3","33":"_UI"},H:{"2":"1D"},I:{"1":"I","2":"_G"},J:{"2":"_B"},K:{"1":"H","2":"_D"},L:{"1":"I"},M:{"1":"YC"},N:{"2":"_A"},O:{"1":"bC"},P:{"1":"_cJ","2":"J","194":"_rI mC DE"},Q:{"2":"JE"},R:{"1":"KE"},S:{"2":"_C"}},B:7,C:"CSS Backdrop Filter",D:true};
@@ -0,0 +1,42 @@
'use strict'
let Warning = require('./warning')
class Result {
get content() {
return this.css
}
constructor(processor, root, opts) {
this.processor = processor
this.messages = []
this.root = root
this.opts = opts
this.css = ''
this.map = undefined
}
toString() {
return this.css
}
warn(text, opts = {}) {
if (!opts.plugin) {
if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
opts.plugin = this.lastPlugin.postcssPlugin
}
}
let warning = new Warning(text, opts)
this.messages.push(warning)
return warning
}
warnings() {
return this.messages.filter(i => i.type === 'warning')
}
}
module.exports = Result
Result.default = Result
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"_E"},B:{"1":"_K","2":"_I"},C:{"1":"_LF","16":"GD","33":"fC _eL _L"},D:{"1":"_MM","16":"_Y","33":"_UF _vD"},E:{"1":"_PB","16":"_4C","33":"_RJ _tE"},F:{"1":"_RI","2":"_T","33":"_KR"},G:{"1":"_s","16":"_1","33":"_SD"},H:{"2":"1D"},I:{"1":"I","16":"_W","33":"_y"},J:{"16":"_B"},K:{"1":"H","2":"_D"},L:{"1":"I"},M:{"1":"YC"},N:{"2":"_A"},O:{"1":"bC"},P:{"1":"_sF","16":"J","33":"_mJ BE"},Q:{"1":"JE"},R:{"1":"KE"},S:{"1":"ME","33":"LE"}},B:5,C:"CSS :any-link selector",D:true};
@@ -0,0 +1,986 @@
// source/ip-key-generator.ts
import { isIPv6 } from "node:net";
import { Address6 } from "ip-address";
function ipKeyGenerator(ip, ipv6Subnet = 56) {
if (isIPv6(ip)) {
const address = new Address6(ip);
if (address.is4()) return address.to4().correctForm();
if (ipv6Subnet) {
const subnet = new Address6(`${ip}/${ipv6Subnet}`);
return subnet.networkForm();
}
}
return ip;
}
// source/memory-store.ts
var MemoryStore = class {
constructor(validations2) {
this.validations = validations2;
/**
* These two maps store usage (requests) and reset time by key (for example, IP
* addresses or API keys).
*
* They are split into two to avoid having to iterate through the entire set to
* determine which ones need reset. Instead, `Client`s are moved from `previous`
* to `current` as they hit the endpoint. Once `windowMs` has elapsed, all clients
* left in `previous`, i.e., those that have not made any recent requests, are
* known to be expired and can be deleted in bulk.
*/
this.previous = /* @__PURE__ */ new Map();
this.current = /* @__PURE__ */ new Map();
/**
* Confirmation that the keys incremented in once instance of MemoryStore
* cannot affect other instances.
*/
this.localKeys = true;
}
/**
* Method that initializes the store.
*
* @param options {Options} - The options used to setup the middleware.
*/
init(options) {
this.windowMs = options.windowMs;
this.validations?.windowMs(this.windowMs);
if (this.interval) clearInterval(this.interval);
this.interval = setInterval(() => {
this.clearExpired();
}, this.windowMs);
this.interval.unref?.();
}
/**
* Method to fetch a client's hit count and reset time.
*
* @param key {string} - The identifier for a client.
*
* @returns {ClientRateLimitInfo | undefined} - The number of hits and reset time for that client.
*
* @public
*/
async get(key) {
return this.current.get(key) ?? this.previous.get(key);
}
/**
* Method to increment a client's hit counter.
*
* @param key {string} - The identifier for a client.
*
* @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
*
* @public
*/
async increment(key) {
const client = this.getClient(key);
const now = Date.now();
if (client.resetTime.getTime() <= now) {
this.resetClient(client, now);
}
client.totalHits++;
return client;
}
/**
* Method to decrement a client's hit counter.
*
* @param key {string} - The identifier for a client.
*
* @public
*/
async decrement(key) {
const client = this.getClient(key);
if (client.totalHits > 0) client.totalHits--;
}
/**
* Method to reset a client's hit counter.
*
* @param key {string} - The identifier for a client.
*
* @public
*/
async resetKey(key) {
this.current.delete(key);
this.previous.delete(key);
}
/**
* Method to reset everyone's hit counter.
*
* @public
*/
async resetAll() {
this.current.clear();
this.previous.clear();
}
/**
* Method to stop the timer (if currently running) and prevent any memory
* leaks.
*
* @public
*/
shutdown() {
clearInterval(this.interval);
void this.resetAll();
}
/**
* Recycles a client by setting its hit count to zero, and reset time to
* `windowMs` milliseconds from now.
*
* NOT to be confused with `#resetKey()`, which removes a client from both the
* `current` and `previous` maps.
*
* @param client {Client} - The client to recycle.
* @param now {number} - The current time, to which the `windowMs` is added to get the `resetTime` for the client.
*
* @return {Client} - The modified client that was passed in, to allow for chaining.
*/
resetClient(client, now = Date.now()) {
client.totalHits = 0;
client.resetTime.setTime(now + this.windowMs);
return client;
}
/**
* Retrieves or creates a client, given a key. Also ensures that the client being
* returned is in the `current` map.
*
* @param key {string} - The key under which the client is (or is to be) stored.
*
* @returns {Client} - The requested client.
*/
getClient(key) {
if (this.current.has(key)) return this.current.get(key);
let client;
if (this.previous.has(key)) {
client = this.previous.get(key);
this.previous.delete(key);
} else {
client = { totalHits: 0, resetTime: /* @__PURE__ */ new Date() };
this.resetClient(client);
}
this.current.set(key, client);
return client;
}
/**
* Move current clients to previous, create a new map for current.
*
* This function is called every `windowMs`.
*/
clearExpired() {
this.previous = this.current;
this.current = /* @__PURE__ */ new Map();
}
};
// source/rate-limit.ts
import { isIPv6 as isIPv62 } from "node:net";
// source/console-logger.ts
var ConsoleLogger = {
warn(...args) {
console.warn(...args.reverse());
},
error(...args) {
console.error(...args.reverse());
}
};
// source/headers.ts
import { Buffer } from "node:buffer";
import { createHash } from "node:crypto";
var SUPPORTED_DRAFT_VERSIONS = [
"draft-6",
"draft-7",
"draft-8"
];
var getResetSeconds = (windowMs, resetTime) => {
let resetSeconds;
if (resetTime) {
const deltaSeconds = Math.ceil((resetTime.getTime() - Date.now()) / 1e3);
resetSeconds = Math.max(0, deltaSeconds);
} else {
resetSeconds = Math.ceil(windowMs / 1e3);
}
return resetSeconds;
};
var getPartitionKey = (key) => {
const hash = createHash("sha256");
hash.update(key);
const partitionKey = hash.digest("hex").slice(0, 12);
return Buffer.from(partitionKey).toString("base64");
};
var setLegacyHeaders = (response, info) => {
if (response.headersSent) return;
response.setHeader("X-RateLimit-Limit", info.limit.toString());
response.setHeader("X-RateLimit-Remaining", info.remaining.toString());
if (info.resetTime instanceof Date) {
response.setHeader("Date", (/* @__PURE__ */ new Date()).toUTCString());
response.setHeader(
"X-RateLimit-Reset",
Math.ceil(info.resetTime.getTime() / 1e3).toString()
);
}
};
var setDraft6Headers = (response, info, windowMs) => {
if (response.headersSent) return;
const windowSeconds = Math.ceil(windowMs / 1e3);
const resetSeconds = getResetSeconds(windowMs, info.resetTime);
response.setHeader("RateLimit-Policy", `${info.limit};w=${windowSeconds}`);
response.setHeader("RateLimit-Limit", info.limit.toString());
response.setHeader("RateLimit-Remaining", info.remaining.toString());
if (typeof resetSeconds === "number")
response.setHeader("RateLimit-Reset", resetSeconds.toString());
};
var setDraft7Headers = (response, info, windowMs) => {
if (response.headersSent) return;
const windowSeconds = Math.ceil(windowMs / 1e3);
const resetSeconds = getResetSeconds(windowMs, info.resetTime);
response.setHeader("RateLimit-Policy", `${info.limit};w=${windowSeconds}`);
response.setHeader(
"RateLimit",
`limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}`
);
};
var setDraft8Headers = (response, info, windowMs, name, key) => {
if (response.headersSent) return;
const windowSeconds = Math.ceil(windowMs / 1e3);
const resetSeconds = getResetSeconds(windowMs, info.resetTime);
const partitionKey = getPartitionKey(key);
const header = `r=${info.remaining}; t=${resetSeconds}`;
const policy = `q=${info.limit}; w=${windowSeconds}; pk=:${partitionKey}:`;
response.append("RateLimit", `"${name}"; ${header}`);
response.append("RateLimit-Policy", `"${name}"; ${policy}`);
};
var setRetryAfterHeader = (response, info, windowMs) => {
if (response.headersSent) return;
const resetSeconds = getResetSeconds(windowMs, info.resetTime);
response.setHeader("Retry-After", resetSeconds.toString());
};
// source/utils.ts
var omitUndefinedProperties = (passedOptions) => {
const omittedOptions = {};
for (const k of Object.keys(passedOptions)) {
const key = k;
if (passedOptions[key] !== void 0) {
omittedOptions[key] = passedOptions[key];
}
}
return omittedOptions;
};
// source/validations.ts
import { isIP } from "node:net";
var ValidationError = class extends Error {
/**
* The code must be a string, in snake case and all capital, that starts with
* the substring `ERR_ERL_`.
*
* The message must be a string, starting with an uppercase character,
* describing the issue in detail.
*/
constructor(code, message) {
const url = `https://express-rate-limit.github.io/${code}/`;
super(`${message} See ${url} for more information.`);
this.name = this.constructor.name;
this.code = code;
this.help = url;
}
};
var ChangeWarning = class extends ValidationError {
};
var usedStores = /* @__PURE__ */ new Set();
var singleCountKeys = /* @__PURE__ */ new WeakMap();
var validations = {
enabled: {
default: true
},
// Should be EnabledValidations type, but that's a circular reference
disable() {
for (const k of Object.keys(this.enabled)) this.enabled[k] = false;
},
/**
* Checks whether the IP address is valid, and that it does not have a port
* number in it.
*
* See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_invalid_ip_address.
*
* @param ip {string | undefined} - The IP address provided by Express as request.ip.
*
* @returns {void}
*/
ip(ip) {
if (ip === void 0) {
throw new ValidationError(
"ERR_ERL_UNDEFINED_IP_ADDRESS",
`An undefined 'request.ip' was detected. This might indicate a misconfiguration or the connection being destroyed prematurely.`
);
}
if (!isIP(ip)) {
throw new ValidationError(
"ERR_ERL_INVALID_IP_ADDRESS",
`An invalid 'request.ip' (${ip}) was detected. Consider passing a custom 'keyGenerator' function to the rate limiter.`
);
}
},
/**
* Makes sure the trust proxy setting is not set to `true`.
*
* See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_permissive_trust_proxy.
*
* @param request {Request} - The Express request object.
*
* @returns {void}
*/
trustProxy(request) {
if (request.app.get("trust proxy") === true) {
throw new ValidationError(
"ERR_ERL_PERMISSIVE_TRUST_PROXY",
`The Express 'trust proxy' setting is true, which allows anyone to trivially bypass IP-based rate limiting.`
);
}
},
/**
* Makes sure the trust proxy setting is set in case the `X-Forwarded-For`
* header is present.
*
* See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_unset_trust_proxy.
*
* @param request {Request} - The Express request object.
*
* @returns {void}
*/
xForwardedForHeader(request) {
if (request.headers["x-forwarded-for"] && request.app.get("trust proxy") === false) {
throw new ValidationError(
"ERR_ERL_UNEXPECTED_X_FORWARDED_FOR",
`The 'X-Forwarded-For' header is set but the Express 'trust proxy' setting is false (default). This could indicate a misconfiguration which would prevent express-rate-limit from accurately identifying users.`
);
}
},
/**
* Alert the user if the Forwarded header is set (standardized version of X-Forwarded-For - not supported by express as of version 5.1.0)
*
* @param request {Request} - The Express request object.
*
* @returns {void}
*/
forwardedHeader(request) {
if (request.headers.forwarded && request.ip === request.socket?.remoteAddress) {
throw new ValidationError(
"ERR_ERL_FORWARDED_HEADER",
`The 'Forwarded' header (standardized X-Forwarded-For) is set but currently being ignored. Add a custom keyGenerator to use a value from this header.`
);
}
},
/**
* Ensures totalHits value from store is a positive integer.
*
* @param hits {any} - The `totalHits` returned by the store.
*/
positiveHits(hits) {
if (typeof hits !== "number" || hits < 1 || hits !== Math.round(hits)) {
throw new ValidationError(
"ERR_ERL_INVALID_HITS",
`The totalHits value returned from the store must be a positive integer, got ${hits}`
);
}
},
/**
* Ensures a single store instance is not used with multiple express-rate-limit instances
*/
unsharedStore(store) {
if (usedStores.has(store)) {
const maybeUniquePrefix = store?.localKeys ? "" : " (with a unique prefix)";
throw new ValidationError(
"ERR_ERL_STORE_REUSE",
`A Store instance must not be shared across multiple rate limiters. Create a new instance of ${store.constructor.name}${maybeUniquePrefix} for each limiter instead.`
);
}
usedStores.add(store);
},
/**
* Ensures a given key is incremented only once per request.
*
* @param request {Request} - The Express request object.
* @param store {Store} - The store class.
* @param key {string} - The key used to store the client's hit count.
*
* @returns {void}
*/
singleCount(request, store, key) {
let storeKeys = singleCountKeys.get(request);
if (!storeKeys) {
storeKeys = /* @__PURE__ */ new Map();
singleCountKeys.set(request, storeKeys);
}
const storeKey = store.localKeys ? store : store.constructor.name;
let keys = storeKeys.get(storeKey);
if (!keys) {
keys = [];
storeKeys.set(storeKey, keys);
}
const prefixedKey = `${store.prefix ?? ""}${key}`;
if (keys.includes(prefixedKey)) {
throw new ValidationError(
"ERR_ERL_DOUBLE_COUNT",
`The hit count for ${key} was incremented more than once for a single request.`
);
}
keys.push(prefixedKey);
},
/**
* Warns the user that the behaviour for `max: 0` / `limit: 0` is
* changing in the next major release.
*
* @param limit {number} - The maximum number of hits per client.
*
* @returns {void}
*/
limit(limit) {
if (limit === 0) {
throw new ChangeWarning(
"WRN_ERL_MAX_ZERO",
"Setting limit or max to 0 disables rate limiting in express-rate-limit v6 and older, but will cause all requests to be blocked in v7"
);
}
},
/**
* Warns the user that the `draft_polli_ratelimit_headers` option is deprecated
* and will be removed in the next major release.
*
* @param draft_polli_ratelimit_headers {any | undefined} - The now-deprecated setting that was used to enable standard headers.
*
* @returns {void}
*/
draftPolliHeaders(draft_polli_ratelimit_headers) {
if (draft_polli_ratelimit_headers) {
throw new ChangeWarning(
"WRN_ERL_DEPRECATED_DRAFT_POLLI_HEADERS",
`The draft_polli_ratelimit_headers configuration option is deprecated and has been removed in express-rate-limit v7, please set standardHeaders: 'draft-6' instead.`
);
}
},
/**
* Warns the user that the `onLimitReached` option is deprecated and
* will be removed in the next major release.
*
* @param onLimitReached {any | undefined} - The maximum number of hits per client.
*
* @returns {void}
*/
onLimitReached(onLimitReached) {
if (onLimitReached) {
throw new ChangeWarning(
"WRN_ERL_DEPRECATED_ON_LIMIT_REACHED",
"The onLimitReached configuration option is deprecated and has been removed in express-rate-limit v7."
);
}
},
/**
* Warns the user when an invalid/unsupported version of the draft spec is passed.
*
* @param version {any | undefined} - The version passed by the user.
*
* @returns {void}
*/
headersDraftVersion(version) {
if (typeof version !== "string" || // @ts-expect-error This is fine. If version is not in the array, it will just return false.
!SUPPORTED_DRAFT_VERSIONS.includes(version)) {
const versionString = SUPPORTED_DRAFT_VERSIONS.join(", ");
throw new ValidationError(
"ERR_ERL_HEADERS_UNSUPPORTED_DRAFT_VERSION",
`standardHeaders: only the following versions of the IETF draft specification are supported: ${versionString}.`
);
}
},
/**
* Warns the user when the selected headers option requires a reset time but
* the store does not provide one.
*
* @param resetTime {Date | undefined} - The timestamp when the client's hit count will be reset.
*
* @returns {void}
*/
headersResetTime(resetTime) {
if (!resetTime) {
throw new ValidationError(
"ERR_ERL_HEADERS_NO_RESET",
`standardHeaders: 'draft-7' requires a 'resetTime', but the store did not provide one. The 'windowMs' value will be used instead, which may cause clients to wait longer than necessary.`
);
}
},
knownOptions(passedOptions) {
if (!passedOptions) return;
const optionsMap = {
windowMs: true,
limit: true,
message: true,
statusCode: true,
legacyHeaders: true,
standardHeaders: true,
identifier: true,
requestPropertyName: true,
skipFailedRequests: true,
skipSuccessfulRequests: true,
keyGenerator: true,
ipv6Subnet: true,
handler: true,
skip: true,
requestWasSuccessful: true,
store: true,
validate: true,
headers: true,
max: true,
passOnStoreError: true,
logger: true
};
const validOptions = Object.keys(optionsMap).concat(
"draft_polli_ratelimit_headers",
// not a valid option anymore, but we have a more specific check for this one, so don't warn for it here
// from express-slow-down - https://github.com/express-rate-limit/express-slow-down/blob/main/source/types.ts#L65
"delayAfter",
"delayMs",
"maxDelayMs"
);
for (const key of Object.keys(passedOptions)) {
if (!validOptions.includes(key)) {
throw new ValidationError(
"ERR_ERL_UNKNOWN_OPTION",
`Unexpected configuration option: ${key}`
// todo: suggest a valid option with a short levenstein distance?
);
}
}
},
/**
* Checks the options.validate setting to ensure that only recognized
* validations are enabled or disabled.
*
* If any unrecognized values are found, an error is logged that
* includes the list of supported validations.
*/
validationsConfig() {
const supportedValidations = Object.keys(this).filter(
(k) => !["enabled", "disable"].includes(k)
);
supportedValidations.push("default");
for (const key of Object.keys(this.enabled)) {
if (!supportedValidations.includes(key)) {
throw new ValidationError(
"ERR_ERL_UNKNOWN_VALIDATION",
`options.validate.${key} is not recognized. Supported validate options are: ${supportedValidations.join(
", "
)}.`
);
}
}
},
/**
* Checks to see if the instance was created inside of a request handler,
* which would prevent it from working correctly, with the default memory
* store (or any other store with localKeys.)
*/
creationStack(store) {
const { stack } = new Error(
"express-rate-limit validation check (set options.validate.creationStack=false to disable)"
);
if (stack?.includes("Layer.handle [as handle_request]") || // express v4
stack?.includes("Layer.handleRequest")) {
if (!store.localKeys) {
throw new ValidationError(
"ERR_ERL_CREATED_IN_REQUEST_HANDLER",
"express-rate-limit instance should *usually* be created at app initialization, not when responding to a request."
);
}
throw new ValidationError(
"ERR_ERL_CREATED_IN_REQUEST_HANDLER",
"express-rate-limit instance should be created at app initialization, not when responding to a request."
);
}
},
ipv6Subnet(ipv6Subnet) {
if (ipv6Subnet === false) {
return;
}
if (!Number.isInteger(ipv6Subnet) || ipv6Subnet < 32 || ipv6Subnet > 64) {
throw new ValidationError(
"ERR_ERL_IPV6_SUBNET",
`Unexpected ipv6Subnet value: ${ipv6Subnet}. Expected an integer between 32 and 64 (usually 48-64).`
);
}
},
ipv6SubnetOrKeyGenerator(options) {
if (options.ipv6Subnet !== void 0 && options.keyGenerator) {
throw new ValidationError(
"ERR_ERL_IPV6SUBNET_OR_KEYGENERATOR",
`Incompatible options: the 'ipv6Subnet' option is ignored when a custom 'keyGenerator' function is also set.`
);
}
},
keyGeneratorIpFallback(keyGenerator) {
if (!keyGenerator) {
return;
}
const src = keyGenerator.toString();
if ((src.includes("req.ip") || src.includes("request.ip")) && !src.includes("ipKeyGenerator")) {
throw new ValidationError(
"ERR_ERL_KEY_GEN_IPV6",
"Custom keyGenerator appears to use request IP without calling the ipKeyGenerator helper function for IPv6 addresses. This could allow IPv6 users to bypass limits."
);
}
},
/**
* Checks to see if the window duration is greater than 2^32 - 1. This is only
* called by the default MemoryStore, since it uses Node's setInterval method.
*
* See https://nodejs.org/api/timers.html#setintervalcallback-delay-args.
*/
windowMs(windowMs) {
const SET_TIMEOUT_MAX = 2 ** 31 - 1;
if (typeof windowMs !== "number" || Number.isNaN(windowMs) || windowMs < 1 || windowMs > SET_TIMEOUT_MAX) {
throw new ValidationError(
"ERR_ERL_WINDOW_MS",
`Invalid windowMs value: ${windowMs}${typeof windowMs !== "number" ? ` (${typeof windowMs})` : ""}, must be a number between 1 and ${SET_TIMEOUT_MAX} when using the default MemoryStore`
);
}
}
};
function validateLogger(logger) {
if (typeof logger !== "object" || typeof logger.error !== "function" || typeof logger.warn !== "function") {
throw new TypeError(
"Provided logger does not implement the Logger interface"
);
}
}
var getValidations = (_enabled, logger) => {
validateLogger(logger);
let enabled;
if (typeof _enabled === "boolean") {
enabled = {
default: _enabled
};
} else {
enabled = {
default: true,
..._enabled
};
}
const wrappedValidations = { enabled };
for (const [name, validation] of Object.entries(validations)) {
if (typeof validation === "function")
wrappedValidations[name] = (...args) => {
if (!(enabled[name] ?? enabled.default)) {
return;
}
try {
;
validation.apply(
wrappedValidations,
args
);
} catch (error) {
if (error instanceof ChangeWarning) logger.warn(error);
else logger.error(error);
}
};
}
return wrappedValidations;
};
// source/rate-limit.ts
var isLegacyStore = (store) => (
// Check that `incr` exists but `increment` does not - store authors might want
// to keep both around for backwards compatibility.
typeof store.incr === "function" && typeof store.increment !== "function"
);
var promisifyStore = (passedStore) => {
if (!isLegacyStore(passedStore)) {
return passedStore;
}
const legacyStore = passedStore;
class PromisifiedStore {
async increment(key) {
return new Promise((resolve, reject) => {
legacyStore.incr(
key,
(error, totalHits, resetTime) => {
if (error) reject(error);
resolve({ totalHits, resetTime });
}
);
});
}
async decrement(key) {
return legacyStore.decrement(key);
}
async resetKey(key) {
return legacyStore.resetKey(key);
}
/* istanbul ignore next */
async resetAll() {
if (typeof legacyStore.resetAll === "function")
return legacyStore.resetAll();
}
}
return new PromisifiedStore();
};
var getOptionsFromConfig = (config) => {
const { validations: validations2, ...directlyPassableEntries } = config;
return {
...directlyPassableEntries,
validate: validations2.enabled
};
};
var parseOptions = (passedOptions) => {
const notUndefinedOptions = omitUndefinedProperties(passedOptions);
const logger = passedOptions.logger ?? ConsoleLogger;
const validations2 = getValidations(
notUndefinedOptions?.validate ?? true,
logger
);
validations2.validationsConfig();
validations2.knownOptions(passedOptions);
validations2.draftPolliHeaders(
// @ts-expect-error see the note above.
notUndefinedOptions.draft_polli_ratelimit_headers
);
validations2.onLimitReached(notUndefinedOptions.onLimitReached);
if (notUndefinedOptions.ipv6Subnet !== void 0 && typeof notUndefinedOptions.ipv6Subnet !== "function") {
validations2.ipv6Subnet(notUndefinedOptions.ipv6Subnet);
}
validations2.keyGeneratorIpFallback(notUndefinedOptions.keyGenerator);
validations2.ipv6SubnetOrKeyGenerator(notUndefinedOptions);
let standardHeaders = notUndefinedOptions.standardHeaders ?? false;
if (standardHeaders === true) standardHeaders = "draft-6";
const config = {
windowMs: 60 * 1e3,
limit: passedOptions.max ?? 5,
// `max` is deprecated, but support it anyways.
message: "Too many requests, please try again later.",
statusCode: 429,
legacyHeaders: passedOptions.headers ?? true,
identifier(request, _response) {
let duration = "";
const property = config.requestPropertyName;
const { limit } = request[property];
const seconds = config.windowMs / 1e3;
const minutes = config.windowMs / (1e3 * 60);
const hours = config.windowMs / (1e3 * 60 * 60);
const days = config.windowMs / (1e3 * 60 * 60 * 24);
if (seconds < 60) duration = `${seconds}sec`;
else if (minutes < 60) duration = `${minutes}min`;
else if (hours < 24) duration = `${hours}hr${hours > 1 ? "s" : ""}`;
else duration = `${days}day${days > 1 ? "s" : ""}`;
return `${limit}-in-${duration}`;
},
requestPropertyName: "rateLimit",
skipFailedRequests: false,
skipSuccessfulRequests: false,
requestWasSuccessful: (_request, response) => response.statusCode < 400,
skip: (_request, _response) => false,
async keyGenerator(request, response) {
validations2.ip(request.ip);
validations2.trustProxy(request);
validations2.xForwardedForHeader(request);
validations2.forwardedHeader(request);
const ip = request.ip;
let subnet = 56;
if (isIPv62(ip)) {
subnet = typeof config.ipv6Subnet === "function" ? await config.ipv6Subnet(request, response) : config.ipv6Subnet;
if (typeof config.ipv6Subnet === "function")
validations2.ipv6Subnet(subnet);
}
return ipKeyGenerator(ip, subnet);
},
ipv6Subnet: 56,
async handler(request, response, _next, _optionsUsed) {
response.status(config.statusCode);
const message = typeof config.message === "function" ? await config.message(
request,
response
) : config.message;
if (!response.writableEnded) response.send(message);
},
passOnStoreError: false,
// Allow the default options to be overridden by the passed options.
...notUndefinedOptions,
// `standardHeaders` is resolved into a draft version above, use that.
standardHeaders,
// Note that this field is declared after the user's options are spread in,
// so that this field doesn't get overridden with an un-promisified store!
store: promisifyStore(
notUndefinedOptions.store ?? new MemoryStore(validations2)
),
// Print an error to the console if a few known misconfigurations are detected.
validations: validations2,
logger
};
if (typeof config.store.increment !== "function" || typeof config.store.decrement !== "function" || typeof config.store.resetKey !== "function" || config.store.resetAll !== void 0 && typeof config.store.resetAll !== "function" || config.store.init !== void 0 && typeof config.store.init !== "function") {
throw new TypeError(
"An invalid store was passed. Please ensure that the store is a class that implements the `Store` interface."
);
}
return config;
};
var handleAsyncErrors = (fn) => async (request, response, next) => {
try {
await Promise.resolve(fn(request, response, next)).catch(next);
} catch (error) {
next(error);
}
};
var rateLimit = (passedOptions) => {
const config = parseOptions(passedOptions ?? {});
const options = getOptionsFromConfig(config);
config.validations.creationStack(config.store);
config.validations.unsharedStore(config.store);
if (typeof config.store.init === "function") {
try {
const storeInit = config.store.init(options);
if (storeInit instanceof Promise) {
storeInit.catch(
(error) => config.logger.error(
error,
"express-rate-limit: async error during store initialization."
)
);
}
} catch (error) {
config.logger.error(
error,
"express-rate-limit: error during store initialization."
);
}
}
const middleware = handleAsyncErrors(
async (request, response, next) => {
const closePromise = config.skipFailedRequests && new Promise((resolve) => response.once("close", resolve));
const finishPromise = (config.skipFailedRequests || config.skipSuccessfulRequests) && new Promise((resolve) => response.once("finish", resolve));
const errorPromise = config.skipFailedRequests && new Promise((resolve) => response.once("error", resolve));
const skip = await config.skip(request, response);
if (skip) {
next();
return;
}
const augmentedRequest = request;
const key = await config.keyGenerator(request, response);
let totalHits = 0;
let resetTime;
try {
const incrementResult = await config.store.increment(key);
totalHits = incrementResult.totalHits;
resetTime = incrementResult.resetTime;
} catch (error) {
if (config.passOnStoreError) {
config.logger.error(
error,
"express-rate-limit: error from store, allowing request without rate-limiting."
);
next();
return;
}
throw error;
}
config.validations.positiveHits(totalHits);
config.validations.singleCount(request, config.store, key);
const retrieveLimit = typeof config.limit === "function" ? config.limit(request, response) : config.limit;
const limit = await retrieveLimit;
config.validations.limit(limit);
const info = {
limit,
used: totalHits,
remaining: Math.max(limit - totalHits, 0),
resetTime,
key
};
Object.defineProperty(info, "current", {
configurable: false,
enumerable: false,
value: totalHits
});
augmentedRequest[config.requestPropertyName] = info;
if (config.legacyHeaders && !response.headersSent) {
setLegacyHeaders(response, info);
}
if (config.standardHeaders && !response.headersSent) {
switch (config.standardHeaders) {
case "draft-6": {
setDraft6Headers(response, info, config.windowMs);
break;
}
case "draft-7": {
config.validations.headersResetTime(info.resetTime);
setDraft7Headers(response, info, config.windowMs);
break;
}
case "draft-8": {
const retrieveName = typeof config.identifier === "function" ? config.identifier(request, response) : config.identifier;
const name = await retrieveName;
config.validations.headersResetTime(info.resetTime);
setDraft8Headers(response, info, config.windowMs, name, key);
break;
}
default: {
config.validations.headersDraftVersion(config.standardHeaders);
break;
}
}
}
if (config.skipFailedRequests || config.skipSuccessfulRequests) {
let decremented = false;
const decrementKey = async () => {
if (!decremented) {
await config.store.decrement(key);
decremented = true;
}
};
if (config.skipFailedRequests) {
if (finishPromise) {
void finishPromise.then(async () => {
if (!await config.requestWasSuccessful(request, response))
await decrementKey();
});
}
if (closePromise) {
void closePromise.then(async () => {
if (!response.writableEnded) await decrementKey();
});
}
if (errorPromise) {
void errorPromise.then(async () => {
await decrementKey();
});
}
}
if (config.skipSuccessfulRequests) {
if (finishPromise) {
void finishPromise.then(async () => {
if (await config.requestWasSuccessful(request, response))
await decrementKey();
});
}
}
}
config.validations.disable();
if (totalHits > limit) {
if (config.legacyHeaders || config.standardHeaders) {
setRetryAfterHeader(response, info, config.windowMs);
}
config.handler(request, response, next, options);
return;
}
next();
}
);
const getThrowFn = () => {
throw new Error("The current store does not support the get/getKey method");
};
middleware.resetKey = config.store.resetKey.bind(config.store);
middleware.getKey = typeof config.store.get === "function" ? config.store.get.bind(config.store) : getThrowFn;
return middleware;
};
var rate_limit_default = rateLimit;
export {
MemoryStore,
rate_limit_default as default,
ipKeyGenerator,
rate_limit_default as rateLimit
};
@@ -0,0 +1 @@
{"version":3,"file":"inMemoryEventStore.js","sourceRoot":"","sources":["../../../../src/examples/shared/inMemoryEventStore.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,MAAM,OAAO,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"}
@@ -0,0 +1,14 @@
import Range = require("../classes/range");
import SemVer = require("../classes/semver");
import semver = require("../index");
/**
* Return the highest version in the list that satisfies the range, or null if none of them do.
*/
declare function maxSatisfying<T extends string | SemVer>(
versions: readonly T[],
range: string | Range,
optionsOrLoose?: boolean | semver.RangeOptions,
): T | null;
export = maxSatisfying;
@@ -0,0 +1,330 @@
'use strict'
const { PoolStats } = require('../util/stats.js')
const DispatcherBase = require('./dispatcher-base')
const FixedQueue = require('./fixed-queue')
const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require('../core/symbols')
const kClients = Symbol('clients')
const kNeedDrain = Symbol('needDrain')
const kQueue = Symbol('queue')
const kClosedResolve = Symbol('closed resolve')
const kOnDrain = Symbol('onDrain')
const kOnConnect = Symbol('onConnect')
const kOnDisconnect = Symbol('onDisconnect')
const kOnConnectionError = Symbol('onConnectionError')
const kOnClientBusy = Symbol('on client busy')
const kOnClientDrain = Symbol('on client drain')
const kDrainQueue = Symbol('drain queue')
const kGetDispatcher = Symbol('get dispatcher')
const kHasDispatcher = Symbol('has dispatcher')
const kAddClient = Symbol('add client')
const kRemoveClient = Symbol('remove client')
const kRetireClient = Symbol('retire client')
const kRetiring = Symbol('retiring clients')
// Closes every live client, including clients that have been
// taken out of rotation but are still finishing their own
// requests.
function closeClients (pool) {
const closeAll = []
for (let i = 0; i < pool[kClients].length; i++) {
const client = pool[kClients][i]
if (!client.destroyed) {
closeAll.push(client.close())
}
}
for (const closed of pool[kRetiring].values()) {
closeAll.push(closed)
}
return Promise.all(closeAll)
}
class PoolBase extends DispatcherBase {
[kQueue] = new FixedQueue();
[kQueued] = 0;
[kClients] = [];
// Clients removed from kClients that have not finished closing,
// mapped to a promise that settles once they have.
[kRetiring] = new Map();
[kNeedDrain] = false;
[kOnDrain] (client, origin, targets) {
if (client.closed || client.destroyed) {
return
}
const queue = this[kQueue]
let needDrain = false
this[kOnClientDrain](client)
while (!needDrain) {
const item = queue.shift()
if (!item) {
break
}
this[kQueued]--
needDrain = !client.dispatch(item.opts, item.handler)
}
client[kNeedDrain] = needDrain
if (needDrain) {
this[kOnClientBusy](client)
// This client is full but requests are still queued, e.g. an h2
// client that has just released everything queued while ALPN was
// negotiated and hit maxConcurrentStreams. Hand the rest to other
// clients, creating new ones up to the connection limit, instead of
// leaving them for this client to drain one batch at a time.
if (!queue.isEmpty()) {
return this[kDrainQueue](origin, targets)
}
}
if (!needDrain && this[kNeedDrain]) {
this[kNeedDrain] = false
this.emit('drain', origin, [this, ...targets])
}
if (this[kClosedResolve] && queue.isEmpty()) {
return closeClients(this).then(this[kClosedResolve])
}
}
[kOnClientBusy] () {}
[kOnClientDrain] () {}
[kDrainQueue] (origin, targets) {
const queue = this[kQueue]
let hasDispatcher = true
while (!queue.isEmpty()) {
const dispatcher = this[kGetDispatcher]()
if (!dispatcher) {
hasDispatcher = false
break
}
const item = queue.shift()
this[kQueued]--
if (!dispatcher.dispatch(item.opts, item.handler)) {
dispatcher[kNeedDrain] = true
this[kOnClientBusy](dispatcher)
hasDispatcher = this[kHasDispatcher]()
if (!hasDispatcher) {
break
}
}
}
if (hasDispatcher && this[kNeedDrain]) {
this[kNeedDrain] = false
this.emit('drain', origin, [this, ...targets])
}
if (this[kClosedResolve] && queue.isEmpty()) {
return closeClients(this).then(this[kClosedResolve])
}
}
[kOnConnect] = (origin, targets) => {
this.emit('connect', origin, [this, ...targets])
};
[kOnDisconnect] = (origin, targets, err) => {
this.emit('disconnect', origin, [this, ...targets], err)
};
[kOnConnectionError] = (origin, targets, err) => {
this.emit('connectionError', origin, [this, ...targets], err)
}
get [kBusy] () {
return this[kNeedDrain]
}
get [kConnected] () {
let ret = 0
for (const { [kConnected]: connected } of this[kClients]) {
ret += connected
}
return ret
}
get [kFree] () {
let ret = 0
for (const { [kConnected]: connected, [kNeedDrain]: needDrain } of this[kClients]) {
ret += connected && !needDrain
}
return ret
}
get [kPending] () {
let ret = this[kQueued]
for (const { [kPending]: pending } of this[kClients]) {
ret += pending
}
return ret
}
get [kRunning] () {
let ret = 0
for (const { [kRunning]: running } of this[kClients]) {
ret += running
}
return ret
}
get [kSize] () {
let ret = this[kQueued]
for (const { [kSize]: size } of this[kClients]) {
ret += size
}
return ret
}
get stats () {
return new PoolStats(this)
}
[kClose] () {
if (this[kQueue].isEmpty()) {
return closeClients(this)
} else {
return new Promise((resolve) => {
this[kClosedResolve] = resolve
})
}
}
[kDestroy] (err) {
while (true) {
const item = this[kQueue].shift()
if (!item) {
break
}
item.handler.onResponseError(null, err)
}
const destroyAll = new Array(this[kClients].length)
for (let i = 0; i < this[kClients].length; i++) {
destroyAll[i] = this[kClients][i].destroy(err)
}
for (const client of this[kRetiring].keys()) {
destroyAll.push(client.destroy(err))
}
return Promise.all(destroyAll)
}
[kDispatch] (opts, handler) {
const dispatcher = this[kGetDispatcher]()
if (!dispatcher) {
this[kNeedDrain] = true
this[kQueue].push({ opts, handler })
this[kQueued]++
} else if (!dispatcher.dispatch(opts, handler)) {
dispatcher[kNeedDrain] = true
this[kOnClientBusy](dispatcher)
this[kNeedDrain] = !this[kHasDispatcher]()
}
return !this[kNeedDrain]
}
[kHasDispatcher] () {
for (let i = 0; i < this[kClients].length; i++) {
const dispatcher = this[kClients][i]
if (
!dispatcher[kNeedDrain] &&
dispatcher.closed !== true &&
dispatcher.destroyed !== true
) {
return true
}
}
return false
}
[kAddClient] (client) {
client
.on('drain', this[kOnDrain].bind(this, client))
.on('connect', this[kOnConnect])
.on('disconnect', this[kOnDisconnect])
.on('connectionError', this[kOnConnectionError])
this[kClients].push(client)
if (this[kNeedDrain]) {
queueMicrotask(() => {
if (this[kNeedDrain] && !client[kNeedDrain]) {
this[kOnDrain](client, client[kUrl], [client, this])
}
})
}
return this
}
// Takes a client out of rotation. A closed client no longer takes requests
// from the pool queue (see kOnDrain), but it finishes the requests it
// already has. Until it has, pool.close() waits for it and pool.destroy()
// destroys it.
[kRetireClient] (client) {
const idx = this[kClients].indexOf(client)
if (idx !== -1) {
this[kClients].splice(idx, 1)
}
if (client.destroyed || this[kRetiring].has(client)) {
return
}
// Use the callback form: custom dispatchers from `factory` are not
// required to return a promise, and may call back synchronously.
let done = false
let resolveClosed
const closed = new Promise((resolve) => { resolveClosed = resolve })
this[kRetiring].set(client, closed)
client.close(() => {
if (!done) {
done = true
this[kRetiring].delete(client)
resolveClosed()
}
})
}
[kRemoveClient] (client) {
this[kRetireClient](client)
this[kNeedDrain] = !this[kClients].some(dispatcher => (
!dispatcher[kNeedDrain] &&
dispatcher.closed !== true &&
dispatcher.destroyed !== true
))
}
}
module.exports = {
PoolBase,
kClients,
kNeedDrain,
kAddClient,
kRemoveClient,
kRetireClient,
kDrainQueue,
kOnClientBusy,
kOnClientDrain,
kGetDispatcher,
kHasDispatcher
}
@@ -0,0 +1,56 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
//#region src/http-exception.ts
/**
* `HTTPException` must be used when a fatal error such as authentication failure occurs.
*
* @see {@link https://hono.dev/docs/api/exception}
*
* @param {StatusCode} status - status code of HTTPException
* @param {HTTPExceptionOptions} options - options of HTTPException
* @param {HTTPExceptionOptions["res"]} options.res - response of options of HTTPException
* @param {HTTPExceptionOptions["message"]} options.message - message of options of HTTPException
* @param {HTTPExceptionOptions["cause"]} options.cause - cause of options of HTTPException
*
* @example
* ```ts
* import { HTTPException } from 'hono/http-exception'
*
* // ...
*
* app.post('/auth', async (c, next) => {
* // authentication
* if (authorized === false) {
* throw new HTTPException(401, { message: 'Custom error message' })
* }
* await next()
* })
* ```
*/
var HTTPException = class extends Error {
res;
status;
/**
* Creates an instance of `HTTPException`.
* @param status - HTTP status code for the exception. Defaults to 500.
* @param options - Additional options for the exception.
*/
constructor(status = 500, options) {
super(options?.message, { cause: options?.cause });
this.res = options?.res;
this.status = status;
}
/**
* Returns the response object associated with the exception.
* If a response object is not provided, a new response is created with the error message and status code.
* @returns The response object.
*/
getResponse() {
if (this.res) return new Response(this.res.body, {
status: this.status,
headers: this.res.headers
});
return new Response(this.message, { status: this.status });
}
};
//#endregion
exports.HTTPException = HTTPException;
@@ -0,0 +1,13 @@
import { t as CfWorkerJsonSchemaValidator } from "./cfWorkerProvider-doTkZbTr.cjs";
//#region src/shimsBrowser.d.ts
/**
* Whether `fetch()` may throw `TypeError` due to CORS. Only true in browser contexts
* (including Web Workers / Service Workers). In Node.js and Cloudflare Workers, a
* `TypeError` from `fetch` is always a real network/configuration error.
*/
declare const CORS_IS_POSSIBLE = true;
//#endregion
export { CORS_IS_POSSIBLE, CfWorkerJsonSchemaValidator as DefaultJsonSchemaValidator };
//# sourceMappingURL=shimsBrowser.d.cts.map
@@ -0,0 +1,16 @@
'use strict';
// TODO: switch to class private field when targetting node.js 12
const _summarizer = Symbol('ReportBase.#summarizer');
class ReportBase {
constructor(opts = {}) {
this[_summarizer] = opts.summarizer;
}
execute(context) {
context.getTree(this[_summarizer]).visit(this, context);
}
}
module.exports = ReportBase;
@@ -0,0 +1,10 @@
import type { CodeKeywordDefinition } from "../../types";
import { _JTDTypeError } from "./error";
export type JTDTypeError = _JTDTypeError<"type", JTDType, JTDType>;
export type IntType = "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32";
export declare const intRange: {
[T in IntType]: [number, number, number];
};
export type JTDType = "boolean" | "string" | "timestamp" | "float32" | "float64" | IntType;
declare const def: CodeKeywordDefinition;
export default def;
@@ -0,0 +1,74 @@
{
"name": "ws",
"version": "8.22.0",
"description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js",
"keywords": [
"HyBi",
"Push",
"RFC-6455",
"WebSocket",
"WebSockets",
"real-time"
],
"homepage": "https://github.com/websockets/ws",
"bugs": "https://github.com/websockets/ws/issues",
"repository": {
"type": "git",
"url": "git+https://github.com/websockets/ws.git"
},
"author": "Einar Otto Stangvik <einaros@gmail.com> (http://2x.io)",
"license": "MIT",
"main": "index.js",
"exports": {
".": {
"browser": "./browser.js",
"import": "./wrapper.mjs",
"require": "./index.js"
},
"./package.json": "./package.json"
},
"browser": "browser.js",
"engines": {
"node": ">=10.0.0"
},
"files": [
"browser.js",
"index.js",
"lib/*.js",
"wrapper.mjs"
],
"scripts": {
"test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js",
"integration": "mocha --throw-deprecation test/*.integration.js",
"lint": "eslint . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\""
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"benchmark": "^2.1.4",
"bufferutil": "^4.0.1",
"eslint": "^10.0.1",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.0.0",
"globals": "^17.0.0",
"mocha": "^8.4.0",
"nyc": "^15.0.0",
"prettier": "^3.0.0",
"utf-8-validate": "^6.0.0"
},
"allowScripts": {
"bufferutil": true,
"utf-8-validate": true
}
}
@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _maybeArrayLike;
var _arrayLikeToArray = require("./arrayLikeToArray.js");
function _maybeArrayLike(orElse, arr, i) {
if (arr && !Array.isArray(arr) && typeof arr.length === "number") {
var len = arr.length;
return (0, _arrayLikeToArray.default)(arr, i !== void 0 && i < len ? i : len);
}
return orElse(arr, i);
}
//# sourceMappingURL=maybeArrayLike.js.map
@@ -0,0 +1 @@
{"version":3,"file":"circle-arrow-left.js","sources":["../../../src/icons/circle-arrow-left.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name CircleArrowLeft\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSIxMCIgLz4KICA8cGF0aCBkPSJNMTYgMTJIOCIgLz4KICA8cGF0aCBkPSJtMTIgOC00IDQgNCA0IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/circle-arrow-left\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 CircleArrowLeft = createLucideIcon('CircleArrowLeft', [\n ['circle', { cx: '12', cy: '12', r: '10', key: '1mglay' }],\n ['path', { d: 'M16 12H8', key: '1fr5h0' }],\n ['path', { d: 'm12 8-4 4 4 4', key: '15vm53' }],\n]);\n\nexport default CircleArrowLeft;\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,CAAkB,iBAAiB,iBAAmB,CAAA,CAAA,CAAA;AAAA,CAC1D,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,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,CAAiB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAChD,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,16 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const SignalLow = createLucideIcon("SignalLow", [
["path", { d: "M2 20h.01", key: "4haj6o" }],
["path", { d: "M7 20v-4", key: "j294jx" }]
]);
export { SignalLow as default };
//# sourceMappingURL=signal-low.js.map