diff --git a/node_modules/@types/supercluster/LICENSE b/node_modules/@types/supercluster/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/node_modules/@types/supercluster/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/supercluster/README.md b/node_modules/@types/supercluster/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9c99c80d3eef22456fcb047a60c6750bfb57c4ed --- /dev/null +++ b/node_modules/@types/supercluster/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/supercluster` + +# Summary +This package contains type definitions for supercluster (https://github.com/mapbox/supercluster). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/supercluster. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:36 GMT + * Dependencies: [@types/geojson](https://npmjs.com/package/@types/geojson) + +# Credits +These definitions were written by [Denis Carriere](https://github.com/DenisCarriere), and [Nick Zahn](https://github.com/Manc). diff --git a/node_modules/@types/supercluster/index.d.ts b/node_modules/@types/supercluster/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5d076c9521649f27d5d8df6d86f1db848f8c02b4 --- /dev/null +++ b/node_modules/@types/supercluster/index.d.ts @@ -0,0 +1,185 @@ +import * as GeoJSON from "geojson"; + +export as namespace supercluster; + +declare namespace Supercluster { + interface Options { + /** + * Minimum zoom level at which clusters are generated. + * + * @default 0 + */ + minZoom?: number | undefined; + + /** + * Maximum zoom level at which clusters are generated. + * + * @default 16 + */ + maxZoom?: number | undefined; + + /** + * Minimum number of points to form a cluster. + * + * @default 2 + */ + minPoints?: number | undefined; + + /** + * Cluster radius, in pixels. + * + * @default 40 + */ + radius?: number | undefined; + + /** + * (Tiles) Tile extent. Radius is calculated relative to this value. + * + * @default 512 + */ + extent?: number | undefined; + + /** + * Size of the KD-tree leaf node. Affects performance. + * + * @default 64 + */ + nodeSize?: number | undefined; + + /** + * Whether timing info should be logged. + * + * @default false + */ + log?: boolean | undefined; + + /** + * Whether to generate ids for input features in vector tiles. + * + * @default false + */ + generateId?: boolean | undefined; + + /** + * A function that returns cluster properties corresponding to a single point. + * + * @example + * (props) => ({sum: props.myValue}) + */ + map?: ((props: P) => C) | undefined; + + /** + * A reduce function that merges properties of two clusters into one. + * + * @example + * (accumulated, props) => { accumulated.sum += props.sum; } + */ + reduce?: ((accumulated: C, props: Readonly) => void) | undefined; + } + + /** + * Default properties type, allowing any properties. + * Try to avoid this for better typesafety by using proper types. + */ + interface AnyProps { + [name: string]: any; + } + + /** + * [GeoJSON Feature](https://tools.ietf.org/html/rfc7946#section-3.2), + * with the geometry being a + * [GeoJSON Point](https://tools.ietf.org/html/rfc7946#section-3.1.2). + */ + type PointFeature

= GeoJSON.Feature; + + interface ClusterProperties { + /** + * Always `true` to indicate that the Feature is a Cluster and not + * an individual point. + */ + cluster: true; + /** Cluster ID */ + cluster_id: number; + /** Number of points in the cluster. */ + point_count: number; + /** + * Abbreviated number of points in the cluster as string if the number + * is 1000 or greater (e.g. `1.3k` if the number is 1298). + * + * For less than 1000 points it is the same value as `point_count`. + */ + point_count_abbreviated: string | number; + } + + type ClusterFeature = PointFeature; + + interface TileFeature { + type: 1; + geometry: Array<[number, number]>; + tags: (ClusterProperties & C) | P; + } + + interface Tile { + features: Array>; + } +} + +/** + * A very fast geospatial point clustering library for browsers and Node. + */ +declare class Supercluster< + P extends GeoJSON.GeoJsonProperties = Supercluster.AnyProps, + C extends GeoJSON.GeoJsonProperties = Supercluster.AnyProps, +> { + constructor(options?: Supercluster.Options); + + /** + * Loads an array of GeoJSON Feature objects. Each feature's geometry + * must be a GeoJSON Point. Once loaded, index is immutable. + * + * @param points Array of GeoJSON Features, the geometries being GeoJSON Points. + */ + load(points: Array>): Supercluster; + + /** + * Returns an array of clusters and points as `GeoJSON.Feature` objects + * for the given bounding box (`bbox`) and zoom level (`zoom`). + * + * @param bbox Bounding box (`[westLng, southLat, eastLng, northLat]`). + * @param zoom Zoom level. + */ + getClusters(bbox: GeoJSON.BBox, zoom: number): Array | Supercluster.PointFeature

>; + + /** + * For a given zoom and x/y coordinates, returns a + * [geojson-vt](https://github.com/mapbox/geojson-vt)-compatible JSON + * tile object with cluster any point features. + */ + getTile(zoom: number, x: number, y: number): Supercluster.Tile | null; + + /** + * Returns the children of a cluster (on the next zoom level). + * + * @param clusterId Cluster ID (`cluster_id` value from feature properties). + * @throws {Error} If `clusterId` does not exist. + */ + getChildren(clusterId: number): Array | Supercluster.PointFeature

>; + + /** + * Returns all the points of a cluster (with pagination support). + * + * @param clusterId Cluster ID (`cluster_id` value from feature properties). + * @param limit The number of points to return (set to `Infinity` for all points). + * @param offset The amount of points to skip (for pagination). + */ + getLeaves(clusterId: number, limit?: number, offset?: number): Array>; + + /** + * Returns the zoom level on which the cluster expands into several + * children (useful for "click to zoom" feature). + * + * @param clusterId Cluster ID (`cluster_id` value from feature properties). + */ + getClusterExpansionZoom(clusterId: number): number; +} +export = Supercluster; diff --git a/node_modules/@types/supercluster/package.json b/node_modules/@types/supercluster/package.json new file mode 100644 index 0000000000000000000000000000000000000000..cc6559fcb2cb7b12320d5b9cd37f2141aa92744f --- /dev/null +++ b/node_modules/@types/supercluster/package.json @@ -0,0 +1,32 @@ +{ + "name": "@types/supercluster", + "version": "7.1.3", + "description": "TypeScript definitions for supercluster", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/supercluster", + "license": "MIT", + "contributors": [ + { + "name": "Denis Carriere", + "githubUsername": "DenisCarriere", + "url": "https://github.com/DenisCarriere" + }, + { + "name": "Nick Zahn", + "githubUsername": "Manc", + "url": "https://github.com/Manc" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/supercluster" + }, + "scripts": {}, + "dependencies": { + "@types/geojson": "*" + }, + "typesPublisherContentHash": "883fb7311fcd4f97d0f1472bc6b1c31899cd1888f8ba52ccc2a2e4022ca85d22", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/node_modules/@types/supertest/LICENSE b/node_modules/@types/supertest/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/node_modules/@types/supertest/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/supertest/README.md b/node_modules/@types/supertest/README.md new file mode 100644 index 0000000000000000000000000000000000000000..39daba899118891610ca3eb767b0b0fb1c5dec8a --- /dev/null +++ b/node_modules/@types/supertest/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/supertest` + +# Summary +This package contains type definitions for supertest (https://github.com/visionmedia/supertest). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/supertest. + +### Additional Details + * Last updated: Mon, 24 Mar 2025 14:36:45 GMT + * Dependencies: [@types/methods](https://npmjs.com/package/@types/methods), [@types/superagent](https://npmjs.com/package/@types/superagent) + +# Credits +These definitions were written by [Alex Varju](https://github.com/varju), [Petteri Parkkila](https://github.com/pietu), and [David Tanner](https://github.com/DavidTanner). diff --git a/node_modules/@types/supertest/index.d.ts b/node_modules/@types/supertest/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dc4991ae48ccb58a61a79eee606575d321c5ff32 --- /dev/null +++ b/node_modules/@types/supertest/index.d.ts @@ -0,0 +1,38 @@ +import superagent = require("superagent"); +import stAgent = require("./lib/agent"); +import STest = require("./lib/test"); +import { AgentOptions as STAgentOptions, App } from "./types"; + +declare const supertest: supertest.SuperTestStatic; + +declare namespace supertest { + type Response = superagent.Response; + + type Request = superagent.SuperAgentRequest; + + type CallbackHandler = superagent.CallbackHandler; + + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface Test extends STest {} + + // eslint-disable-next-line @typescript-eslint/no-empty-interface + interface Agent extends stAgent {} + + interface Options { + http2?: boolean; + } + + type AgentOptions = STAgentOptions; + + type SuperTest = superagent.SuperAgent; + + type SuperAgentTest = SuperTest; + + interface SuperTestStatic { + (app: App, options?: STAgentOptions): stAgent; + Test: typeof STest; + agent: typeof stAgent & ((app?: App, options?: STAgentOptions) => InstanceType); + } +} + +export = supertest; diff --git a/node_modules/@types/supertest/lib/agent.d.ts b/node_modules/@types/supertest/lib/agent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..12edf4dfeb3c0983b44487386b8e7ac4f7b3f4c3 --- /dev/null +++ b/node_modules/@types/supertest/lib/agent.d.ts @@ -0,0 +1,152 @@ +import superagent = require("superagent"); +import { Test } from "../index"; +import { AgentOptions, App } from "../types"; + +declare class TestAgent extends superagent.agent { + constructor( + app?: App, + options?: AgentOptions, + ); + + host(host: string): this; + + "M-SEARCH"(url: string): Req; + + "m-search"(url: string): Req; + + ACL(url: string): Req; + + BIND(url: string): Req; + + CHECKOUT(url: string): Req; + + CONNECT(url: string): Req; + + COPY(url: string): Req; + + DELETE(url: string): Req; + + GET(url: string): Req; + + HEAD(url: string): Req; + + LINK(url: string): Req; + + LOCK(url: string): Req; + + MERGE(url: string): Req; + + MKACTIVITY(url: string): Req; + + MKCALENDAR(url: string): Req; + + MKCOL(url: string): Req; + + MOVE(url: string): Req; + + NOTIFY(url: string): Req; + + OPTIONS(url: string): Req; + + PATCH(url: string): Req; + + POST(url: string): Req; + + PROPFIND(url: string): Req; + + PROPPATCH(url: string): Req; + + PURGE(url: string): Req; + + PUT(url: string): Req; + + REBIND(url: string): Req; + + REPORT(url: string): Req; + + SEARCH(url: string): Req; + + SOURCE(url: string): Req; + + SUBSCRIBE(url: string): Req; + + TRACE(url: string): Req; + + UNBIND(url: string): Req; + + UNLINK(url: string): Req; + + UNLOCK(url: string): Req; + + UNSUBSCRIBE(url: string): Req; + + acl(url: string): Req; + + bind(url: string): Req; + + checkout(url: string): Req; + + connect(url: string): Req; + + copy(url: string): Req; + + del(url: string): Req; + + delete(url: string): Req; + + get(url: string): Req; + + head(url: string): Req; + + link(url: string): Req; + + lock(url: string): Req; + + merge(url: string): Req; + + mkactivity(url: string): Req; + + mkcalendar(url: string): Req; + + mkcol(url: string): Req; + + move(url: string): Req; + + notify(url: string): Req; + + options(url: string): Req; + + patch(url: string): Req; + + post(url: string): Req; + + propfind(url: string): Req; + + proppatch(url: string): Req; + + purge(url: string): Req; + + put(url: string): Req; + + rebind(url: string): Req; + + report(url: string): Req; + + search(url: string): Req; + + source(url: string): Req; + + subscribe(url: string): Req; + + trace(url: string): Req; + + unbind(url: string): Req; + + unlink(url: string): Req; + + unlock(url: string): Req; + + unsubscribe(url: string): Req; +} + +export = TestAgent; diff --git a/node_modules/@types/supertest/lib/test.d.ts b/node_modules/@types/supertest/lib/test.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..123cd27568f1fd81aa27adb77fc552b8ef38e491 --- /dev/null +++ b/node_modules/@types/supertest/lib/test.d.ts @@ -0,0 +1,22 @@ +import { CallbackHandler, Request, Response } from "superagent"; +import { App } from "../types"; + +declare class Test extends Request { + constructor(app: App, method: string, path: string); + app: App; + url: string; + + serverAddress(app: App, path: string): string; + + expect(status: number, callback?: CallbackHandler): this; + expect(status: number, body: any, callback?: CallbackHandler): this; + expect(checker: (res: Response) => any, callback?: CallbackHandler): this; + expect(body: string, callback?: CallbackHandler): this; + expect(body: RegExp, callback?: CallbackHandler): this; + expect(body: object, callback?: CallbackHandler): this; + expect(field: string, val: string, callback?: CallbackHandler): this; + expect(field: string, val: RegExp, callback?: CallbackHandler): this; + end(callback?: CallbackHandler): this; +} + +export = Test; diff --git a/node_modules/@types/supertest/package.json b/node_modules/@types/supertest/package.json new file mode 100644 index 0000000000000000000000000000000000000000..53da44415fcc873acf34635fc9c96109dbb7de69 --- /dev/null +++ b/node_modules/@types/supertest/package.json @@ -0,0 +1,39 @@ +{ + "name": "@types/supertest", + "version": "6.0.3", + "description": "TypeScript definitions for supertest", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/supertest", + "license": "MIT", + "contributors": [ + { + "name": "Alex Varju", + "githubUsername": "varju", + "url": "https://github.com/varju" + }, + { + "name": "Petteri Parkkila", + "githubUsername": "pietu", + "url": "https://github.com/pietu" + }, + { + "name": "David Tanner", + "githubUsername": "DavidTanner", + "url": "https://github.com/DavidTanner" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/supertest" + }, + "scripts": {}, + "dependencies": { + "@types/methods": "^1.1.4", + "@types/superagent": "^8.1.0" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "af2a0cb3057b367259b4ef29c5307e259132de91fa0cd17d5d2910051690bdc4", + "typeScriptVersion": "5.0" +} \ No newline at end of file diff --git a/node_modules/@types/supertest/types.d.ts b/node_modules/@types/supertest/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..927fc6ccb37ea53736cac959b11cd45ad4d638c0 --- /dev/null +++ b/node_modules/@types/supertest/types.d.ts @@ -0,0 +1,17 @@ +import { AgentOptions as SAgentOptions } from "superagent"; +import methods = require("methods"); +import { IncomingMessage, RequestListener, ServerResponse } from "http"; +import { Http2ServerRequest, Http2ServerResponse } from "http2"; +import { Server } from "net"; + +export type App = + | Server + | RequestListener + | ((request: Http2ServerRequest, response: Http2ServerResponse) => void | Promise) + | string; + +export interface AgentOptions extends SAgentOptions { + http2?: boolean; +} + +export type AllMethods = typeof methods[number] | "del"; diff --git a/node_modules/@types/trusted-types/LICENSE b/node_modules/@types/trusted-types/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/node_modules/@types/trusted-types/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/trusted-types/README.md b/node_modules/@types/trusted-types/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fb376e79031191dad8148ce0e692f83cab2f8687 --- /dev/null +++ b/node_modules/@types/trusted-types/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/trusted-types` + +# Summary +This package contains type definitions for trusted-types (https://github.com/WICG/trusted-types). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/trusted-types. + +### Additional Details + * Last updated: Mon, 20 Nov 2023 23:36:24 GMT + * Dependencies: none + +# Credits +These definitions were written by [Jakub Vrana](https://github.com/vrana), [Damien Engels](https://github.com/engelsdamien), [Emanuel Tesar](https://github.com/siegrift), [Bjarki](https://github.com/bjarkler), and [Sebastian Silbermann](https://github.com/eps1lon). diff --git a/node_modules/@types/trusted-types/index.d.ts b/node_modules/@types/trusted-types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..18ab043a3eea44395798ce7c6cbcfcebb7183665 --- /dev/null +++ b/node_modules/@types/trusted-types/index.d.ts @@ -0,0 +1,53 @@ +import * as lib from "./lib"; + +// Re-export the type definitions globally. +declare global { + // eslint-disable-next-line @typescript-eslint/no-empty-interface -- interface to allow module augmentation + interface TrustedHTML extends lib.TrustedHTML {} + // eslint-disable-next-line @typescript-eslint/no-empty-interface -- interface to allow module augmentation + interface TrustedScript extends lib.TrustedScript {} + // eslint-disable-next-line @typescript-eslint/no-empty-interface -- interface to allow module augmentation + interface TrustedScriptURL extends lib.TrustedScriptURL {} + + // eslint-disable-next-line @typescript-eslint/no-empty-interface -- interface to allow module augmentation + interface TrustedTypePolicy extends lib.TrustedTypePolicy {} + + // eslint-disable-next-line @typescript-eslint/no-empty-interface -- interface to allow module augmentation + interface TrustedTypePolicyFactory extends lib.TrustedTypePolicyFactory {} + + // eslint-disable-next-line @typescript-eslint/no-empty-interface -- interface to allow module augmentation + interface TrustedTypePolicyOptions extends lib.TrustedTypePolicyOptions {} + + // Attach the relevant Trusted Types properties to the Window object. + // eslint-disable-next-line @typescript-eslint/no-empty-interface -- interface to allow module augmentation + interface Window extends lib.TrustedTypesWindow {} +} + +// These are the available exports when using the polyfill as npm package (e.g. in nodejs) +interface InternalTrustedTypePolicyFactory extends lib.TrustedTypePolicyFactory { + TrustedHTML: typeof lib.TrustedHTML; + TrustedScript: typeof lib.TrustedScript; + TrustedScriptURL: typeof lib.TrustedScriptURL; +} + +declare const trustedTypes: InternalTrustedTypePolicyFactory; + +declare class TrustedTypesEnforcer { + constructor(config: TrustedTypeConfig); + install: () => void; + uninstall: () => void; +} + +// tslint:disable-next-line no-unnecessary-class +declare class TrustedTypeConfig { + constructor( + isLoggingEnabled: boolean, + isEnforcementEnabled: boolean, + allowedPolicyNames: string[], + allowDuplicates: boolean, + cspString?: string | null, + windowObject?: Window, + ); +} + +export { TrustedTypeConfig, TrustedTypePolicy, TrustedTypePolicyFactory, trustedTypes, TrustedTypesEnforcer }; diff --git a/node_modules/@types/trusted-types/lib/index.d.ts b/node_modules/@types/trusted-types/lib/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c7ccd4b8063129830ff54851b0084de8826fab9 --- /dev/null +++ b/node_modules/@types/trusted-types/lib/index.d.ts @@ -0,0 +1,64 @@ +// The main type definitions. Packages that do not want to pollute the global +// scope with Trusted Types (e.g. libraries whose users may not be using Trusted +// Types) can import the types directly from 'trusted-types/lib'. + +export type FnNames = keyof TrustedTypePolicyOptions; +export type Args = Parameters>; + +export class TrustedHTML { + private constructor(); // To prevent instantiting with 'new'. + private brand: true; // To prevent structural typing. +} + +export class TrustedScript { + private constructor(); // To prevent instantiting with 'new'. + private brand: true; // To prevent structural typing. +} + +export class TrustedScriptURL { + private constructor(); // To prevent instantiting with 'new'. + private brand: true; // To prevent structural typing. +} + +export abstract class TrustedTypePolicyFactory { + createPolicy( + policyName: string, + policyOptions?: Options, + ): Pick, "name" | Extract>; + isHTML(value: unknown): value is TrustedHTML; + isScript(value: unknown): value is TrustedScript; + isScriptURL(value: unknown): value is TrustedScriptURL; + readonly emptyHTML: TrustedHTML; + readonly emptyScript: TrustedScript; + getAttributeType(tagName: string, attribute: string, elementNs?: string, attrNs?: string): string | null; + getPropertyType(tagName: string, property: string, elementNs?: string): string | null; + readonly defaultPolicy: TrustedTypePolicy | null; +} + +export abstract class TrustedTypePolicy { + readonly name: string; + createHTML(...args: Args): TrustedHTML; + createScript(...args: Args): TrustedScript; + createScriptURL(...args: Args): TrustedScriptURL; +} + +export interface TrustedTypePolicyOptions { + createHTML?: ((input: string, ...arguments: any[]) => string) | undefined; + createScript?: ((input: string, ...arguments: any[]) => string) | undefined; + createScriptURL?: ((input: string, ...arguments: any[]) => string) | undefined; +} + +// The Window object is augmented with the following properties in browsers that +// support Trusted Types. Users of the 'trusted-types/lib' entrypoint can cast +// window as TrustedTypesWindow to access these properties. +export interface TrustedTypesWindow { + // `trustedTypes` is left intentionally optional to make sure that + // people handle the case when their code is running in a browser not + // supporting trustedTypes. + trustedTypes?: TrustedTypePolicyFactory | undefined; + TrustedHTML: typeof TrustedHTML; + TrustedScript: typeof TrustedScript; + TrustedScriptURL: typeof TrustedScriptURL; + TrustedTypePolicyFactory: typeof TrustedTypePolicyFactory; + TrustedTypePolicy: typeof TrustedTypePolicy; +} diff --git a/node_modules/@types/trusted-types/package.json b/node_modules/@types/trusted-types/package.json new file mode 100644 index 0000000000000000000000000000000000000000..eda8c7302771afb2cf181ea1574fff448ebfb8f0 --- /dev/null +++ b/node_modules/@types/trusted-types/package.json @@ -0,0 +1,45 @@ +{ + "name": "@types/trusted-types", + "version": "2.0.7", + "description": "TypeScript definitions for trusted-types", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/trusted-types", + "license": "MIT", + "contributors": [ + { + "name": "Jakub Vrana", + "githubUsername": "vrana", + "url": "https://github.com/vrana" + }, + { + "name": "Damien Engels", + "githubUsername": "engelsdamien", + "url": "https://github.com/engelsdamien" + }, + { + "name": "Emanuel Tesar", + "githubUsername": "siegrift", + "url": "https://github.com/siegrift" + }, + { + "name": "Bjarki", + "githubUsername": "bjarkler", + "url": "https://github.com/bjarkler" + }, + { + "name": "Sebastian Silbermann", + "githubUsername": "eps1lon", + "url": "https://github.com/eps1lon" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/trusted-types" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "20982c5e0452e662515e29b41f7be5a3c69e5918a9228929a563d9f1dfdfbbc5", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/node_modules/@types/unist/LICENSE b/node_modules/@types/unist/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/node_modules/@types/unist/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/unist/README.md b/node_modules/@types/unist/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b84e51bfb836f999b47b6d8e233b64cb372e48df --- /dev/null +++ b/node_modules/@types/unist/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/unist` + +# Summary +This package contains type definitions for unist (https://github.com/syntax-tree/unist). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/unist. + +### Additional Details + * Last updated: Thu, 15 Aug 2024 02:18:53 GMT + * Dependencies: none + +# Credits +These definitions were written by [bizen241](https://github.com/bizen241), [Jun Lu](https://github.com/lujun2), [Hernan Rajchert](https://github.com/hrajchert), [Titus Wormer](https://github.com/wooorm), [Junyoung Choi](https://github.com/rokt33r), [Ben Moon](https://github.com/GuiltyDolphin), [JounQin](https://github.com/JounQin), and [Remco Haszing](https://github.com/remcohaszing). diff --git a/node_modules/@types/unist/index.d.ts b/node_modules/@types/unist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..513ddee5e9e2acb1e5c88c26da384212e52ed90b --- /dev/null +++ b/node_modules/@types/unist/index.d.ts @@ -0,0 +1,119 @@ +// ## Interfaces + +/** + * Info associated with nodes by the ecosystem. + * + * This space is guaranteed to never be specified by unist or specifications + * implementing unist. + * But you can use it in utilities and plugins to store data. + * + * This type can be augmented to register custom data. + * For example: + * + * ```ts + * declare module 'unist' { + * interface Data { + * // `someNode.data.myId` is typed as `number | undefined` + * myId?: number | undefined + * } + * } + * ``` + */ +export interface Data {} + +/** + * One place in a source file. + */ +export interface Point { + /** + * Line in a source file (1-indexed integer). + */ + line: number; + + /** + * Column in a source file (1-indexed integer). + */ + column: number; + /** + * Character in a source file (0-indexed integer). + */ + offset?: number | undefined; +} + +/** + * Position of a node in a source document. + * + * A position is a range between two points. + */ +export interface Position { + /** + * Place of the first character of the parsed source region. + */ + start: Point; + + /** + * Place of the first character after the parsed source region. + */ + end: Point; +} + +// ## Abstract nodes + +/** + * Abstract unist node that contains the smallest possible value. + * + * This interface is supposed to be extended. + * + * For example, in HTML, a `text` node is a leaf that contains text. + */ +export interface Literal extends Node { + /** + * Plain value. + */ + value: unknown; +} + +/** + * Abstract unist node. + * + * The syntactic unit in unist syntax trees are called nodes. + * + * This interface is supposed to be extended. + * If you can use {@link Literal} or {@link Parent}, you should. + * But for example in markdown, a `thematicBreak` (`***`), is neither literal + * nor parent, but still a node. + */ +export interface Node { + /** + * Node type. + */ + type: string; + + /** + * Info from the ecosystem. + */ + data?: Data | undefined; + + /** + * Position of a node in a source document. + * + * Nodes that are generated (not in the original source document) must not + * have a position. + */ + position?: Position | undefined; +} + +/** + * Abstract unist node that contains other nodes (*children*). + * + * This interface is supposed to be extended. + * + * For example, in XML, an element is a parent of different things, such as + * comments, text, and further elements. + */ +export interface Parent extends Node { + /** + * List of children. + */ + children: Node[]; +} diff --git a/node_modules/@types/unist/package.json b/node_modules/@types/unist/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d2092dba8f2208817af3e1811569d90b6358ad8f --- /dev/null +++ b/node_modules/@types/unist/package.json @@ -0,0 +1,60 @@ +{ + "name": "@types/unist", + "version": "3.0.3", + "description": "TypeScript definitions for unist", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/unist", + "license": "MIT", + "contributors": [ + { + "name": "bizen241", + "githubUsername": "bizen241", + "url": "https://github.com/bizen241" + }, + { + "name": "Jun Lu", + "githubUsername": "lujun2", + "url": "https://github.com/lujun2" + }, + { + "name": "Hernan Rajchert", + "githubUsername": "hrajchert", + "url": "https://github.com/hrajchert" + }, + { + "name": "Titus Wormer", + "githubUsername": "wooorm", + "url": "https://github.com/wooorm" + }, + { + "name": "Junyoung Choi", + "githubUsername": "rokt33r", + "url": "https://github.com/rokt33r" + }, + { + "name": "Ben Moon", + "githubUsername": "GuiltyDolphin", + "url": "https://github.com/GuiltyDolphin" + }, + { + "name": "JounQin", + "githubUsername": "JounQin", + "url": "https://github.com/JounQin" + }, + { + "name": "Remco Haszing", + "githubUsername": "remcohaszing", + "url": "https://github.com/remcohaszing" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/unist" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "7f3d5ce8d56003f3583a5317f98d444bdc99910c7b486c6b10af4f38694e61fe", + "typeScriptVersion": "4.8" +} \ No newline at end of file diff --git a/node_modules/@types/unzipper/LICENSE b/node_modules/@types/unzipper/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/node_modules/@types/unzipper/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/unzipper/README.md b/node_modules/@types/unzipper/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4a822305f311d6430e9c97ad6d80f818058772dd --- /dev/null +++ b/node_modules/@types/unzipper/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/unzipper` + +# Summary +This package contains type definitions for unzipper (https://github.com/ZJONSSON/node-unzipper#readme). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/unzipper. + +### Additional Details + * Last updated: Fri, 28 Feb 2025 17:33:47 GMT + * Dependencies: [@types/node](https://npmjs.com/package/@types/node) + +# Credits +These definitions were written by [s73obrien](https://github.com/s73obrien), [Bart](https://github.com/bartje321), and [Ken Human](https://github.com/kenhuman). diff --git a/node_modules/@types/unzipper/index.d.ts b/node_modules/@types/unzipper/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..07324501143a393a954d89c964834ef6cf9d8578 --- /dev/null +++ b/node_modules/@types/unzipper/index.d.ts @@ -0,0 +1,128 @@ +/// + +import { ClientRequest, RequestOptions } from "http"; +import { Duplex, PassThrough, Readable, Stream, Transform } from "stream"; + +export interface PullStream extends Duplex { + stream(eof: number | string, includeEof: boolean): PassThrough; + pull(eof: number | string, includeEof: boolean): Promise; +} + +export interface Entry extends PassThrough { + autodrain(): Transform & { + promise(): Promise; + }; + buffer(): Promise; + path: string; + + props: { + path: string; + }; + + type: string; + vars: { + signature?: number | undefined; + versionsNeededToExtract: number; + flags: number; + compressionMethod: number; + lastModifiedTime: number; + crc32: number; + compressedSize: number; + fileNameLength: number; + extraFieldLength: number; + }; + + extra: { + signature: number; + partsize: number; + uncompressedSize: number; + compressedSize: number; + offset: number; + disknum: number; + }; +} + +export function unzip( + source: { + stream: Readable; + size: () => Promise; + }, + offset: number, + _password: string, +): Entry; + +export namespace Open { + function buffer(data: Buffer): Promise; + function file(filename: string): Promise; + function url( + request: ClientRequest, + opt: string | RequestOptions, + ): Promise; + function s3(client: any, params: any): Promise; + function s3_v3(client: any, params: any): Promise; + function custom( + source: { + size: () => Promise; + stream: (offset: number, length: number) => Readable; + }, + ): Promise; +} + +export function BufferStream(entry: Entry): Promise; + +export interface CentralDirectory { + signature: number; + diskNumber: number; + diskStart: number; + numberOfRecordsOnDisk: number; + numberOfRecords: number; + sizeOfCentralDirectory: number; + offsetToStartOfCentralDirectory: number; + commentLength: number; + files: File[]; + extract: (opts: ParseOptions) => Promise; +} + +export interface File { + signature: number; + versionMadeBy: number; + versionsNeededToExtract: number; + flags: number; + compressionMethod: number; + lastModifiedTime: number; + lastModifiedDate: number; + lastModifiedDateTime: Date; + crc32: number; + compressedSize: number; + uncompressedSize: number; + fileNameLength: number; + extraFieldLength: number; + fileCommentLength: number; + diskNumber: number; + internalFileAttributes: number; + externalFileAttributes: number; + offsetToLocalFileHeader: number; + pathBuffer: Buffer; + path: string; + isUnicode: number; + extra: any; + type: "Directory" | "File"; + comment: string; + stream: (password?: string) => Entry; + buffer: (password?: string) => Promise; +} + +export interface ParseOptions { + verbose?: boolean | undefined; + path?: string | undefined; + concurrency?: number | undefined; + forceStream?: boolean | undefined; +} + +export type ParseStream = PullStream & { + promise(): Promise; +}; + +export function Parse(opts?: ParseOptions): ParseStream; +export function ParseOne(match?: RegExp, opts?: ParseOptions): Duplex; +export function Extract(opts?: ParseOptions): ParseStream; diff --git a/node_modules/@types/unzipper/package.json b/node_modules/@types/unzipper/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3c5e1aeb2357b6d8256ae656fe9327bdef916cd2 --- /dev/null +++ b/node_modules/@types/unzipper/package.json @@ -0,0 +1,38 @@ +{ + "name": "@types/unzipper", + "version": "0.10.11", + "description": "TypeScript definitions for unzipper", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/unzipper", + "license": "MIT", + "contributors": [ + { + "name": "s73obrien", + "githubUsername": "s73obrien", + "url": "https://github.com/s73obrien" + }, + { + "name": "Bart", + "githubUsername": "bartje321", + "url": "https://github.com/bartje321" + }, + { + "name": "Ken Human", + "githubUsername": "kenhuman", + "url": "https://github.com/kenhuman" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/unzipper" + }, + "scripts": {}, + "dependencies": { + "@types/node": "*" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "7412f33ee3fbe532f1ae06c8958ef493820d6cde131f124c0e0484f57b3fb6e0", + "typeScriptVersion": "5.0" +} \ No newline at end of file diff --git a/node_modules/@types/uuid/LICENSE b/node_modules/@types/uuid/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/node_modules/@types/uuid/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/uuid/README.md b/node_modules/@types/uuid/README.md new file mode 100644 index 0000000000000000000000000000000000000000..946ff9931106c1b9921435c41ae91426a0664232 --- /dev/null +++ b/node_modules/@types/uuid/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/uuid` + +# Summary +This package contains type definitions for uuid (https://github.com/uuidjs/uuid). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/uuid. + +### Additional Details + * Last updated: Thu, 20 Jun 2024 21:07:25 GMT + * Dependencies: none + +# Credits +These definitions were written by [Oliver Hoffmann](https://github.com/iamolivinius), [Felipe Ochoa](https://github.com/felipeochoa), [Chris Barth](https://github.com/cjbarth), [Linus Unnebäck](https://github.com/LinusU), and [Christoph Tavan](https://github.com/ctavan). diff --git a/node_modules/@types/uuid/index.d.mts b/node_modules/@types/uuid/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..84bc5bd8d279b06b6947c741648ae872deeda184 --- /dev/null +++ b/node_modules/@types/uuid/index.d.mts @@ -0,0 +1,19 @@ +import uuid from "./index.js"; +export import v1 = uuid.v1; +export import v1ToV6 = uuid.v1ToV6; +export import v3 = uuid.v3; +export import v4 = uuid.v4; +export import v5 = uuid.v5; +export import v6 = uuid.v6; +export import v6ToV1 = uuid.v6ToV1; +export import v7 = uuid.v7; +export import NIL = uuid.NIL; +export import MAX = uuid.MAX; +export import version = uuid.version; +export import validate = uuid.validate; +export import stringify = uuid.stringify; +export import parse = uuid.parse; +export import V1Options = uuid.V1Options; +export import V4Options = uuid.V4Options; +export import V6Options = uuid.V6Options; +export import V7Options = uuid.V7Options; diff --git a/node_modules/@types/uuid/index.d.ts b/node_modules/@types/uuid/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a2edac06fe37b7f1de13d65a8f9b492d9b0c3ab --- /dev/null +++ b/node_modules/@types/uuid/index.d.ts @@ -0,0 +1,113 @@ +// disable automatic export +export {}; + +// Uses ArrayLike to admit Uint8 and co. +type OutputBuffer = ArrayLike; +type InputBuffer = ArrayLike; + +interface RandomOptions { + /** `Array` of 16 random bytes (0-255) */ + random?: InputBuffer | undefined; +} +interface RngOptions { + /** Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) */ + rng?: (() => InputBuffer) | undefined; +} + +interface V1BaseOptions { + /** RFC "node" field as an `Array[6]` of byte values (per 4.1.6) */ + node?: InputBuffer | undefined; + /** RFC "clock sequence" as a `Number` between 0 - 0x3fff */ + clockseq?: number | undefined; + /** RFC "timestamp" field (`Number` of milliseconds, unix epoch) */ + msecs?: number | Date | undefined; + /** RFC "timestamp" field (`Number` of nanoseconds to add to msecs, should be 0-10,000) */ + nsecs?: number | undefined; +} +interface V1RandomOptions extends V1BaseOptions, RandomOptions {} +interface V1RngOptions extends V1BaseOptions, RngOptions {} + +export type V1Options = V1RandomOptions | V1RngOptions; +export type V4Options = RandomOptions | RngOptions; +export type V6Options = V1Options; + +interface V7BaseOptions { + msecs?: number | Date | undefined; + seq?: number; +} +export type V7Options = (RandomOptions | RngOptions) & V7BaseOptions; + +type VToV = ((uuid: string) => string) & ((uuid: OutputBuffer) => Uint8Array); + +type v1String = (options?: V1Options) => string; +type v1Buffer = (options: V1Options | null | undefined, buffer: T, offset?: number) => T; +type v1 = v1Buffer & v1String; + +type v1ToV6 = VToV; + +type v4String = (options?: V4Options) => string; +type v4Buffer = (options: V4Options | null | undefined, buffer: T, offset?: number) => T; +type v4 = v4Buffer & v4String; + +type v3String = (name: string | InputBuffer, namespace: string | InputBuffer) => string; +type v3Buffer = ( + name: string | InputBuffer, + namespace: string | InputBuffer, + buffer: T, + offset?: number, +) => T; +interface v3Static { + // https://github.com/uuidjs/uuid/blob/master/src/v35.js#L16 + DNS: string; + // https://github.com/uuidjs/uuid/blob/master/src/v35.js#L17 + URL: string; +} +type v3 = v3Buffer & v3String & v3Static; + +type v5String = (name: string | InputBuffer, namespace: string | InputBuffer) => string; +type v5Buffer = ( + name: string | InputBuffer, + namespace: string | InputBuffer, + buffer: T, + offset?: number, +) => T; +interface v5Static { + // https://github.com/uuidjs/uuid/blob/master/src/v35.js#L16 + DNS: string; + // https://github.com/uuidjs/uuid/blob/master/src/v35.js#L17 + URL: string; +} +type v5 = v5Buffer & v5String & v5Static; + +type v6String = (options?: V6Options) => string; +type v6Buffer = (options: V6Options | null | undefined, buffer: T, offset?: number) => T; +type v6 = v6Buffer & v6String; + +type v6ToV1 = VToV; + +type v7String = (options?: V7Options) => string; +type v7Buffer = (options: V7Options | null | undefined, buffer: T, offset?: number) => T; +type v7 = v7Buffer & v7String; + +type NIL = string; +type MAX = string; + +type parse = (uuid: string) => Uint8Array; +type stringify = (buffer: InputBuffer, offset?: number) => string; +type validate = (uuid: string) => boolean; +type version = (uuid: string) => number; + +export const NIL: NIL; +export const MAX: MAX; +export const parse: parse; +export const stringify: stringify; +export const v1: v1; +export const v1ToV6: v1ToV6; +export const v3: v3; +export const v4: v4; +export const v5: v5; +export const v6: v6; +export const v6ToV1: v6ToV1; +export const v7: v7; +export const validate: validate; +export const version: version; diff --git a/node_modules/@types/uuid/package.json b/node_modules/@types/uuid/package.json new file mode 100644 index 0000000000000000000000000000000000000000..56acf25cce09f49dfa755b7068c11546cfdce713 --- /dev/null +++ b/node_modules/@types/uuid/package.json @@ -0,0 +1,54 @@ +{ + "name": "@types/uuid", + "version": "10.0.0", + "description": "TypeScript definitions for uuid", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/uuid", + "license": "MIT", + "contributors": [ + { + "name": "Oliver Hoffmann", + "githubUsername": "iamolivinius", + "url": "https://github.com/iamolivinius" + }, + { + "name": "Felipe Ochoa", + "githubUsername": "felipeochoa", + "url": "https://github.com/felipeochoa" + }, + { + "name": "Chris Barth", + "githubUsername": "cjbarth", + "url": "https://github.com/cjbarth" + }, + { + "name": "Linus Unnebäck", + "githubUsername": "LinusU", + "url": "https://github.com/LinusU" + }, + { + "name": "Christoph Tavan", + "githubUsername": "ctavan", + "url": "https://github.com/ctavan" + } + ], + "main": "", + "types": "index.d.ts", + "exports": { + "./package.json": "./package.json", + ".": { + "types": { + "import": "./index.d.mts", + "default": "./index.d.ts" + } + } + }, + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/uuid" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "08fbc5ff7d23aaac1e81b5acf98181d2544ce6ffd5578e9879e2a75f0c087d54", + "typeScriptVersion": "4.7" +} \ No newline at end of file diff --git a/node_modules/@types/ws/LICENSE b/node_modules/@types/ws/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/node_modules/@types/ws/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/ws/README.md b/node_modules/@types/ws/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d5a4a1cb9fcc5bfdd906ab03e3a30a2ab07128c0 --- /dev/null +++ b/node_modules/@types/ws/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/ws` + +# Summary +This package contains type definitions for ws (https://github.com/websockets/ws). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/ws. + +### Additional Details + * Last updated: Tue, 01 Apr 2025 02:59:53 GMT + * Dependencies: [@types/node](https://npmjs.com/package/@types/node) + +# Credits +These definitions were written by [Paul Loyd](https://github.com/loyd), [Margus Lamp](https://github.com/mlamp), [Philippe D'Alva](https://github.com/TitaneBoy), [reduckted](https://github.com/reduckted), [teidesu](https://github.com/teidesu), [Bartosz Wojtkowiak](https://github.com/wojtkowiak), [Kyle Hensel](https://github.com/k-yle), and [Samuel Skeen](https://github.com/cwadrupldijjit). diff --git a/node_modules/@types/ws/index.d.mts b/node_modules/@types/ws/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..8c5dffb560582aaebe7602c9110d4bdb89401097 --- /dev/null +++ b/node_modules/@types/ws/index.d.mts @@ -0,0 +1,451 @@ +/// + +import { EventEmitter } from "events"; +import { + Agent, + ClientRequest, + ClientRequestArgs, + IncomingMessage, + OutgoingHttpHeaders, + Server as HTTPServer, +} from "http"; +import { Server as HTTPSServer } from "https"; +import { createConnection } from "net"; +import { Duplex, DuplexOptions } from "stream"; +import { SecureContextOptions } from "tls"; +import { URL } from "url"; +import { ZlibOptions } from "zlib"; + +// can not get all overload of BufferConstructor['from'], need to copy all it's first arguments here +// https://github.com/microsoft/TypeScript/issues/32164 +type BufferLike = + | string + | Buffer + | DataView + | number + | ArrayBufferView + | Uint8Array + | ArrayBuffer + | SharedArrayBuffer + | Blob + | readonly any[] + | readonly number[] + | { valueOf(): ArrayBuffer } + | { valueOf(): SharedArrayBuffer } + | { valueOf(): Uint8Array } + | { valueOf(): readonly number[] } + | { valueOf(): string } + | { [Symbol.toPrimitive](hint: string): string }; + +// WebSocket socket. +declare class WebSocket extends EventEmitter { + /** The connection is not yet open. */ + static readonly CONNECTING: 0; + /** The connection is open and ready to communicate. */ + static readonly OPEN: 1; + /** The connection is in the process of closing. */ + static readonly CLOSING: 2; + /** The connection is closed. */ + static readonly CLOSED: 3; + + binaryType: "nodebuffer" | "arraybuffer" | "fragments"; + readonly bufferedAmount: number; + readonly extensions: string; + /** Indicates whether the websocket is paused */ + readonly isPaused: boolean; + readonly protocol: string; + /** The current state of the connection */ + readonly readyState: + | typeof WebSocket.CONNECTING + | typeof WebSocket.OPEN + | typeof WebSocket.CLOSING + | typeof WebSocket.CLOSED; + readonly url: string; + + /** The connection is not yet open. */ + readonly CONNECTING: 0; + /** The connection is open and ready to communicate. */ + readonly OPEN: 1; + /** The connection is in the process of closing. */ + readonly CLOSING: 2; + /** The connection is closed. */ + readonly CLOSED: 3; + + onopen: ((event: WebSocket.Event) => void) | null; + onerror: ((event: WebSocket.ErrorEvent) => void) | null; + onclose: ((event: WebSocket.CloseEvent) => void) | null; + onmessage: ((event: WebSocket.MessageEvent) => void) | null; + + constructor(address: null); + constructor(address: string | URL, options?: WebSocket.ClientOptions | ClientRequestArgs); + constructor( + address: string | URL, + protocols?: string | string[], + options?: WebSocket.ClientOptions | ClientRequestArgs, + ); + + close(code?: number, data?: string | Buffer): void; + ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void; + pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void; + // https://github.com/websockets/ws/issues/2076#issuecomment-1250354722 + send(data: BufferLike, cb?: (err?: Error) => void): void; + send( + data: BufferLike, + options: { + mask?: boolean | undefined; + binary?: boolean | undefined; + compress?: boolean | undefined; + fin?: boolean | undefined; + }, + cb?: (err?: Error) => void, + ): void; + terminate(): void; + + /** + * Pause the websocket causing it to stop emitting events. Some events can still be + * emitted after this is called, until all buffered data is consumed. This method + * is a noop if the ready state is `CONNECTING` or `CLOSED`. + */ + pause(): void; + /** + * Make a paused socket resume emitting events. This method is a noop if the ready + * state is `CONNECTING` or `CLOSED`. + */ + resume(): void; + + // HTML5 WebSocket events + addEventListener( + type: K, + listener: + | ((event: WebSocket.WebSocketEventMap[K]) => void) + | { handleEvent(event: WebSocket.WebSocketEventMap[K]): void }, + options?: WebSocket.EventListenerOptions, + ): void; + removeEventListener( + type: K, + listener: + | ((event: WebSocket.WebSocketEventMap[K]) => void) + | { handleEvent(event: WebSocket.WebSocketEventMap[K]): void }, + ): void; + + // Events + on(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this; + on(event: "error", listener: (this: WebSocket, error: Error) => void): this; + on(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this; + on(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this; + on(event: "open", listener: (this: WebSocket) => void): this; + on(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this; + on(event: "redirect", listener: (this: WebSocket, url: string, request: ClientRequest) => void): this; + on( + event: "unexpected-response", + listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void, + ): this; + on(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this; + + once(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this; + once(event: "error", listener: (this: WebSocket, error: Error) => void): this; + once(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this; + once(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this; + once(event: "open", listener: (this: WebSocket) => void): this; + once(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this; + once(event: "redirect", listener: (this: WebSocket, url: string, request: ClientRequest) => void): this; + once( + event: "unexpected-response", + listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void, + ): this; + once(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this; + + off(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this; + off(event: "error", listener: (this: WebSocket, error: Error) => void): this; + off(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this; + off(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this; + off(event: "open", listener: (this: WebSocket) => void): this; + off(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this; + off(event: "redirect", listener: (this: WebSocket, url: string, request: ClientRequest) => void): this; + off( + event: "unexpected-response", + listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void, + ): this; + off(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this; + + addListener(event: "close", listener: (code: number, reason: Buffer) => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "upgrade", listener: (request: IncomingMessage) => void): this; + addListener(event: "message", listener: (data: WebSocket.RawData, isBinary: boolean) => void): this; + addListener(event: "open", listener: () => void): this; + addListener(event: "ping" | "pong", listener: (data: Buffer) => void): this; + addListener(event: "redirect", listener: (url: string, request: ClientRequest) => void): this; + addListener( + event: "unexpected-response", + listener: (request: ClientRequest, response: IncomingMessage) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: (code: number, reason: Buffer) => void): this; + removeListener(event: "error", listener: (error: Error) => void): this; + removeListener(event: "upgrade", listener: (request: IncomingMessage) => void): this; + removeListener(event: "message", listener: (data: WebSocket.RawData, isBinary: boolean) => void): this; + removeListener(event: "open", listener: () => void): this; + removeListener(event: "ping" | "pong", listener: (data: Buffer) => void): this; + removeListener(event: "redirect", listener: (url: string, request: ClientRequest) => void): this; + removeListener( + event: "unexpected-response", + listener: (request: ClientRequest, response: IncomingMessage) => void, + ): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; +} + +declare namespace WebSocket { + /** + * Data represents the raw message payload received over the WebSocket. + */ + type RawData = Buffer | ArrayBuffer | Buffer[]; + + /** + * Data represents the message payload received over the WebSocket. + */ + type Data = string | Buffer | ArrayBuffer | Buffer[]; + + /** + * CertMeta represents the accepted types for certificate & key data. + */ + type CertMeta = string | string[] | Buffer | Buffer[]; + + /** + * VerifyClientCallbackSync is a synchronous callback used to inspect the + * incoming message. The return value (boolean) of the function determines + * whether or not to accept the handshake. + */ + type VerifyClientCallbackSync = (info: { + origin: string; + secure: boolean; + req: Request; + }) => boolean; + + /** + * VerifyClientCallbackAsync is an asynchronous callback used to inspect the + * incoming message. The return value (boolean) of the function determines + * whether or not to accept the handshake. + */ + type VerifyClientCallbackAsync = ( + info: { origin: string; secure: boolean; req: Request }, + callback: (res: boolean, code?: number, message?: string, headers?: OutgoingHttpHeaders) => void, + ) => void; + + /** + * FinishRequestCallback is a callback for last minute customization of the + * headers. If finishRequest is set, then it has the responsibility to call + * request.end() once it is done setting request headers. + */ + type FinishRequestCallback = (request: ClientRequest, websocket: WebSocket) => void; + + interface ClientOptions extends SecureContextOptions { + protocol?: string | undefined; + followRedirects?: boolean | undefined; + generateMask?(mask: Buffer): void; + handshakeTimeout?: number | undefined; + maxRedirects?: number | undefined; + perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined; + localAddress?: string | undefined; + protocolVersion?: number | undefined; + headers?: { [key: string]: string } | undefined; + origin?: string | undefined; + agent?: Agent | undefined; + host?: string | undefined; + family?: number | undefined; + checkServerIdentity?(servername: string, cert: CertMeta): boolean; + rejectUnauthorized?: boolean | undefined; + allowSynchronousEvents?: boolean | undefined; + autoPong?: boolean | undefined; + maxPayload?: number | undefined; + skipUTF8Validation?: boolean | undefined; + createConnection?: typeof createConnection | undefined; + finishRequest?: FinishRequestCallback | undefined; + } + + interface PerMessageDeflateOptions { + serverNoContextTakeover?: boolean | undefined; + clientNoContextTakeover?: boolean | undefined; + serverMaxWindowBits?: number | undefined; + clientMaxWindowBits?: number | undefined; + zlibDeflateOptions?: + | { + flush?: number | undefined; + finishFlush?: number | undefined; + chunkSize?: number | undefined; + windowBits?: number | undefined; + level?: number | undefined; + memLevel?: number | undefined; + strategy?: number | undefined; + dictionary?: Buffer | Buffer[] | DataView | undefined; + info?: boolean | undefined; + } + | undefined; + zlibInflateOptions?: ZlibOptions | undefined; + threshold?: number | undefined; + concurrencyLimit?: number | undefined; + } + + interface Event { + type: string; + target: WebSocket; + } + + interface ErrorEvent { + error: any; + message: string; + type: string; + target: WebSocket; + } + + interface CloseEvent { + wasClean: boolean; + code: number; + reason: string; + type: string; + target: WebSocket; + } + + interface MessageEvent { + data: Data; + type: string; + target: WebSocket; + } + + interface WebSocketEventMap { + open: Event; + error: ErrorEvent; + close: CloseEvent; + message: MessageEvent; + } + + interface EventListenerOptions { + once?: boolean | undefined; + } + + interface ServerOptions< + U extends typeof WebSocket = typeof WebSocket, + V extends typeof IncomingMessage = typeof IncomingMessage, + > { + host?: string | undefined; + port?: number | undefined; + backlog?: number | undefined; + server?: HTTPServer | HTTPSServer | undefined; + verifyClient?: + | VerifyClientCallbackAsync> + | VerifyClientCallbackSync> + | undefined; + handleProtocols?: (protocols: Set, request: InstanceType) => string | false; + path?: string | undefined; + noServer?: boolean | undefined; + allowSynchronousEvents?: boolean | undefined; + autoPong?: boolean | undefined; + clientTracking?: boolean | undefined; + perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined; + maxPayload?: number | undefined; + skipUTF8Validation?: boolean | undefined; + WebSocket?: U | undefined; + } + + interface AddressInfo { + address: string; + family: string; + port: number; + } +} + +export import AddressInfo = WebSocket.AddressInfo; +export import CertMeta = WebSocket.CertMeta; +export import ClientOptions = WebSocket.ClientOptions; +export import CloseEvent = WebSocket.CloseEvent; +export import Data = WebSocket.Data; +export import ErrorEvent = WebSocket.ErrorEvent; +export import Event = WebSocket.Event; +export import EventListenerOptions = WebSocket.EventListenerOptions; +export import FinishRequestCallback = WebSocket.FinishRequestCallback; +export import MessageEvent = WebSocket.MessageEvent; +export import PerMessageDeflateOptions = WebSocket.PerMessageDeflateOptions; +export import RawData = WebSocket.RawData; +export import ServerOptions = WebSocket.ServerOptions; +export import VerifyClientCallbackAsync = WebSocket.VerifyClientCallbackAsync; +export import VerifyClientCallbackSync = WebSocket.VerifyClientCallbackSync; + +// WebSocket Server +declare class Server< + T extends typeof WebSocket = typeof WebSocket, + U extends typeof IncomingMessage = typeof IncomingMessage, +> extends EventEmitter { + options: WebSocket.ServerOptions; + path: string; + clients: Set>; + + constructor(options?: WebSocket.ServerOptions, callback?: () => void); + + address(): WebSocket.AddressInfo | string | null; + close(cb?: (err?: Error) => void): void; + handleUpgrade( + request: InstanceType, + socket: Duplex, + upgradeHead: Buffer, + callback: (client: InstanceType, request: InstanceType) => void, + ): void; + shouldHandle(request: InstanceType): boolean | Promise; + + // Events + on(event: "connection", cb: (this: Server, websocket: InstanceType, request: InstanceType) => void): this; + on(event: "error", cb: (this: Server, error: Error) => void): this; + on(event: "headers", cb: (this: Server, headers: string[], request: InstanceType) => void): this; + on(event: "close" | "listening", cb: (this: Server) => void): this; + on( + event: "wsClientError", + cb: (this: Server, error: Error, socket: Duplex, request: InstanceType) => void, + ): this; + on(event: string | symbol, listener: (this: Server, ...args: any[]) => void): this; + + once( + event: "connection", + cb: (this: Server, websocket: InstanceType, request: InstanceType) => void, + ): this; + once(event: "error", cb: (this: Server, error: Error) => void): this; + once(event: "headers", cb: (this: Server, headers: string[], request: InstanceType) => void): this; + once(event: "close" | "listening", cb: (this: Server) => void): this; + once( + event: "wsClientError", + cb: (this: Server, error: Error, socket: Duplex, request: InstanceType) => void, + ): this; + once(event: string | symbol, listener: (this: Server, ...args: any[]) => void): this; + + off(event: "connection", cb: (this: Server, websocket: InstanceType, request: InstanceType) => void): this; + off(event: "error", cb: (this: Server, error: Error) => void): this; + off(event: "headers", cb: (this: Server, headers: string[], request: InstanceType) => void): this; + off(event: "close" | "listening", cb: (this: Server) => void): this; + off( + event: "wsClientError", + cb: (this: Server, error: Error, socket: Duplex, request: InstanceType) => void, + ): this; + off(event: string | symbol, listener: (this: Server, ...args: any[]) => void): this; + + addListener(event: "connection", cb: (websocket: InstanceType, request: InstanceType) => void): this; + addListener(event: "error", cb: (error: Error) => void): this; + addListener(event: "headers", cb: (headers: string[], request: InstanceType) => void): this; + addListener(event: "close" | "listening", cb: () => void): this; + addListener(event: "wsClientError", cb: (error: Error, socket: Duplex, request: InstanceType) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "connection", cb: (websocket: InstanceType, request: InstanceType) => void): this; + removeListener(event: "error", cb: (error: Error) => void): this; + removeListener(event: "headers", cb: (headers: string[], request: InstanceType) => void): this; + removeListener(event: "close" | "listening", cb: () => void): this; + removeListener(event: "wsClientError", cb: (error: Error, socket: Duplex, request: InstanceType) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; +} +export { type Server }; + +export const WebSocketServer: typeof Server; +export interface WebSocketServer extends Server {} // eslint-disable-line @typescript-eslint/no-empty-interface + +// WebSocket stream +export function createWebSocketStream(websocket: WebSocket, options?: DuplexOptions): Duplex; + +export default WebSocket; +export { WebSocket }; diff --git a/node_modules/@types/ws/index.d.ts b/node_modules/@types/ws/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d08adc155873e948d2ffebf40622fe405159bc0 --- /dev/null +++ b/node_modules/@types/ws/index.d.ts @@ -0,0 +1,445 @@ +/// + +import { EventEmitter } from "events"; +import { + Agent, + ClientRequest, + ClientRequestArgs, + IncomingMessage, + OutgoingHttpHeaders, + Server as HTTPServer, +} from "http"; +import { Server as HTTPSServer } from "https"; +import { createConnection } from "net"; +import { Duplex, DuplexOptions } from "stream"; +import { SecureContextOptions } from "tls"; +import { URL } from "url"; +import { ZlibOptions } from "zlib"; + +// can not get all overload of BufferConstructor['from'], need to copy all it's first arguments here +// https://github.com/microsoft/TypeScript/issues/32164 +type BufferLike = + | string + | Buffer + | DataView + | number + | ArrayBufferView + | Uint8Array + | ArrayBuffer + | SharedArrayBuffer + | Blob + | readonly any[] + | readonly number[] + | { valueOf(): ArrayBuffer } + | { valueOf(): SharedArrayBuffer } + | { valueOf(): Uint8Array } + | { valueOf(): readonly number[] } + | { valueOf(): string } + | { [Symbol.toPrimitive](hint: string): string }; + +// WebSocket socket. +declare class WebSocket extends EventEmitter { + /** The connection is not yet open. */ + static readonly CONNECTING: 0; + /** The connection is open and ready to communicate. */ + static readonly OPEN: 1; + /** The connection is in the process of closing. */ + static readonly CLOSING: 2; + /** The connection is closed. */ + static readonly CLOSED: 3; + + binaryType: "nodebuffer" | "arraybuffer" | "fragments"; + readonly bufferedAmount: number; + readonly extensions: string; + /** Indicates whether the websocket is paused */ + readonly isPaused: boolean; + readonly protocol: string; + /** The current state of the connection */ + readonly readyState: + | typeof WebSocket.CONNECTING + | typeof WebSocket.OPEN + | typeof WebSocket.CLOSING + | typeof WebSocket.CLOSED; + readonly url: string; + + /** The connection is not yet open. */ + readonly CONNECTING: 0; + /** The connection is open and ready to communicate. */ + readonly OPEN: 1; + /** The connection is in the process of closing. */ + readonly CLOSING: 2; + /** The connection is closed. */ + readonly CLOSED: 3; + + onopen: ((event: WebSocket.Event) => void) | null; + onerror: ((event: WebSocket.ErrorEvent) => void) | null; + onclose: ((event: WebSocket.CloseEvent) => void) | null; + onmessage: ((event: WebSocket.MessageEvent) => void) | null; + + constructor(address: null); + constructor(address: string | URL, options?: WebSocket.ClientOptions | ClientRequestArgs); + constructor( + address: string | URL, + protocols?: string | string[], + options?: WebSocket.ClientOptions | ClientRequestArgs, + ); + + close(code?: number, data?: string | Buffer): void; + ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void; + pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void; + // https://github.com/websockets/ws/issues/2076#issuecomment-1250354722 + send(data: BufferLike, cb?: (err?: Error) => void): void; + send( + data: BufferLike, + options: { + mask?: boolean | undefined; + binary?: boolean | undefined; + compress?: boolean | undefined; + fin?: boolean | undefined; + }, + cb?: (err?: Error) => void, + ): void; + terminate(): void; + + /** + * Pause the websocket causing it to stop emitting events. Some events can still be + * emitted after this is called, until all buffered data is consumed. This method + * is a noop if the ready state is `CONNECTING` or `CLOSED`. + */ + pause(): void; + /** + * Make a paused socket resume emitting events. This method is a noop if the ready + * state is `CONNECTING` or `CLOSED`. + */ + resume(): void; + + // HTML5 WebSocket events + addEventListener( + type: K, + listener: + | ((event: WebSocket.WebSocketEventMap[K]) => void) + | { handleEvent(event: WebSocket.WebSocketEventMap[K]): void }, + options?: WebSocket.EventListenerOptions, + ): void; + removeEventListener( + type: K, + listener: + | ((event: WebSocket.WebSocketEventMap[K]) => void) + | { handleEvent(event: WebSocket.WebSocketEventMap[K]): void }, + ): void; + + // Events + on(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this; + on(event: "error", listener: (this: WebSocket, error: Error) => void): this; + on(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this; + on(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this; + on(event: "open", listener: (this: WebSocket) => void): this; + on(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this; + on(event: "redirect", listener: (this: WebSocket, url: string, request: ClientRequest) => void): this; + on( + event: "unexpected-response", + listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void, + ): this; + on(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this; + + once(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this; + once(event: "error", listener: (this: WebSocket, error: Error) => void): this; + once(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this; + once(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this; + once(event: "open", listener: (this: WebSocket) => void): this; + once(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this; + once(event: "redirect", listener: (this: WebSocket, url: string, request: ClientRequest) => void): this; + once( + event: "unexpected-response", + listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void, + ): this; + once(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this; + + off(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this; + off(event: "error", listener: (this: WebSocket, error: Error) => void): this; + off(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this; + off(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this; + off(event: "open", listener: (this: WebSocket) => void): this; + off(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this; + off(event: "redirect", listener: (this: WebSocket, url: string, request: ClientRequest) => void): this; + off( + event: "unexpected-response", + listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void, + ): this; + off(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this; + + addListener(event: "close", listener: (code: number, reason: Buffer) => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "upgrade", listener: (request: IncomingMessage) => void): this; + addListener(event: "message", listener: (data: WebSocket.RawData, isBinary: boolean) => void): this; + addListener(event: "open", listener: () => void): this; + addListener(event: "ping" | "pong", listener: (data: Buffer) => void): this; + addListener(event: "redirect", listener: (url: string, request: ClientRequest) => void): this; + addListener( + event: "unexpected-response", + listener: (request: ClientRequest, response: IncomingMessage) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: (code: number, reason: Buffer) => void): this; + removeListener(event: "error", listener: (error: Error) => void): this; + removeListener(event: "upgrade", listener: (request: IncomingMessage) => void): this; + removeListener(event: "message", listener: (data: WebSocket.RawData, isBinary: boolean) => void): this; + removeListener(event: "open", listener: () => void): this; + removeListener(event: "ping" | "pong", listener: (data: Buffer) => void): this; + removeListener(event: "redirect", listener: (url: string, request: ClientRequest) => void): this; + removeListener( + event: "unexpected-response", + listener: (request: ClientRequest, response: IncomingMessage) => void, + ): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; +} + +declare const WebSocketAlias: typeof WebSocket; +interface WebSocketAlias extends WebSocket {} // eslint-disable-line @typescript-eslint/no-empty-interface + +declare namespace WebSocket { + /** + * Data represents the raw message payload received over the WebSocket. + */ + type RawData = Buffer | ArrayBuffer | Buffer[]; + + /** + * Data represents the message payload received over the WebSocket. + */ + type Data = string | Buffer | ArrayBuffer | Buffer[]; + + /** + * CertMeta represents the accepted types for certificate & key data. + */ + type CertMeta = string | string[] | Buffer | Buffer[]; + + /** + * VerifyClientCallbackSync is a synchronous callback used to inspect the + * incoming message. The return value (boolean) of the function determines + * whether or not to accept the handshake. + */ + type VerifyClientCallbackSync = (info: { + origin: string; + secure: boolean; + req: Request; + }) => boolean; + + /** + * VerifyClientCallbackAsync is an asynchronous callback used to inspect the + * incoming message. The return value (boolean) of the function determines + * whether or not to accept the handshake. + */ + type VerifyClientCallbackAsync = ( + info: { origin: string; secure: boolean; req: Request }, + callback: (res: boolean, code?: number, message?: string, headers?: OutgoingHttpHeaders) => void, + ) => void; + + /** + * FinishRequestCallback is a callback for last minute customization of the + * headers. If finishRequest is set, then it has the responsibility to call + * request.end() once it is done setting request headers. + */ + type FinishRequestCallback = (request: ClientRequest, websocket: WebSocket) => void; + + interface ClientOptions extends SecureContextOptions { + protocol?: string | undefined; + followRedirects?: boolean | undefined; + generateMask?(mask: Buffer): void; + handshakeTimeout?: number | undefined; + maxRedirects?: number | undefined; + perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined; + localAddress?: string | undefined; + protocolVersion?: number | undefined; + headers?: { [key: string]: string } | undefined; + origin?: string | undefined; + agent?: Agent | undefined; + host?: string | undefined; + family?: number | undefined; + checkServerIdentity?(servername: string, cert: CertMeta): boolean; + rejectUnauthorized?: boolean | undefined; + allowSynchronousEvents?: boolean | undefined; + autoPong?: boolean | undefined; + maxPayload?: number | undefined; + skipUTF8Validation?: boolean | undefined; + createConnection?: typeof createConnection | undefined; + finishRequest?: FinishRequestCallback | undefined; + } + + interface PerMessageDeflateOptions { + serverNoContextTakeover?: boolean | undefined; + clientNoContextTakeover?: boolean | undefined; + serverMaxWindowBits?: number | undefined; + clientMaxWindowBits?: number | undefined; + zlibDeflateOptions?: { + flush?: number | undefined; + finishFlush?: number | undefined; + chunkSize?: number | undefined; + windowBits?: number | undefined; + level?: number | undefined; + memLevel?: number | undefined; + strategy?: number | undefined; + dictionary?: Buffer | Buffer[] | DataView | undefined; + info?: boolean | undefined; + } | undefined; + zlibInflateOptions?: ZlibOptions | undefined; + threshold?: number | undefined; + concurrencyLimit?: number | undefined; + } + + interface Event { + type: string; + target: WebSocket; + } + + interface ErrorEvent { + error: any; + message: string; + type: string; + target: WebSocket; + } + + interface CloseEvent { + wasClean: boolean; + code: number; + reason: string; + type: string; + target: WebSocket; + } + + interface MessageEvent { + data: Data; + type: string; + target: WebSocket; + } + + interface WebSocketEventMap { + open: Event; + error: ErrorEvent; + close: CloseEvent; + message: MessageEvent; + } + + interface EventListenerOptions { + once?: boolean | undefined; + } + + interface ServerOptions< + U extends typeof WebSocket.WebSocket = typeof WebSocket.WebSocket, + V extends typeof IncomingMessage = typeof IncomingMessage, + > { + host?: string | undefined; + port?: number | undefined; + backlog?: number | undefined; + server?: HTTPServer | HTTPSServer | undefined; + verifyClient?: + | VerifyClientCallbackAsync> + | VerifyClientCallbackSync> + | undefined; + handleProtocols?: (protocols: Set, request: InstanceType) => string | false; + path?: string | undefined; + noServer?: boolean | undefined; + allowSynchronousEvents?: boolean | undefined; + autoPong?: boolean | undefined; + clientTracking?: boolean | undefined; + perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined; + maxPayload?: number | undefined; + skipUTF8Validation?: boolean | undefined; + WebSocket?: U | undefined; + } + + interface AddressInfo { + address: string; + family: string; + port: number; + } + + // WebSocket Server + class Server< + T extends typeof WebSocket.WebSocket = typeof WebSocket.WebSocket, + U extends typeof IncomingMessage = typeof IncomingMessage, + > extends EventEmitter { + options: ServerOptions; + path: string; + clients: Set>; + + constructor(options?: ServerOptions, callback?: () => void); + + address(): AddressInfo | string | null; + close(cb?: (err?: Error) => void): void; + handleUpgrade( + request: InstanceType, + socket: Duplex, + upgradeHead: Buffer, + callback: (client: InstanceType, request: InstanceType) => void, + ): void; + shouldHandle(request: InstanceType): boolean | Promise; + + // Events + on( + event: "connection", + cb: (this: Server, websocket: InstanceType, request: InstanceType) => void, + ): this; + on(event: "error", cb: (this: Server, error: Error) => void): this; + on(event: "headers", cb: (this: Server, headers: string[], request: InstanceType) => void): this; + on(event: "close" | "listening", cb: (this: Server) => void): this; + on( + event: "wsClientError", + cb: (this: Server, error: Error, socket: Duplex, request: InstanceType) => void, + ): this; + on(event: string | symbol, listener: (this: Server, ...args: any[]) => void): this; + + once( + event: "connection", + cb: (this: Server, websocket: InstanceType, request: InstanceType) => void, + ): this; + once(event: "error", cb: (this: Server, error: Error) => void): this; + once(event: "headers", cb: (this: Server, headers: string[], request: InstanceType) => void): this; + once(event: "close" | "listening", cb: (this: Server) => void): this; + once( + event: "wsClientError", + cb: (this: Server, error: Error, socket: Duplex, request: InstanceType) => void, + ): this; + once(event: string | symbol, listener: (this: Server, ...args: any[]) => void): this; + + off( + event: "connection", + cb: (this: Server, socket: InstanceType, request: InstanceType) => void, + ): this; + off(event: "error", cb: (this: Server, error: Error) => void): this; + off(event: "headers", cb: (this: Server, headers: string[], request: InstanceType) => void): this; + off(event: "close" | "listening", cb: (this: Server) => void): this; + off( + event: "wsClientError", + cb: (this: Server, error: Error, socket: Duplex, request: InstanceType) => void, + ): this; + off(event: string | symbol, listener: (this: Server, ...args: any[]) => void): this; + + addListener(event: "connection", cb: (websocket: InstanceType, request: InstanceType) => void): this; + addListener(event: "error", cb: (error: Error) => void): this; + addListener(event: "headers", cb: (headers: string[], request: InstanceType) => void): this; + addListener(event: "close" | "listening", cb: () => void): this; + addListener(event: "wsClientError", cb: (error: Error, socket: Duplex, request: InstanceType) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "connection", cb: (websocket: InstanceType, request: InstanceType) => void): this; + removeListener(event: "error", cb: (error: Error) => void): this; + removeListener(event: "headers", cb: (headers: string[], request: InstanceType) => void): this; + removeListener(event: "close" | "listening", cb: () => void): this; + removeListener( + event: "wsClientError", + cb: (error: Error, socket: Duplex, request: InstanceType) => void, + ): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + const WebSocketServer: typeof Server; + interface WebSocketServer extends Server {} // eslint-disable-line @typescript-eslint/no-empty-interface + const WebSocket: typeof WebSocketAlias; + interface WebSocket extends WebSocketAlias {} // eslint-disable-line @typescript-eslint/no-empty-interface + + // WebSocket stream + function createWebSocketStream(websocket: WebSocket, options?: DuplexOptions): Duplex; +} + +export = WebSocket; diff --git a/node_modules/@types/ws/package.json b/node_modules/@types/ws/package.json new file mode 100644 index 0000000000000000000000000000000000000000..030a47f399f57a9c47278f1c75493e1820437d6f --- /dev/null +++ b/node_modules/@types/ws/package.json @@ -0,0 +1,72 @@ +{ + "name": "@types/ws", + "version": "8.18.1", + "description": "TypeScript definitions for ws", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/ws", + "license": "MIT", + "contributors": [ + { + "name": "Paul Loyd", + "githubUsername": "loyd", + "url": "https://github.com/loyd" + }, + { + "name": "Margus Lamp", + "githubUsername": "mlamp", + "url": "https://github.com/mlamp" + }, + { + "name": "Philippe D'Alva", + "githubUsername": "TitaneBoy", + "url": "https://github.com/TitaneBoy" + }, + { + "name": "reduckted", + "githubUsername": "reduckted", + "url": "https://github.com/reduckted" + }, + { + "name": "teidesu", + "githubUsername": "teidesu", + "url": "https://github.com/teidesu" + }, + { + "name": "Bartosz Wojtkowiak", + "githubUsername": "wojtkowiak", + "url": "https://github.com/wojtkowiak" + }, + { + "name": "Kyle Hensel", + "githubUsername": "k-yle", + "url": "https://github.com/k-yle" + }, + { + "name": "Samuel Skeen", + "githubUsername": "cwadrupldijjit", + "url": "https://github.com/cwadrupldijjit" + } + ], + "main": "", + "types": "index.d.ts", + "exports": { + ".": { + "types": { + "import": "./index.d.mts", + "default": "./index.d.ts" + } + }, + "./package.json": "./package.json" + }, + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/ws" + }, + "scripts": {}, + "dependencies": { + "@types/node": "*" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "043c83a4bb92503ab01243879ee715fb6db391090d10883c5a2eb72099d22724", + "typeScriptVersion": "5.1" +} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/LICENSE b/node_modules/@typescript-eslint/eslint-plugin/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a1164108d4d6037cb976384c16e5493917d87157 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/eslint-plugin/README.md b/node_modules/@typescript-eslint/eslint-plugin/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3f894c883444b85166f4b0dd627b241aa8301160 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/README.md @@ -0,0 +1,12 @@ +# `@typescript-eslint/eslint-plugin` + +An ESLint plugin which provides lint rules for TypeScript codebases. + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/eslint-plugin.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/eslint-plugin) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/eslint-plugin.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/eslint-plugin) + +👉 See **https://typescript-eslint.io/getting-started** for our Getting Started docs. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/node_modules/@typescript-eslint/eslint-plugin/index.d.ts b/node_modules/@typescript-eslint/eslint-plugin/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..756a025eb97d7d2819e3688bb16f5118432f7921 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/index.d.ts @@ -0,0 +1,13 @@ +import type { + ClassicConfig, + FlatConfig, +} from '@typescript-eslint/utils/ts-eslint'; + +import type rules from './rules'; + +declare const cjsExport: { + configs: Record; + meta: FlatConfig.PluginMeta; + rules: typeof rules; +}; +export = cjsExport; diff --git a/node_modules/@typescript-eslint/eslint-plugin/package.json b/node_modules/@typescript-eslint/eslint-plugin/package.json new file mode 100644 index 0000000000000000000000000000000000000000..075b530c7e099419ab73d0199708b84e25b94f95 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/package.json @@ -0,0 +1,126 @@ +{ + "name": "@typescript-eslint/eslint-plugin", + "version": "8.61.1", + "description": "TypeScript plugin for ESLint", + "files": [ + "dist", + "!**/*.tsbuildinfo", + "index.d.ts", + "raw-plugin.d.ts", + "rules.d.ts", + "package.json", + "./README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json", + "./use-at-your-own-risk/rules": { + "types": "./rules.d.ts", + "default": "./dist/rules/index.js" + }, + "./use-at-your-own-risk/raw-plugin": { + "types": "./raw-plugin.d.ts", + "default": "./dist/raw-plugin.js" + } + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/eslint-plugin" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io/packages/eslint-plugin", + "license": "MIT", + "keywords": [ + "eslint", + "eslintplugin", + "eslint-plugin", + "typescript" + ], + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.5.0", + "@typescript-eslint/scope-manager": "8.61.1", + "@typescript-eslint/type-utils": "8.61.1", + "@typescript-eslint/utils": "8.61.1", + "@typescript-eslint/visitor-keys": "8.61.1" + }, + "devDependencies": { + "@types/json-schema": "^7.0.15", + "@types/mdast": "^4.0.4", + "@types/natural-compare": "^1.4.3", + "@types/react": "^18.3.21", + "@typescript/native-preview": "7.0.0-dev.20260518.1", + "@vitest/coverage-v8": "^4.0.18", + "ajv": "^6.12.6", + "eslint": "^10.0.0", + "json-schema": "^0.4.0", + "markdown-table": "^3.0.4", + "marked": "^15.0.12", + "mdast-util-from-markdown": "^2.0.2", + "mdast-util-mdx": "^3.0.0", + "micromark-extension-mdxjs": "^3.0.0", + "prettier": "3.8.0", + "rimraf": "^5.0.10", + "title-case": "^4.3.2", + "tsx": "^4.7.2", + "typescript": ">=4.8.4 <6.1.0", + "unist-util-visit": "^5.0.0", + "vitest": "^4.0.18", + "@typescript-eslint/rule-tester": "8.61.1", + "@typescript-eslint/rule-schema-to-typescript-types": "8.61.1" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0", + "@typescript-eslint/parser": "^8.61.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "nx": { + "name": "eslint-plugin", + "includedScripts": [ + "clean" + ], + "targets": { + "generate-breaking-changes": { + "command": "tsx tools/generate-breaking-changes.mts", + "options": { + "cwd": "{projectRoot}" + }, + "dependsOn": [ + "type-utils:build" + ] + }, + "lint": { + "command": "eslint" + }, + "typecheck:tsgo": {} + } + }, + "scripts": { + "build": "pnpm -w exec nx build", + "clean": "rimraf dist/ coverage/", + "format": "pnpm -w run format", + "generate-breaking-changes": "tsx tools/generate-breaking-changes.mts", + "generate-configs": "pnpm -w run generate-configs", + "lint": "pnpm -w exec nx lint", + "test": "pnpm -w exec nx test", + "typecheck": "pnpm -w exec nx typecheck", + "typecheck:tsgo": "pnpm -w exec nx typecheck:tsgo" + } +} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/eslint-plugin/raw-plugin.d.ts b/node_modules/@typescript-eslint/eslint-plugin/raw-plugin.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..25a093aba9023301f6597aef604abce93c085400 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/raw-plugin.d.ts @@ -0,0 +1,25 @@ +import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint'; + +import type plugin from './index'; + +declare const cjsExport: { + flatConfigs: { + 'flat/all': FlatConfig.ConfigArray; + 'flat/base': FlatConfig.Config; + 'flat/disable-type-checked': FlatConfig.Config; + 'flat/eslint-recommended': FlatConfig.Config; + 'flat/recommended': FlatConfig.ConfigArray; + 'flat/recommended-type-checked': FlatConfig.ConfigArray; + 'flat/recommended-type-checked-only': FlatConfig.ConfigArray; + 'flat/strict': FlatConfig.ConfigArray; + 'flat/strict-type-checked': FlatConfig.ConfigArray; + 'flat/strict-type-checked-only': FlatConfig.ConfigArray; + 'flat/stylistic': FlatConfig.ConfigArray; + 'flat/stylistic-type-checked': FlatConfig.ConfigArray; + 'flat/stylistic-type-checked-only': FlatConfig.ConfigArray; + }; + parser: FlatConfig.Parser; + plugin: typeof plugin; +}; + +export = cjsExport; diff --git a/node_modules/@typescript-eslint/eslint-plugin/rules.d.ts b/node_modules/@typescript-eslint/eslint-plugin/rules.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..db19c5d6959145481eba9866db6d665c624bb0e1 --- /dev/null +++ b/node_modules/@typescript-eslint/eslint-plugin/rules.d.ts @@ -0,0 +1,87 @@ +/* +We purposely don't generate types for our plugin because TL;DR: +1) there's no real reason that anyone should do a typed import of our rules, +2) it would require us to change our code so there aren't as many inferred types + +This type declaration exists as a hacky way to add a type to the export for our +internal packages that require it. + +*** Long reason *** + +When you turn on declaration files, TS requires all types to be "fully resolvable" +without changes to the code. +All of our lint rules `export default createRule(...)`, which means they all +implicitly reference the `TSESLint.Rule` type for the export. + +TS wants to transpile each rule file to this `.d.ts` file: + +```ts +import type { TSESLint } from '@typescript-eslint/utils'; +declare const _default: TSESLint.RuleModule; +export default _default; +``` + +Because we don't import `TSESLint` in most files, it means that TS would have to +insert a new import during the declaration emit to make this work. +However TS wants to avoid adding new imports to the file because a new module +could have type side-effects (like global augmentation) which could cause weird +type side-effects in the decl file that wouldn't exist in source TS file. + +So TS errors on most of our rules with the following error: +``` +The inferred type of 'default' cannot be named without a reference to +'../../../../node_modules/@typescript-eslint/utils/src/ts-eslint/Rule'. +This is likely not portable. A type annotation is necessary. ts(2742) +``` +*/ +/* eslint-disable no-restricted-syntax */ + +import type { + RuleModuleWithMetaDocs, + RuleRecommendation, + RuleRecommendationAcrossConfigs, +} from '@typescript-eslint/utils/ts-eslint'; + +interface ESLintPluginDocs { + /** + * Does the rule extend (or is it based off of) an ESLint code rule? + * Alternately accepts the name of the base rule, in case the rule has been renamed. + * This is only used for documentation purposes. + */ + extendsBaseRule?: boolean | string; + + /** + * If a string config name, which starting config this rule is enabled in. + * If an object, which settings it has enabled in each of those configs. + */ + recommended?: RuleRecommendation | RuleRecommendationAcrossConfigs; + + /** + * Does the rule require us to create a full TypeScript Program in order for it + * to type-check code. This is only used for documentation purposes. + */ + requiresTypeChecking?: boolean; +} + +type ESLintPluginRuleModule = RuleModuleWithMetaDocs< + string, + readonly unknown[], + ESLintPluginDocs +>; + +type TypeScriptESLintRules = Record< + string, + RuleModuleWithMetaDocs +>; + +declare const rules: TypeScriptESLintRules; + +declare namespace rules { + export type { + ESLintPluginDocs, + ESLintPluginRuleModule, + TypeScriptESLintRules, + }; +} + +export = rules; diff --git a/node_modules/@typescript-eslint/parser/LICENSE b/node_modules/@typescript-eslint/parser/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a1164108d4d6037cb976384c16e5493917d87157 --- /dev/null +++ b/node_modules/@typescript-eslint/parser/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/parser/README.md b/node_modules/@typescript-eslint/parser/README.md new file mode 100644 index 0000000000000000000000000000000000000000..56ee655a56b09c65599bfc06b5d711a65a3c2858 --- /dev/null +++ b/node_modules/@typescript-eslint/parser/README.md @@ -0,0 +1,12 @@ +# `@typescript-eslint/parser` + +> An ESLint parser which leverages TypeScript ESTree to allow for ESLint to lint TypeScript source code. + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/parser.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/parser) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/parser.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/parser) + +👉 See **https://typescript-eslint.io/packages/parser** for documentation on this package. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/node_modules/@typescript-eslint/parser/package.json b/node_modules/@typescript-eslint/parser/package.json new file mode 100644 index 0000000000000000000000000000000000000000..34beb91ffeb7740f6376545939cc3584b2ea5867 --- /dev/null +++ b/node_modules/@typescript-eslint/parser/package.json @@ -0,0 +1,86 @@ +{ + "name": "@typescript-eslint/parser", + "version": "8.61.1", + "description": "An ESLint custom parser which leverages TypeScript ESTree", + "files": [ + "dist", + "!**/*.tsbuildinfo", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/parser" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io/packages/parser", + "license": "MIT", + "keywords": [ + "ast", + "ecmascript", + "javascript", + "typescript", + "parser", + "syntax", + "eslint" + ], + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + }, + "dependencies": { + "debug": "^4.4.3", + "@typescript-eslint/scope-manager": "8.61.1", + "@typescript-eslint/types": "8.61.1", + "@typescript-eslint/typescript-estree": "8.61.1", + "@typescript-eslint/visitor-keys": "8.61.1" + }, + "devDependencies": { + "@typescript/native-preview": "7.0.0-dev.20260518.1", + "@vitest/coverage-v8": "^4.0.18", + "eslint": "^10.0.0", + "glob": "^11.1.0", + "rimraf": "^5.0.10", + "typescript": ">=4.8.4 <6.1.0", + "vitest": "^4.0.18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "nx": { + "name": "parser", + "includedScripts": [ + "clean" + ], + "targets": { + "lint": { + "command": "eslint" + }, + "typecheck:tsgo": {} + } + }, + "scripts": { + "build": "pnpm exec nx build", + "clean": "rimraf dist/ coverage/", + "format": "pnpm -w run format", + "lint": "pnpm -w exec nx lint", + "test": "pnpm -w exec nx test", + "typecheck": "pnpm -w exec nx typecheck", + "typecheck:tsgo": "pnpm -w exec nx typecheck:tsgo" + } +} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/project-service/LICENSE b/node_modules/@typescript-eslint/project-service/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..310a18f8a6cbbe878d7c2874d6e3323827709b99 --- /dev/null +++ b/node_modules/@typescript-eslint/project-service/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/project-service/README.md b/node_modules/@typescript-eslint/project-service/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cf1a671681d63076a2ffc04b25ab3f8a86cd7f07 --- /dev/null +++ b/node_modules/@typescript-eslint/project-service/README.md @@ -0,0 +1,12 @@ +# `@typescript-eslint/project-service` + +> Standalone TypeScript project service wrapper for linting. + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/project-service.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/project-service) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/project-service.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/project-service) + +A standalone export of the "Project Service" that powers typed linting for typescript-eslint. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/node_modules/@typescript-eslint/project-service/package.json b/node_modules/@typescript-eslint/project-service/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d4513167e0e21e5f15f63521e4dcaa8d97834b70 --- /dev/null +++ b/node_modules/@typescript-eslint/project-service/package.json @@ -0,0 +1,83 @@ +{ + "name": "@typescript-eslint/project-service", + "version": "8.61.1", + "description": "Standalone TypeScript project service wrapper for linting.", + "files": [ + "dist", + "!**/*.tsbuildinfo", + "package.json", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "types": "./dist/index.d.ts", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/project-service" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io", + "license": "MIT", + "keywords": [ + "eslint", + "typescript", + "estree" + ], + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + }, + "dependencies": { + "debug": "^4.4.3", + "@typescript-eslint/tsconfig-utils": "^8.61.1", + "@typescript-eslint/types": "^8.61.1" + }, + "devDependencies": { + "@typescript/native-preview": "7.0.0-dev.20260518.1", + "@vitest/coverage-v8": "^4.0.18", + "rimraf": "^5.0.10", + "typescript": ">=4.8.4 <6.1.0", + "vitest": "^4.0.18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "publishConfig": { + "access": "public" + }, + "nx": { + "name": "project-service", + "includedScripts": [ + "clean" + ], + "targets": { + "lint": { + "command": "eslint" + }, + "typecheck:tsgo": {} + } + }, + "scripts": { + "//": "These package scripts are mostly here for convenience. Task running is handled by Nx at the root level.", + "build": "pnpm exec nx build", + "clean": "rimraf dist/ coverage/", + "format": "pnpm -w run format", + "lint": "pnpm -w exec nx lint", + "test": "pnpm -w exec nx test", + "typecheck": "pnpm -w exec nx typecheck", + "typecheck:tsgo": "pnpm -w exec nx typecheck:tsgo" + } +} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/scope-manager/LICENSE b/node_modules/@typescript-eslint/scope-manager/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a1164108d4d6037cb976384c16e5493917d87157 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/scope-manager/README.md b/node_modules/@typescript-eslint/scope-manager/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b730e9d83a99b3c3422018d0a3f2b4289aaeb5d8 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/README.md @@ -0,0 +1,10 @@ +# `@typescript-eslint/scope-manager` + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/scope-manager.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/scope-manager) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/scope-manager.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/scope-manager) + +👉 See **https://typescript-eslint.io/packages/scope-manager** for documentation on this package. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/node_modules/@typescript-eslint/scope-manager/package.json b/node_modules/@typescript-eslint/scope-manager/package.json new file mode 100644 index 0000000000000000000000000000000000000000..cea4ea8d3350f64bef03032921ca52e6350864b9 --- /dev/null +++ b/node_modules/@typescript-eslint/scope-manager/package.json @@ -0,0 +1,82 @@ +{ + "name": "@typescript-eslint/scope-manager", + "version": "8.61.1", + "description": "TypeScript scope analyser for ESLint", + "files": [ + "dist", + "!**/*.tsbuildinfo", + "package.json", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "types": "./dist/index.d.ts", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/scope-manager" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io/packages/scope-manager", + "license": "MIT", + "keywords": [ + "eslint", + "typescript", + "estree" + ], + "dependencies": { + "@typescript-eslint/types": "8.61.1", + "@typescript-eslint/visitor-keys": "8.61.1" + }, + "devDependencies": { + "@typescript/native-preview": "7.0.0-dev.20260518.1", + "@vitest/coverage-v8": "^4.0.18", + "@vitest/pretty-format": "^4.0.18", + "eslint": "^10.0.0", + "glob": "^11.1.0", + "rimraf": "^5.0.10", + "typescript": ">=4.8.4 <6.1.0", + "vitest": "^4.0.18", + "@typescript-eslint/typescript-estree": "8.61.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "nx": { + "name": "scope-manager", + "includedScripts": [ + "clean", + "clean-fixtures" + ], + "targets": { + "lint": { + "command": "eslint" + }, + "typecheck:tsgo": {} + } + }, + "scripts": { + "build": "pnpm exec nx build", + "clean": "rimraf dist/ coverage/", + "clean-fixtures": "rimraf -g \"./src/**/fixtures/**/snapshots\"", + "format": "pnpm -w run format", + "generate-lib": "pnpm -w exec nx generate-lib repo", + "lint": "pnpm -w exec nx lint", + "test": "pnpm -w exec nx test", + "typecheck": "pnpm -w exec nx typecheck", + "typecheck:tsgo": "pnpm -w exec nx typecheck:tsgo" + } +} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/tsconfig-utils/LICENSE b/node_modules/@typescript-eslint/tsconfig-utils/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..310a18f8a6cbbe878d7c2874d6e3323827709b99 --- /dev/null +++ b/node_modules/@typescript-eslint/tsconfig-utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/tsconfig-utils/README.md b/node_modules/@typescript-eslint/tsconfig-utils/README.md new file mode 100644 index 0000000000000000000000000000000000000000..075c3fbb7315c3d273368a14531e56af1697cea0 --- /dev/null +++ b/node_modules/@typescript-eslint/tsconfig-utils/README.md @@ -0,0 +1,12 @@ +# `@typescript-eslint/tsconfig-utils` + +> Utilities for collecting TSConfigs for linting scenarios. + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/tsconfig-utils.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/tsconfig-utils) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/tsconfig-utils.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/tsconfig-utils) + +The utilities in this package are separated from `@typescript-eslint/utils` so that they do not have a dependency on `eslint` or `@typescript-eslint/typescript-estree`. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/node_modules/@typescript-eslint/tsconfig-utils/package.json b/node_modules/@typescript-eslint/tsconfig-utils/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1dd234354fca8ed9fe491ccf84a88a14dec3714a --- /dev/null +++ b/node_modules/@typescript-eslint/tsconfig-utils/package.json @@ -0,0 +1,74 @@ +{ + "name": "@typescript-eslint/tsconfig-utils", + "version": "8.61.1", + "description": "Utilities for collecting TSConfigs for linting scenarios.", + "files": [ + "dist", + "!**/*.tsbuildinfo", + "package.json", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/tsconfig-utils" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io", + "license": "MIT", + "keywords": [ + "eslint", + "typescript", + "estree" + ], + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + }, + "devDependencies": { + "@typescript/native-preview": "7.0.0-dev.20260518.1", + "@vitest/coverage-v8": "^4.0.18", + "rimraf": "^5.0.10", + "typescript": ">=4.8.4 <6.1.0", + "vitest": "^4.0.18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "publishConfig": { + "access": "public" + }, + "nx": { + "name": "tsconfig-utils", + "includedScripts": [ + "clean" + ], + "targets": { + "typecheck:tsgo": {} + } + }, + "scripts": { + "//": "These package scripts are mostly here for convenience. Task running is handled by Nx at the root level.", + "build": "pnpm exec nx build", + "clean": "rimraf dist/ coverage/", + "format": "pnpm -w exec format", + "lint": "pnpm -w exec nx lint", + "test": "pnpm -w exec nx test", + "typecheck": "pnpm -w exec nx typecheck", + "typecheck:tsgo": "pnpm -w exec nx typecheck:tsgo" + } +} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/type-utils/LICENSE b/node_modules/@typescript-eslint/type-utils/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..dabd464af3a207c5f55cd5250caf63f05fc3b9fc --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/type-utils/README.md b/node_modules/@typescript-eslint/type-utils/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c5d32797dcf082fd71f00c2a76f8718564ee2afd --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/README.md @@ -0,0 +1,12 @@ +# `@typescript-eslint/type-utils` + +> Type utilities for working with TypeScript within ESLint rules. + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/utils.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/utils) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/utils.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/utils) + +The utilities in this package are separated from `@typescript-eslint/utils` so that that package does not require a dependency on `typescript`. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/node_modules/@typescript-eslint/type-utils/package.json b/node_modules/@typescript-eslint/type-utils/package.json new file mode 100644 index 0000000000000000000000000000000000000000..fac2fd6c3d41c5ce9aedaf4fd047742c4e68bda7 --- /dev/null +++ b/node_modules/@typescript-eslint/type-utils/package.json @@ -0,0 +1,85 @@ +{ + "name": "@typescript-eslint/type-utils", + "version": "8.61.1", + "description": "Type utilities for working with TypeScript + ESLint together", + "files": [ + "dist", + "!**/*.tsbuildinfo", + "package.json", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/type-utils" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io", + "license": "MIT", + "keywords": [ + "eslint", + "typescript", + "estree" + ], + "dependencies": { + "debug": "^4.4.3", + "ts-api-utils": "^2.5.0", + "@typescript-eslint/types": "8.61.1", + "@typescript-eslint/typescript-estree": "8.61.1", + "@typescript-eslint/utils": "8.61.1" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + }, + "devDependencies": { + "@types/babel__code-frame": "^7.0.6", + "@typescript/native-preview": "7.0.0-dev.20260518.1", + "@vitest/coverage-v8": "^4.0.18", + "ajv": "^6.12.6", + "eslint": "^10.0.0", + "rimraf": "^5.0.10", + "typescript": ">=4.8.4 <6.1.0", + "vitest": "^4.0.18", + "@typescript-eslint/parser": "8.61.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "nx": { + "name": "type-utils", + "includedScripts": [ + "clean" + ], + "targets": { + "lint": { + "command": "eslint" + }, + "typecheck:tsgo": {} + } + }, + "scripts": { + "build": "pnpm exec nx build", + "clean": "rimraf dist/ coverage/", + "format": "pnpm -w run format", + "lint": "pnpm -w exec nx lint", + "test": "pnpm -w exec nx test", + "typecheck": "pnpm -w exec nx typecheck", + "typecheck:tsgo": "pnpm -w exec nx typecheck:tsgo" + } +} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/types/LICENSE b/node_modules/@typescript-eslint/types/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a1164108d4d6037cb976384c16e5493917d87157 --- /dev/null +++ b/node_modules/@typescript-eslint/types/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/types/README.md b/node_modules/@typescript-eslint/types/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7a3008bb982abdf588b84c49a662f79e01957342 --- /dev/null +++ b/node_modules/@typescript-eslint/types/README.md @@ -0,0 +1,12 @@ +# `@typescript-eslint/types` + +> Types for the TypeScript-ESTree AST spec + +This package exists to help us reduce cycles and provide lighter-weight packages at runtime. + +## ✋ Internal Package + +This is an _internal package_ to the [typescript-eslint monorepo](https://github.com/typescript-eslint/typescript-eslint). +You likely don't want to use it directly. + +👉 See **https://typescript-eslint.io** for docs on typescript-eslint. diff --git a/node_modules/@typescript-eslint/types/package.json b/node_modules/@typescript-eslint/types/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c9b8f3fc1659463f67eda61693ed2fdf87dafd79 --- /dev/null +++ b/node_modules/@typescript-eslint/types/package.json @@ -0,0 +1,103 @@ +{ + "name": "@typescript-eslint/types", + "version": "8.61.1", + "description": "Types for the TypeScript-ESTree AST spec", + "files": [ + "dist", + "!**/*.tsbuildinfo", + "package.json", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "types": "./dist/index.d.ts", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/types" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io", + "license": "MIT", + "keywords": [ + "eslint", + "typescript", + "estree" + ], + "devDependencies": { + "@typescript/native-preview": "7.0.0-dev.20260518.1", + "@vitest/coverage-v8": "^4.0.18", + "eslint": "^10.0.0", + "rimraf": "^5.0.10", + "tsx": "^4.7.2", + "typescript": ">=4.8.4 <6.1.0", + "vitest": "^4.0.18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "nx": { + "name": "types", + "implicitDependencies": [ + "ast-spec" + ], + "includedScripts": [ + "clean" + ], + "targets": { + "build": { + "dependsOn": [ + "copy-ast-spec" + ], + "inputs": [ + "{projectRoot}/src/generated/**/*" + ] + }, + "copy-ast-spec": { + "cache": false, + "command": "tsx tools/copy-ast-spec.mts", + "dependsOn": [ + "ast-spec:build" + ], + "options": { + "cwd": "{projectRoot}" + }, + "outputs": [ + "{projectRoot}/src/generated" + ] + }, + "lint": { + "command": "eslint", + "dependsOn": [ + "typescript-eslint:build", + "eslint-plugin-internal:build" + ] + }, + "typecheck:tsgo": {} + } + }, + "scripts": { + "build": "pnpm exec nx build", + "clean": "rimraf dist/ src/generated/ coverage/", + "copy-ast-spec": "tsx ./tools/copy-ast-spec.mts", + "format": "pnpm -w run format", + "generate-lib": "pnpm -w exec nx run scope-manager:generate-lib", + "lint": "pnpm -w exec nx lint", + "test": "pnpm -w exec nx test", + "typecheck": "pnpm -w exec nx typecheck", + "typecheck:tsgo": "pnpm -w exec nx typecheck:tsgo" + } +} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/typescript-estree/LICENSE b/node_modules/@typescript-eslint/typescript-estree/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a1164108d4d6037cb976384c16e5493917d87157 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/typescript-estree/README.md b/node_modules/@typescript-eslint/typescript-estree/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c98838dad403029865246da7fd08274e983ee39b --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/README.md @@ -0,0 +1,14 @@ +# `@typescript-eslint/typescript-estree` + +> A parser that produces an ESTree-compatible AST for TypeScript code. + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/typescript-estree.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/utils) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/typescript-estree.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/utils) + +## Contributing + +👉 See **https://typescript-eslint.io/packages/typescript-estree** for documentation on this package. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/node_modules/@typescript-eslint/typescript-estree/package.json b/node_modules/@typescript-eslint/typescript-estree/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0597464f19dee25121536b1fb85831c28ea7e8f2 --- /dev/null +++ b/node_modules/@typescript-eslint/typescript-estree/package.json @@ -0,0 +1,95 @@ +{ + "name": "@typescript-eslint/typescript-estree", + "version": "8.61.1", + "description": "A parser that converts TypeScript source code into an ESTree compatible form", + "files": [ + "dist", + "!**/*.tsbuildinfo", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json", + "./use-at-your-own-risk": { + "types": "./dist/use-at-your-own-risk.d.ts", + "default": "./dist/use-at-your-own-risk.js" + } + }, + "types": "./dist/index.d.ts", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/typescript-estree" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io/packages/typescript-estree", + "license": "MIT", + "keywords": [ + "ast", + "estree", + "ecmascript", + "javascript", + "typescript", + "parser", + "syntax" + ], + "dependencies": { + "debug": "^4.4.3", + "minimatch": "^10.2.2", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.5.0", + "@typescript-eslint/tsconfig-utils": "8.61.1", + "@typescript-eslint/project-service": "8.61.1", + "@typescript-eslint/visitor-keys": "8.61.1", + "@typescript-eslint/types": "8.61.1" + }, + "devDependencies": { + "@typescript/native-preview": "7.0.0-dev.20260518.1", + "@vitest/coverage-v8": "^4.0.18", + "eslint": "^10.0.0", + "glob": "^11.1.0", + "rimraf": "^5.0.10", + "typescript": ">=4.8.4 <6.1.0", + "vitest": "^4.0.18", + "yaml": "^2.8.2" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "nx": { + "name": "typescript-estree", + "includedScripts": [ + "clean" + ], + "targets": { + "lint": { + "command": "eslint" + }, + "typecheck:tsgo": {} + } + }, + "scripts": { + "build": "pnpm exec nx build", + "clean": "rimraf dist/ coverage/", + "format": "pnpm -w run format", + "lint": "pnpm -w exec nx lint", + "test": "pnpm -w exec nx test", + "typecheck": "pnpm -w exec nx typecheck", + "typecheck:tsgo": "pnpm -w exec nx typecheck:tsgo" + } +} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/utils/LICENSE b/node_modules/@typescript-eslint/utils/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a1164108d4d6037cb976384c16e5493917d87157 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/utils/README.md b/node_modules/@typescript-eslint/utils/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7ba750090e9bce0db5eac316be4808f087b09582 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/README.md @@ -0,0 +1,12 @@ +# `@typescript-eslint/utils` + +> Utilities for working with TypeScript + ESLint together. + +[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/utils.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/utils) +[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/utils.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/utils) + +👉 See **https://typescript-eslint.io/packages/utils** for documentation on this package. + +> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code. + + diff --git a/node_modules/@typescript-eslint/utils/package.json b/node_modules/@typescript-eslint/utils/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c702a3ba85d79862f370c19c6e0fa3b7fd96a506 --- /dev/null +++ b/node_modules/@typescript-eslint/utils/package.json @@ -0,0 +1,115 @@ +{ + "name": "@typescript-eslint/utils", + "version": "8.61.1", + "description": "Utilities for working with TypeScript + ESLint together", + "files": [ + "dist", + "!**/*.tsbuildinfo", + "package.json", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./ast-utils": { + "types": "./dist/ast-utils/index.d.ts", + "default": "./dist/ast-utils/index.js" + }, + "./eslint-utils": { + "types": "./dist/eslint-utils/index.d.ts", + "default": "./dist/eslint-utils/index.js" + }, + "./json-schema": { + "types": "./dist/json-schema.d.ts", + "default": "./dist/json-schema.js" + }, + "./ts-eslint": { + "types": "./dist/ts-eslint/index.d.ts", + "default": "./dist/ts-eslint/index.js" + }, + "./package.json": "./package.json" + }, + "types": "./dist/index.d.ts", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/utils" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io/packages/utils", + "license": "MIT", + "keywords": [ + "eslint", + "typescript", + "estree" + ], + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/types": "8.61.1", + "@typescript-eslint/typescript-estree": "8.61.1", + "@typescript-eslint/scope-manager": "8.61.1" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + }, + "devDependencies": { + "@typescript/native-preview": "7.0.0-dev.20260518.1", + "@vitest/coverage-v8": "^4.0.18", + "eslint": "^10.0.0", + "rimraf": "^5.0.10", + "typescript": ">=4.8.4 <6.1.0", + "vitest": "^4.0.18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "nx": { + "name": "utils", + "includedScripts": [ + "clean" + ], + "targets": { + "lint": { + "command": "eslint" + }, + "typecheck": { + "outputs": [ + "{workspaceRoot}/dist", + "{projectRoot}/dist" + ] + }, + "typecheck:tsgo": { + "outputs": [ + "{workspaceRoot}/dist", + "{projectRoot}/dist" + ] + }, + "test": { + "dependsOn": [ + "^build", + "typecheck" + ] + } + } + }, + "scripts": { + "build": "pnpm exec nx build", + "clean": "rimraf dist/ coverage/", + "format": "pnpm -w run format", + "lint": "pnpm -w exec nx lint", + "test": "pnpm -w exec nx test", + "typecheck": "pnpm -w exec nx typecheck", + "typecheck:tsgo": "pnpm -w exec nx typecheck:tsgo" + } +} \ No newline at end of file diff --git a/node_modules/@typescript-eslint/visitor-keys/LICENSE b/node_modules/@typescript-eslint/visitor-keys/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a1164108d4d6037cb976384c16e5493917d87157 --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 typescript-eslint and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@typescript-eslint/visitor-keys/README.md b/node_modules/@typescript-eslint/visitor-keys/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1745172a6f20c5d2b170a561d50c4c46966796bd --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/README.md @@ -0,0 +1,10 @@ +# `@typescript-eslint/visitor-keys` + +> Visitor keys used to help traverse the TypeScript-ESTree AST. + +## ✋ Internal Package + +This is an _internal package_ to the [typescript-eslint monorepo](https://github.com/typescript-eslint/typescript-eslint). +You likely don't want to use it directly. + +👉 See **https://typescript-eslint.io** for docs on typescript-eslint. diff --git a/node_modules/@typescript-eslint/visitor-keys/package.json b/node_modules/@typescript-eslint/visitor-keys/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7ebc6668db3864f1267e29422022930d63c017cf --- /dev/null +++ b/node_modules/@typescript-eslint/visitor-keys/package.json @@ -0,0 +1,76 @@ +{ + "name": "@typescript-eslint/visitor-keys", + "version": "8.61.1", + "description": "Visitor keys used to help traverse the TypeScript-ESTree AST", + "files": [ + "dist", + "!**/*.tsbuildinfo", + "package.json", + "README.md", + "LICENSE" + ], + "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "types": "./dist/index.d.ts", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/typescript-eslint/typescript-eslint.git", + "directory": "packages/visitor-keys" + }, + "bugs": { + "url": "https://github.com/typescript-eslint/typescript-eslint/issues" + }, + "homepage": "https://typescript-eslint.io", + "license": "MIT", + "keywords": [ + "eslint", + "typescript", + "estree" + ], + "dependencies": { + "eslint-visitor-keys": "^5.0.0", + "@typescript-eslint/types": "8.61.1" + }, + "devDependencies": { + "@typescript/native-preview": "7.0.0-dev.20260518.1", + "@vitest/coverage-v8": "^4.0.18", + "eslint": "^10.0.0", + "rimraf": "^5.0.10", + "typescript": ">=4.8.4 <6.1.0", + "vitest": "^4.0.18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "nx": { + "name": "visitor-keys", + "includedScripts": [ + "clean" + ], + "targets": { + "lint": { + "command": "eslint" + }, + "typecheck:tsgo": {} + } + }, + "scripts": { + "build": "pnpm exec nx build", + "clean": "rimraf dist/ coverage/", + "format": "pnpm -w run format", + "lint": "pnpm -w exec nx lint", + "test": "pnpm -w exec nx test", + "typecheck": "pnpm -w exec nx typecheck", + "typecheck:tsgo": "pnpm -w exec nx typecheck:tsgo" + } +} \ No newline at end of file diff --git a/node_modules/@ungap/structured-clone/.github/workflows/node.js.yml b/node_modules/@ungap/structured-clone/.github/workflows/node.js.yml new file mode 100644 index 0000000000000000000000000000000000000000..73cf8d65218202c9eccdd6de6c29482fefae3e60 --- /dev/null +++ b/node_modules/@ungap/structured-clone/.github/workflows/node.js.yml @@ -0,0 +1,31 @@ +# This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node +# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions + +name: build + +on: [push, pull_request] + +jobs: + build: + + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [16] + + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v2 + with: + node-version: ${{ matrix.node-version }} + cache: 'npm' + - run: npm ci + - run: npm run build --if-present + - run: npm test + - run: npm run coverage --if-present + - name: Coveralls + uses: coverallsapp/github-action@master + with: + github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/node_modules/@ungap/structured-clone/LICENSE b/node_modules/@ungap/structured-clone/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..48afbe52afb5895b682e9b877bae10f96049a446 --- /dev/null +++ b/node_modules/@ungap/structured-clone/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2021, Andrea Giammarchi, @WebReflection + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@ungap/structured-clone/README.md b/node_modules/@ungap/structured-clone/README.md new file mode 100644 index 0000000000000000000000000000000000000000..07d15a25f4646bab1792f28012305823ed675570 --- /dev/null +++ b/node_modules/@ungap/structured-clone/README.md @@ -0,0 +1,95 @@ +# structuredClone polyfill + +[![Downloads](https://img.shields.io/npm/dm/@ungap/structured-clone.svg)](https://www.npmjs.com/package/@ungap/structured-clone) [![build status](https://github.com/ungap/structured-clone/actions/workflows/node.js.yml/badge.svg)](https://github.com/ungap/structured-clone/actions) [![Coverage Status](https://coveralls.io/repos/github/ungap/structured-clone/badge.svg?branch=main)](https://coveralls.io/github/ungap/structured-clone?branch=main) + +An env agnostic serializer and deserializer with recursion ability and types beyond *JSON* from the *HTML* standard itself. + + * [Supported Types](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm#supported_types) + * *not supported yet*: Blob, File, FileList, ImageBitmap, ImageData or others non *JS* types but typed arrays are supported without major issues, but u/int8, u/int16, and u/int32 are the only safely suppored (right now). + * *not possible to implement*: the `{transfer: []}` option can be passed but it's completely ignored. + * [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) + * [Serializer](https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal) + * [Deserializer](https://html.spec.whatwg.org/multipage/structured-data.html#structureddeserialize) + +Serialized values can be safely stringified as *JSON* too, and deserialization resurrect all values, even recursive, or more complex than what *JSON* allows. + + +### Examples + +Check the [100% test coverage](./test/index.js) to know even more. + +```js +// as default export +import structuredClone from '@ungap/structured-clone'; +const cloned = structuredClone({any: 'serializable'}); + +// as independent serializer/deserializer +import {serialize, deserialize} from '@ungap/structured-clone'; + +// the result can be stringified as JSON without issues +// even if there is recursive data, bigint values, +// typed arrays, and so on +const serialized = serialize({any: 'serializable'}); + +// the result will be a replica of the original object +const deserialized = deserialize(serialized); +``` + +#### Global Polyfill +Note: Only monkey patch the global if needed. This polyfill works just fine as an explicit import: `import structuredClone from "@ungap/structured-clone"` +```js +// Attach the polyfill as a Global function +import structuredClone from "@ungap/structured-clone"; +if (!("structuredClone" in globalThis)) { + globalThis.structuredClone = structuredClone; +} + +// Or don't monkey patch +import structuredClone from "@ungap/structured-clone" +// Just use it in the file +structuredClone() +``` + +**Note**: Do not attach this module's default export directly to the global scope, whithout a conditional guard to detect a native implementation. In environments where there is a native global implementation of `structuredClone()` already, assignment to the global object will result in an infinite loop when `globalThis.structuredClone()` is called. See the example above for a safe way to provide the polyfill globally in your project. + +### Extra Features + +There is no middle-ground between the structured clone algorithm and JSON: + + * JSON is more relaxed about incompatible values: it just ignores these + * Structured clone is inflexible regarding incompatible values, yet it makes specialized instances impossible to reconstruct, plus it doesn't offer any helper, such as `toJSON()`, to make serialization possible, or better, with specific cases + +This module specialized `serialize` export offers, within the optional extra argument, a **lossy** property to avoid throwing when incompatible types are found down the road (function, symbol, ...), so that it is possible to send with less worrying about thrown errors. + +```js +// as default export +import structuredClone from '@ungap/structured-clone'; +const cloned = structuredClone( + { + method() { + // ignored, won't be cloned + }, + special: Symbol('also ignored') + }, + { + // avoid throwing + lossy: true, + // avoid throwing *and* looks for toJSON + json: true + } +); +``` + +The behavior is the same found in *JSON* when it comes to *Array*, so that unsupported values will result as `null` placeholders instead. + +#### toJSON + +If `lossy` option is not enough, `json` will actually enforce `lossy` and also check for `toJSON` method when objects are parsed. + +Alternative, the `json` exports combines all features: + +```js +import {stringify, parse} from '@ungap/structured-clone/json'; + +parse(stringify({any: 'serializable'})); +``` diff --git a/node_modules/@ungap/structured-clone/cjs/deserialize.js b/node_modules/@ungap/structured-clone/cjs/deserialize.js new file mode 100644 index 0000000000000000000000000000000000000000..6ce37b076a7f09b731d0e7e440831cec2acbcd58 --- /dev/null +++ b/node_modules/@ungap/structured-clone/cjs/deserialize.js @@ -0,0 +1,97 @@ +'use strict'; +const { + VOID, PRIMITIVE, ARRAY, OBJECT, DATE, REGEXP, MAP, SET, ERROR, BIGINT +} = require('./types.js'); + +const env = typeof self === 'object' ? self : globalThis; + +const guard = (name, init) => { + switch (name) { + case 'Function': + case 'SharedWorker': + case 'Worker': + case 'eval': + case 'setInterval': + case 'setTimeout': + throw new TypeError('unable to deserialize ' + name); + } + return new env[name](init); +}; + +const deserializer = ($, _) => { + const as = (out, index) => { + $.set(index, out); + return out; + }; + + const unpair = index => { + if ($.has(index)) + return $.get(index); + + const [type, value] = _[index]; + switch (type) { + case PRIMITIVE: + case VOID: + return as(value, index); + case ARRAY: { + const arr = as([], index); + for (const index of value) + arr.push(unpair(index)); + return arr; + } + case OBJECT: { + const object = as({}, index); + for (const [key, index] of value) + object[unpair(key)] = unpair(index); + return object; + } + case DATE: + return as(new Date(value), index); + case REGEXP: { + const {source, flags} = value; + return as(new RegExp(source, flags), index); + } + case MAP: { + const map = as(new Map, index); + for (const [key, index] of value) + map.set(unpair(key), unpair(index)); + return map; + } + case SET: { + const set = as(new Set, index); + for (const index of value) + set.add(unpair(index)); + return set; + } + case ERROR: { + const {name, message} = value; + return as(guard(name, message), index); + } + case BIGINT: + return as(BigInt(value), index); + case 'BigInt': + return as(Object(BigInt(value)), index); + case 'ArrayBuffer': + return as(new Uint8Array(value).buffer, value); + case 'DataView': { + const { buffer } = new Uint8Array(value); + return as(new DataView(buffer), value); + } + } + return as(guard(type, value), index); + }; + + return unpair; +}; + +/** + * @typedef {Array} Record a type representation + */ + +/** + * Returns a deserialized value from a serialized array of Records. + * @param {Record[]} serialized a previously serialized value. + * @returns {any} + */ +const deserialize = serialized => deserializer(new Map, serialized)(0); +exports.deserialize = deserialize; diff --git a/node_modules/@ungap/structured-clone/cjs/index.js b/node_modules/@ungap/structured-clone/cjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..13d747c5937db606221cf597d3345dba76a26aec --- /dev/null +++ b/node_modules/@ungap/structured-clone/cjs/index.js @@ -0,0 +1,27 @@ +'use strict'; +const {deserialize} = require('./deserialize.js'); +const {serialize} = require('./serialize.js'); + +/** + * @typedef {Array} Record a type representation + */ + +/** + * Returns an array of serialized Records. + * @param {any} any a serializable value. + * @param {{transfer?: any[], json?: boolean, lossy?: boolean}?} options an object with + * a transfer option (ignored when polyfilled) and/or non standard fields that + * fallback to the polyfill if present. + * @returns {Record[]} + */ +Object.defineProperty(exports, '__esModule', {value: true}).default = typeof structuredClone === "function" ? + /* c8 ignore start */ + (any, options) => ( + options && ('json' in options || 'lossy' in options) ? + deserialize(serialize(any, options)) : structuredClone(any) + ) : + (any, options) => deserialize(serialize(any, options)); + /* c8 ignore stop */ + +exports.deserialize = deserialize; +exports.serialize = serialize; diff --git a/node_modules/@ungap/structured-clone/cjs/json.js b/node_modules/@ungap/structured-clone/cjs/json.js new file mode 100644 index 0000000000000000000000000000000000000000..0038dcf9ca530fe4506c0b3adec60f99d9d260c0 --- /dev/null +++ b/node_modules/@ungap/structured-clone/cjs/json.js @@ -0,0 +1,24 @@ +'use strict'; +/*! (c) Andrea Giammarchi - ISC */ + +const {deserialize} = require('./deserialize.js'); +const {serialize} = require('./serialize.js'); + +const {parse: $parse, stringify: $stringify} = JSON; +const options = {json: true, lossy: true}; + +/** + * Revive a previously stringified structured clone. + * @param {string} str previously stringified data as string. + * @returns {any} whatever was previously stringified as clone. + */ +const parse = str => deserialize($parse(str)); +exports.parse = parse; + +/** + * Represent a structured clone value as string. + * @param {any} any some clone-able value to stringify. + * @returns {string} the value stringified. + */ +const stringify = any => $stringify(serialize(any, options)); +exports.stringify = stringify; diff --git a/node_modules/@ungap/structured-clone/cjs/package.json b/node_modules/@ungap/structured-clone/cjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0292b9956f2e40d6eb3d0f3998e710d973113aaa --- /dev/null +++ b/node_modules/@ungap/structured-clone/cjs/package.json @@ -0,0 +1 @@ +{"type":"commonjs"} \ No newline at end of file diff --git a/node_modules/@ungap/structured-clone/cjs/serialize.js b/node_modules/@ungap/structured-clone/cjs/serialize.js new file mode 100644 index 0000000000000000000000000000000000000000..59b2d38371c6c656b9a8e7d7657922b1af359a62 --- /dev/null +++ b/node_modules/@ungap/structured-clone/cjs/serialize.js @@ -0,0 +1,170 @@ +'use strict'; +const { + VOID, PRIMITIVE, ARRAY, OBJECT, DATE, REGEXP, MAP, SET, ERROR, BIGINT +} = require('./types.js'); + +const EMPTY = ''; + +const {toString} = {}; +const {keys} = Object; + +const typeOf = value => { + const type = typeof value; + if (type !== 'object' || !value) + return [PRIMITIVE, type]; + + const asString = toString.call(value).slice(8, -1); + switch (asString) { + case 'Array': + return [ARRAY, EMPTY]; + case 'Object': + return [OBJECT, EMPTY]; + case 'Date': + return [DATE, EMPTY]; + case 'RegExp': + return [REGEXP, EMPTY]; + case 'Map': + return [MAP, EMPTY]; + case 'Set': + return [SET, EMPTY]; + case 'DataView': + return [ARRAY, asString]; + } + + if (asString.includes('Array')) + return [ARRAY, asString]; + + if (asString.includes('Error')) + return [ERROR, asString]; + + return [OBJECT, asString]; +}; + +const shouldSkip = ([TYPE, type]) => ( + TYPE === PRIMITIVE && + (type === 'function' || type === 'symbol') +); + +const serializer = (strict, json, $, _) => { + + const as = (out, value) => { + const index = _.push(out) - 1; + $.set(value, index); + return index; + }; + + const pair = value => { + if ($.has(value)) + return $.get(value); + + let [TYPE, type] = typeOf(value); + switch (TYPE) { + case PRIMITIVE: { + let entry = value; + switch (type) { + case 'bigint': + TYPE = BIGINT; + entry = value.toString(); + break; + case 'function': + case 'symbol': + if (strict) + throw new TypeError('unable to serialize ' + type); + entry = null; + break; + case 'undefined': + return as([VOID], value); + } + return as([TYPE, entry], value); + } + case ARRAY: { + if (type) { + let spread = value; + if (type === 'DataView') { + spread = new Uint8Array(value.buffer); + } + else if (type === 'ArrayBuffer') { + spread = new Uint8Array(value); + } + return as([type, [...spread]], value); + } + + const arr = []; + const index = as([TYPE, arr], value); + for (const entry of value) + arr.push(pair(entry)); + return index; + } + case OBJECT: { + if (type) { + switch (type) { + case 'BigInt': + return as([type, value.toString()], value); + case 'Boolean': + case 'Number': + case 'String': + return as([type, value.valueOf()], value); + } + } + + if (json && ('toJSON' in value)) + return pair(value.toJSON()); + + const entries = []; + const index = as([TYPE, entries], value); + for (const key of keys(value)) { + if (strict || !shouldSkip(typeOf(value[key]))) + entries.push([pair(key), pair(value[key])]); + } + return index; + } + case DATE: + return as([TYPE, value.toISOString()], value); + case REGEXP: { + const {source, flags} = value; + return as([TYPE, {source, flags}], value); + } + case MAP: { + const entries = []; + const index = as([TYPE, entries], value); + for (const [key, entry] of value) { + if (strict || !(shouldSkip(typeOf(key)) || shouldSkip(typeOf(entry)))) + entries.push([pair(key), pair(entry)]); + } + return index; + } + case SET: { + const entries = []; + const index = as([TYPE, entries], value); + for (const entry of value) { + if (strict || !shouldSkip(typeOf(entry))) + entries.push(pair(entry)); + } + return index; + } + } + + const {message} = value; + return as([TYPE, {name: type, message}], value); + }; + + return pair; +}; + +/** + * @typedef {Array} Record a type representation + */ + +/** + * Returns an array of serialized Records. + * @param {any} value a serializable value. + * @param {{json?: boolean, lossy?: boolean}?} options an object with a `lossy` or `json` property that, + * if `true`, will not throw errors on incompatible types, and behave more + * like JSON stringify would behave. Symbol and Function will be discarded. + * @returns {Record[]} + */ + const serialize = (value, {json, lossy} = {}) => { + const _ = []; + return serializer(!(json || lossy), !!json, new Map, _)(value), _; +}; +exports.serialize = serialize; diff --git a/node_modules/@ungap/structured-clone/cjs/types.js b/node_modules/@ungap/structured-clone/cjs/types.js new file mode 100644 index 0000000000000000000000000000000000000000..8284be3d69a407829b84aea17965338d0b8efde3 --- /dev/null +++ b/node_modules/@ungap/structured-clone/cjs/types.js @@ -0,0 +1,22 @@ +'use strict'; +const VOID = -1; +exports.VOID = VOID; +const PRIMITIVE = 0; +exports.PRIMITIVE = PRIMITIVE; +const ARRAY = 1; +exports.ARRAY = ARRAY; +const OBJECT = 2; +exports.OBJECT = OBJECT; +const DATE = 3; +exports.DATE = DATE; +const REGEXP = 4; +exports.REGEXP = REGEXP; +const MAP = 5; +exports.MAP = MAP; +const SET = 6; +exports.SET = SET; +const ERROR = 7; +exports.ERROR = ERROR; +const BIGINT = 8; +exports.BIGINT = BIGINT; +// export const SYMBOL = 9; diff --git a/node_modules/@ungap/structured-clone/esm/deserialize.js b/node_modules/@ungap/structured-clone/esm/deserialize.js new file mode 100644 index 0000000000000000000000000000000000000000..440fb30152f1226c7295f37ee0c97deef9ff4884 --- /dev/null +++ b/node_modules/@ungap/structured-clone/esm/deserialize.js @@ -0,0 +1,98 @@ +import { + VOID, PRIMITIVE, + ARRAY, OBJECT, + DATE, REGEXP, MAP, SET, + ERROR, BIGINT +} from './types.js'; + +const env = typeof self === 'object' ? self : globalThis; + +const guard = (name, init) => { + switch (name) { + case 'Function': + case 'SharedWorker': + case 'Worker': + case 'eval': + case 'setInterval': + case 'setTimeout': + throw new TypeError('unable to deserialize ' + name); + } + return new env[name](init); +}; + +const deserializer = ($, _) => { + const as = (out, index) => { + $.set(index, out); + return out; + }; + + const unpair = index => { + if ($.has(index)) + return $.get(index); + + const [type, value] = _[index]; + switch (type) { + case PRIMITIVE: + case VOID: + return as(value, index); + case ARRAY: { + const arr = as([], index); + for (const index of value) + arr.push(unpair(index)); + return arr; + } + case OBJECT: { + const object = as({}, index); + for (const [key, index] of value) + object[unpair(key)] = unpair(index); + return object; + } + case DATE: + return as(new Date(value), index); + case REGEXP: { + const {source, flags} = value; + return as(new RegExp(source, flags), index); + } + case MAP: { + const map = as(new Map, index); + for (const [key, index] of value) + map.set(unpair(key), unpair(index)); + return map; + } + case SET: { + const set = as(new Set, index); + for (const index of value) + set.add(unpair(index)); + return set; + } + case ERROR: { + const {name, message} = value; + return as(guard(name, message), index); + } + case BIGINT: + return as(BigInt(value), index); + case 'BigInt': + return as(Object(BigInt(value)), index); + case 'ArrayBuffer': + return as(new Uint8Array(value).buffer, value); + case 'DataView': { + const { buffer } = new Uint8Array(value); + return as(new DataView(buffer), value); + } + } + return as(guard(type, value), index); + }; + + return unpair; +}; + +/** + * @typedef {Array} Record a type representation + */ + +/** + * Returns a deserialized value from a serialized array of Records. + * @param {Record[]} serialized a previously serialized value. + * @returns {any} + */ +export const deserialize = serialized => deserializer(new Map, serialized)(0); diff --git a/node_modules/@ungap/structured-clone/esm/index.js b/node_modules/@ungap/structured-clone/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d3b47479adfc55679022b9098fa0b968fed8d818 --- /dev/null +++ b/node_modules/@ungap/structured-clone/esm/index.js @@ -0,0 +1,25 @@ +import {deserialize} from './deserialize.js'; +import {serialize} from './serialize.js'; + +/** + * @typedef {Array} Record a type representation + */ + +/** + * Returns an array of serialized Records. + * @param {any} any a serializable value. + * @param {{transfer?: any[], json?: boolean, lossy?: boolean}?} options an object with + * a transfer option (ignored when polyfilled) and/or non standard fields that + * fallback to the polyfill if present. + * @returns {Record[]} + */ +export default typeof structuredClone === "function" ? + /* c8 ignore start */ + (any, options) => ( + options && ('json' in options || 'lossy' in options) ? + deserialize(serialize(any, options)) : structuredClone(any) + ) : + (any, options) => deserialize(serialize(any, options)); + /* c8 ignore stop */ + +export {deserialize, serialize}; diff --git a/node_modules/@ungap/structured-clone/esm/json.js b/node_modules/@ungap/structured-clone/esm/json.js new file mode 100644 index 0000000000000000000000000000000000000000..23eb95222d1a318faba1bffcd907b5038405ae38 --- /dev/null +++ b/node_modules/@ungap/structured-clone/esm/json.js @@ -0,0 +1,21 @@ +/*! (c) Andrea Giammarchi - ISC */ + +import {deserialize} from './deserialize.js'; +import {serialize} from './serialize.js'; + +const {parse: $parse, stringify: $stringify} = JSON; +const options = {json: true, lossy: true}; + +/** + * Revive a previously stringified structured clone. + * @param {string} str previously stringified data as string. + * @returns {any} whatever was previously stringified as clone. + */ +export const parse = str => deserialize($parse(str)); + +/** + * Represent a structured clone value as string. + * @param {any} any some clone-able value to stringify. + * @returns {string} the value stringified. + */ +export const stringify = any => $stringify(serialize(any, options)); diff --git a/node_modules/@ungap/structured-clone/esm/serialize.js b/node_modules/@ungap/structured-clone/esm/serialize.js new file mode 100644 index 0000000000000000000000000000000000000000..6286047a841fffa4019daaa8967d3a9db5725610 --- /dev/null +++ b/node_modules/@ungap/structured-clone/esm/serialize.js @@ -0,0 +1,171 @@ +import { + VOID, PRIMITIVE, + ARRAY, OBJECT, + DATE, REGEXP, MAP, SET, + ERROR, BIGINT +} from './types.js'; + +const EMPTY = ''; + +const {toString} = {}; +const {keys} = Object; + +const typeOf = value => { + const type = typeof value; + if (type !== 'object' || !value) + return [PRIMITIVE, type]; + + const asString = toString.call(value).slice(8, -1); + switch (asString) { + case 'Array': + return [ARRAY, EMPTY]; + case 'Object': + return [OBJECT, EMPTY]; + case 'Date': + return [DATE, EMPTY]; + case 'RegExp': + return [REGEXP, EMPTY]; + case 'Map': + return [MAP, EMPTY]; + case 'Set': + return [SET, EMPTY]; + case 'DataView': + return [ARRAY, asString]; + } + + if (asString.includes('Array')) + return [ARRAY, asString]; + + if (asString.includes('Error')) + return [ERROR, asString]; + + return [OBJECT, asString]; +}; + +const shouldSkip = ([TYPE, type]) => ( + TYPE === PRIMITIVE && + (type === 'function' || type === 'symbol') +); + +const serializer = (strict, json, $, _) => { + + const as = (out, value) => { + const index = _.push(out) - 1; + $.set(value, index); + return index; + }; + + const pair = value => { + if ($.has(value)) + return $.get(value); + + let [TYPE, type] = typeOf(value); + switch (TYPE) { + case PRIMITIVE: { + let entry = value; + switch (type) { + case 'bigint': + TYPE = BIGINT; + entry = value.toString(); + break; + case 'function': + case 'symbol': + if (strict) + throw new TypeError('unable to serialize ' + type); + entry = null; + break; + case 'undefined': + return as([VOID], value); + } + return as([TYPE, entry], value); + } + case ARRAY: { + if (type) { + let spread = value; + if (type === 'DataView') { + spread = new Uint8Array(value.buffer); + } + else if (type === 'ArrayBuffer') { + spread = new Uint8Array(value); + } + return as([type, [...spread]], value); + } + + const arr = []; + const index = as([TYPE, arr], value); + for (const entry of value) + arr.push(pair(entry)); + return index; + } + case OBJECT: { + if (type) { + switch (type) { + case 'BigInt': + return as([type, value.toString()], value); + case 'Boolean': + case 'Number': + case 'String': + return as([type, value.valueOf()], value); + } + } + + if (json && ('toJSON' in value)) + return pair(value.toJSON()); + + const entries = []; + const index = as([TYPE, entries], value); + for (const key of keys(value)) { + if (strict || !shouldSkip(typeOf(value[key]))) + entries.push([pair(key), pair(value[key])]); + } + return index; + } + case DATE: + return as([TYPE, value.toISOString()], value); + case REGEXP: { + const {source, flags} = value; + return as([TYPE, {source, flags}], value); + } + case MAP: { + const entries = []; + const index = as([TYPE, entries], value); + for (const [key, entry] of value) { + if (strict || !(shouldSkip(typeOf(key)) || shouldSkip(typeOf(entry)))) + entries.push([pair(key), pair(entry)]); + } + return index; + } + case SET: { + const entries = []; + const index = as([TYPE, entries], value); + for (const entry of value) { + if (strict || !shouldSkip(typeOf(entry))) + entries.push(pair(entry)); + } + return index; + } + } + + const {message} = value; + return as([TYPE, {name: type, message}], value); + }; + + return pair; +}; + +/** + * @typedef {Array} Record a type representation + */ + +/** + * Returns an array of serialized Records. + * @param {any} value a serializable value. + * @param {{json?: boolean, lossy?: boolean}?} options an object with a `lossy` or `json` property that, + * if `true`, will not throw errors on incompatible types, and behave more + * like JSON stringify would behave. Symbol and Function will be discarded. + * @returns {Record[]} + */ + export const serialize = (value, {json, lossy} = {}) => { + const _ = []; + return serializer(!(json || lossy), !!json, new Map, _)(value), _; +}; diff --git a/node_modules/@ungap/structured-clone/esm/types.js b/node_modules/@ungap/structured-clone/esm/types.js new file mode 100644 index 0000000000000000000000000000000000000000..50e60ca067667f4df09393a3898137f0c933604e --- /dev/null +++ b/node_modules/@ungap/structured-clone/esm/types.js @@ -0,0 +1,11 @@ +export const VOID = -1; +export const PRIMITIVE = 0; +export const ARRAY = 1; +export const OBJECT = 2; +export const DATE = 3; +export const REGEXP = 4; +export const MAP = 5; +export const SET = 6; +export const ERROR = 7; +export const BIGINT = 8; +// export const SYMBOL = 9; diff --git a/node_modules/@ungap/structured-clone/package.json b/node_modules/@ungap/structured-clone/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3adc31103dafff9d76867959dd226062fca27a9e --- /dev/null +++ b/node_modules/@ungap/structured-clone/package.json @@ -0,0 +1,54 @@ +{ + "name": "@ungap/structured-clone", + "version": "1.3.1", + "description": "A structuredClone polyfill", + "main": "./cjs/index.js", + "scripts": { + "build": "npm run cjs && npm run rollup:json && npm run test", + "cjs": "ascjs esm cjs", + "coverage": "c8 report --reporter=text-lcov > ./coverage/lcov.info", + "rollup:json": "rollup --config rollup/json.config.js", + "test": "c8 node test/index.js" + }, + "keywords": [ + "recursion", + "structured", + "clone", + "algorithm" + ], + "author": "Andrea Giammarchi", + "license": "ISC", + "devDependencies": { + "@rollup/plugin-node-resolve": "^16.0.3", + "@rollup/plugin-terser": "^1.0.0", + "ascjs": "^6.0.3", + "c8": "^11.0.0", + "coveralls": "^3.1.1", + "rollup": "^4.60.3" + }, + "module": "./esm/index.js", + "type": "module", + "sideEffects": false, + "exports": { + ".": { + "import": "./esm/index.js", + "default": "./cjs/index.js" + }, + "./json": { + "import": "./esm/json.js", + "default": "./cjs/json.js" + }, + "./package.json": "./package.json" + }, + "directories": { + "test": "test" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ungap/structured-clone.git" + }, + "bugs": { + "url": "https://github.com/ungap/structured-clone/issues" + }, + "homepage": "https://github.com/ungap/structured-clone#readme" +} diff --git a/node_modules/@ungap/structured-clone/structured-json.js b/node_modules/@ungap/structured-clone/structured-json.js new file mode 100644 index 0000000000000000000000000000000000000000..81373cf4a595d659a4fb2cf299374e618068a8c7 --- /dev/null +++ b/node_modules/@ungap/structured-clone/structured-json.js @@ -0,0 +1 @@ +var StructuredJSON=function(e){"use strict";const r="object"==typeof self?self:globalThis,t=(e,t)=>{switch(e){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+e)}return new r[e](t)},n=e=>((e,r)=>{const n=(r,t)=>(e.set(t,r),r),s=c=>{if(e.has(c))return e.get(c);const[a,o]=r[c];switch(a){case 0:case-1:return n(o,c);case 1:{const e=n([],c);for(const r of o)e.push(s(r));return e}case 2:{const e=n({},c);for(const[r,t]of o)e[s(r)]=s(t);return e}case 3:return n(new Date(o),c);case 4:{const{source:e,flags:r}=o;return n(new RegExp(e,r),c)}case 5:{const e=n(new Map,c);for(const[r,t]of o)e.set(s(r),s(t));return e}case 6:{const e=n(new Set,c);for(const r of o)e.add(s(r));return e}case 7:{const{name:e,message:r}=o;return n(t(e,r),c)}case 8:return n(BigInt(o),c);case"BigInt":return n(Object(BigInt(o)),c);case"ArrayBuffer":return n(new Uint8Array(o).buffer,o);case"DataView":{const{buffer:e}=new Uint8Array(o);return n(new DataView(e),o)}}return n(t(a,o),c)};return s})(new Map,e)(0),s="",{toString:c}={},{keys:a}=Object,o=e=>{const r=typeof e;if("object"!==r||!e)return[0,r];const t=c.call(e).slice(8,-1);switch(t){case"Array":return[1,s];case"Object":return[2,s];case"Date":return[3,s];case"RegExp":return[4,s];case"Map":return[5,s];case"Set":return[6,s];case"DataView":return[1,t]}return t.includes("Array")?[1,t]:t.includes("Error")?[7,t]:[2,t]},u=([e,r])=>0===e&&("function"===r||"symbol"===r),i=(e,{json:r,lossy:t}={})=>{const n=[];return((e,r,t,n)=>{const s=(e,r)=>{const s=n.push(e)-1;return t.set(r,s),s},c=n=>{if(t.has(n))return t.get(n);let[i,f]=o(n);switch(i){case 0:{let r=n;switch(f){case"bigint":i=8,r=n.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+f);r=null;break;case"undefined":return s([-1],n)}return s([i,r],n)}case 1:{if(f){let e=n;return"DataView"===f?e=new Uint8Array(n.buffer):"ArrayBuffer"===f&&(e=new Uint8Array(n)),s([f,[...e]],n)}const e=[],r=s([i,e],n);for(const r of n)e.push(c(r));return r}case 2:{if(f)switch(f){case"BigInt":return s([f,n.toString()],n);case"Boolean":case"Number":case"String":return s([f,n.valueOf()],n)}if(r&&"toJSON"in n)return c(n.toJSON());const t=[],l=s([i,t],n);for(const r of a(n))!e&&u(o(n[r]))||t.push([c(r),c(n[r])]);return l}case 3:return s([i,n.toISOString()],n);case 4:{const{source:e,flags:r}=n;return s([i,{source:e,flags:r}],n)}case 5:{const r=[],t=s([i,r],n);for(const[t,s]of n)(e||!u(o(t))&&!u(o(s)))&&r.push([c(t),c(s)]);return t}case 6:{const r=[],t=s([i,r],n);for(const t of n)!e&&u(o(t))||r.push(c(t));return t}}const{message:l}=n;return s([i,{name:f,message:l}],n)};return c})(!(r||t),!!r,new Map,n)(e),n},{parse:f,stringify:l}=JSON,w={json:!0,lossy:!0};return e.parse=e=>n(f(e)),e.stringify=e=>l(i(e,w)),e}({}); diff --git a/node_modules/@vitejs/plugin-react/LICENSE b/node_modules/@vitejs/plugin-react/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9c1b313d7b18166024d52473b2ed645f5b4e64dd --- /dev/null +++ b/node_modules/@vitejs/plugin-react/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@vitejs/plugin-react/README.md b/node_modules/@vitejs/plugin-react/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8556cace7610f68c2852209b8977158a820421af --- /dev/null +++ b/node_modules/@vitejs/plugin-react/README.md @@ -0,0 +1,169 @@ +# @vitejs/plugin-react [![npm](https://img.shields.io/npm/v/@vitejs/plugin-react.svg)](https://npmjs.com/package/@vitejs/plugin-react) + +The default Vite plugin for React projects. + +- enable [Fast Refresh](https://www.npmjs.com/package/react-refresh) in development (requires react >= 16.9) +- use the [automatic JSX runtime](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html) +- small installation size + +```js +// vite.config.js +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [react()], +}) +``` + +## Options + +### include + +Includes `.js`, `.jsx`, `.ts` & `.tsx` by default. This option can be used to add fast refresh to `.mdx` files: + +```js +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import mdx from '@mdx-js/rollup' + +export default defineConfig({ + plugins: [ + { enforce: 'pre', ...mdx() }, + react({ include: /\.(mdx|js|jsx|ts|tsx)$/ }), + ], +}) +``` + +### exclude + +The default value is `/node_modules/`. You may use it to exclude JSX/TSX files that runs in a worker or are not React files. +Except if explicitly desired, you should keep `node_modules` in the exclude list: + +```js +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [ + react({ exclude: [/\/pdf\//, /\.solid\.tsx$/, /\/node_modules\//] }), + ], +}) +``` + +### jsxImportSource + +Control where the JSX factory is imported from. By default, this is inferred from `jsxImportSource` from corresponding a tsconfig file for a transformed file. + +```js +react({ jsxImportSource: '@emotion/react' }) +``` + +### jsxRuntime + +By default, the plugin uses the [automatic JSX runtime](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html). However, if you encounter any issues, you may opt out using the `jsxRuntime` option. + +```js +react({ jsxRuntime: 'classic' }) +``` + +### reactRefreshHost + +The `reactRefreshHost` option is only necessary in a module federation context. It enables HMR to work between a remote & host application. In your remote Vite config, you would add your host origin: + +```js +react({ reactRefreshHost: 'http://localhost:3000' }) +``` + +Under the hood, this simply updates the React Fash Refresh runtime URL from `/@react-refresh` to `http://localhost:3000/@react-refresh` to ensure there is only one Refresh runtime across the whole application. Note that if you define `base` option in the host application, you need to include it in the option, like: `http://localhost:3000/{base}`. + +## React Compiler + +[React Compiler](https://react.dev/learn/react-compiler) support is available via the exported `reactCompilerPreset` helper, which requires [`@rolldown/plugin-babel`](https://npmx.dev/package/@rolldown/plugin-babel) and [`babel-plugin-react-compiler`](https://npmx.dev/package/babel-plugin-react-compiler) and [`@babel/core`](https://npmx.dev/package/@babel/core) as peer dependencies: + +```sh +npm install -D @rolldown/plugin-babel @babel/core babel-plugin-react-compiler +``` + +If you are using TypeScript, you will also need to install [`@types/babel__core`](https://npmx.dev/package/@types/babel__core): + +```sh +npm install -D @types/babel__core +``` + +```js +// vite.config.js +import { defineConfig } from 'vite' +import react, { reactCompilerPreset } from '@vitejs/plugin-react' +import babel from '@rolldown/plugin-babel' + +export default defineConfig({ + plugins: [react(), babel({ presets: [reactCompilerPreset()] })], +}) +``` + +The `reactCompilerPreset` accepts an optional options object with the following properties: + +- `compilationMode` — Set to `'annotation'` to only compile components annotated with `"use memo"`. +- `target` — Set to `'17'` or `'18'` to target older React versions (uses `react-compiler-runtime` instead of `react/compiler-runtime`). + +Additional options can be found in the [documentation](https://react.dev/reference/react-compiler/configuration). + +```js +babel({ + presets: [reactCompilerPreset({ compilationMode: 'annotation' })], +}) +``` + +> [!TIP] +> +> `reactCompilerPreset` is only a convenient helper with a preconfigured filter. You can configure override the filters to fit your project structure or code. For example, if you know a large portion of your files are never React/hook-related or won't benefit from the React Compiler, you can aggressively exclude them via `rolldown.filter`: +> +> ```js +> const myPreset = reactCompilerPreset() +> myPreset.rolldown.filter.id.exclude = ['src/legacy/**', 'src/utils/**'] +> +> babel({ +> presets: [myPreset], +> }) +> ``` + +## `@vitejs/plugin-react/preamble` + +The package provides `@vitejs/plugin-react/preamble` to initialize HMR runtime from client entrypoint for SSR applications which don't use [`transformIndexHtml` API](https://vite.dev/guide/api-javascript.html#vitedevserver). For example: + +```js +// [entry.client.js] +import '@vitejs/plugin-react/preamble' +``` + +Alternatively, you can manually call `transformIndexHtml` during SSR, which sets up equivalent initialization code. Here's an example for an Express server: + +```js +app.get('/', async (req, res, next) => { + try { + let html = fs.readFileSync(path.resolve(root, 'index.html'), 'utf-8') + + // Transform HTML using Vite plugins. + html = await viteServer.transformIndexHtml(req.url, html) + + res.send(html) + } catch (e) { + return next(e) + } +}) +``` + +Otherwise, you'll get the following error: + +``` +Uncaught Error: @vitejs/plugin-react can't detect preamble. Something is wrong. +``` + +## Consistent components exports + +For React refresh to work correctly, your file should only export React components. You can find a good explanation in the [Gatsby docs](https://www.gatsbyjs.com/docs/reference/local-development/fast-refresh/#how-it-works). + +If an incompatible change in exports is found, the module will be invalidated and HMR will propagate. To make it easier to export simple constants alongside your component, the module is only invalidated when their value changes. + +You can catch mistakes and get more detailed warnings with this [ESLint rule](https://github.com/ArnaudBarre/eslint-plugin-react-refresh), or the equivalent [Oxlint rule](https://oxc.rs/docs/guide/usage/linter/rules/react/only-export-components.html). diff --git a/node_modules/@vitejs/plugin-react/package.json b/node_modules/@vitejs/plugin-react/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ed7f7d68a86b8028371d34a411d601a592711c4d --- /dev/null +++ b/node_modules/@vitejs/plugin-react/package.json @@ -0,0 +1,87 @@ +{ + "name": "@vitejs/plugin-react", + "version": "6.0.2", + "description": "The default Vite plugin for React projects", + "keywords": [ + "fast refresh", + "react", + "react-refresh", + "vite", + "vite-plugin" + ], + "homepage": "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react#readme", + "bugs": { + "url": "https://github.com/vitejs/vite-plugin-react/issues" + }, + "license": "MIT", + "author": "Evan You", + "contributors": [ + "Alec Larson", + "Arnaud Barré" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/vitejs/vite-plugin-react.git", + "directory": "packages/plugin-react" + }, + "files": [ + "dist", + "types" + ], + "type": "module", + "imports": { + "#optionalTypes": "./types/optionalTypes.d.ts" + }, + "exports": { + ".": "./dist/index.js", + "./preamble": "./types/preamble.d.ts" + }, + "scripts": { + "dev": "tsdown --watch ./src --watch ../common", + "build": "tsdown", + "prepublishOnly": "npm run build", + "test-unit": "vitest run" + }, + "dependencies": { + "@rolldown/pluginutils": "^1.0.0" + }, + "devDependencies": { + "@babel/core": "8.0.0-rc.4", + "@rolldown/plugin-babel": "^0.2.3", + "@vitejs/react-common": "workspace:*", + "babel-plugin-react-compiler": "^1.0.0", + "react": "^19.2.6", + "react-dom": "^19.2.6", + "rolldown": "^1.0.0", + "tsdown": "^0.22.0", + "vite": "^8.0.11" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", + "babel-plugin-react-compiler": "^1.0.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + } + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "compatiblePackages": { + "schemaVersion": 1, + "rolldown": { + "type": "compatible", + "versions": "^1.0.0", + "note": "You can use Rolldown's built-in feature directly." + }, + "rollup": { + "type": "incompatible", + "reason": "Uses Rolldown-specific APIs or Vite-specific APIs" + } + } +} diff --git a/node_modules/@vitejs/plugin-react/types/optionalTypes.d.ts b/node_modules/@vitejs/plugin-react/types/optionalTypes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f780e933f9c9204038c5dc4ed2664c672097fd92 --- /dev/null +++ b/node_modules/@vitejs/plugin-react/types/optionalTypes.d.ts @@ -0,0 +1,12 @@ +/* eslint-disable @typescript-eslint/ban-ts-comment */ + +// @ts-ignore --- `@rolldown/plugin-babel` is an optional peer dependency, so this may cause an error +import type * as pluginBabel from '@rolldown/plugin-babel' +// @ts-ignore --- `babel-plugin-react-compiler` is an optional peer dependency, so this may cause an error +import type * as babelPluginReactCompiler from 'babel-plugin-react-compiler' + +// @ts-ignore --- `@rolldown/plugin-babel` is an optional peer dependency, so this may cause an error +export type RolldownBabelPreset = pluginBabel.RolldownBabelPreset +// @ts-ignore --- `babel-plugin-react-compiler` is an optional peer dependency, so this may cause an error +export type ReactCompilerBabelPluginOptions = + babelPluginReactCompiler.PluginOptions diff --git a/node_modules/@vitejs/plugin-react/types/preamble.d.ts b/node_modules/@vitejs/plugin-react/types/preamble.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..336ce12bb9106afdf843063ee67c0c1970f70d37 --- /dev/null +++ b/node_modules/@vitejs/plugin-react/types/preamble.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/@vitest/coverage-istanbul/LICENSE b/node_modules/@vitest/coverage-istanbul/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0e5771dddf4e96ebc77c349f53fc763b910e63c0 --- /dev/null +++ b/node_modules/@vitest/coverage-istanbul/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@vitest/coverage-istanbul/README.md b/node_modules/@vitest/coverage-istanbul/README.md new file mode 100644 index 0000000000000000000000000000000000000000..92720622039737e23d9feb89fadfdb0e9349a3a0 --- /dev/null +++ b/node_modules/@vitest/coverage-istanbul/README.md @@ -0,0 +1,30 @@ +# @vitest/coverage-istanbul + +[![NPM version](https://img.shields.io/npm/v/@vitest/coverage-istanbul?color=a1b858&label=)](https://npmx.dev/package/@vitest/coverage-istanbul) + +Vitest coverage provider that instruments code coverage via [istanbul](https://istanbul.js.org/). + +## Installation + +After installing the package, specify `istanbul` in the `coverage.provider` field of your Vitest configuration: + +```ts +// vitest.config.ts +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + coverage: { + provider: 'istanbul', + }, + }, +}) +``` + +Then run Vitest with coverage: + +```sh +npx vitest --coverage +``` + +[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/coverage-istanbul) | [Documentation](https://vitest.dev/guide/coverage) diff --git a/node_modules/@vitest/coverage-istanbul/package.json b/node_modules/@vitest/coverage-istanbul/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8ae6c6fe803babd7dfbd628748bfe9816f638544 --- /dev/null +++ b/node_modules/@vitest/coverage-istanbul/package.json @@ -0,0 +1,69 @@ +{ + "name": "@vitest/coverage-istanbul", + "type": "module", + "version": "4.1.9", + "description": "Istanbul coverage provider for Vitest", + "author": "Anthony Fu ", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://vitest.dev/guide/coverage", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/coverage-istanbul" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "keywords": [ + "vite", + "vitest", + "test", + "coverage", + "istanbul" + ], + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "peerDependencies": { + "vitest": "4.1.9" + }, + "dependencies": { + "@babel/core": "^7.29.0", + "@istanbuljs/schema": "^0.1.3", + "@jridgewell/gen-mapping": "^0.3.13", + "@jridgewell/trace-mapping": "0.3.31", + "istanbul-lib-coverage": "^3.2.2", + "istanbul-lib-report": "^3.0.1", + "istanbul-reports": "^3.2.0", + "magicast": "^0.5.2", + "obug": "^2.1.1", + "tinyrainbow": "^3.1.0" + }, + "devDependencies": { + "@types/istanbul-lib-coverage": "^2.0.6", + "@types/istanbul-lib-instrument": "^1.7.8", + "@types/istanbul-lib-report": "^3.0.3", + "@types/istanbul-lib-source-maps": "^4.0.4", + "@types/istanbul-reports": "^3.0.4", + "istanbul-lib-instrument": "^6.0.3", + "istanbul-lib-source-maps": "^5.0.6", + "pathe": "^2.0.3", + "vitest": "4.1.9" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch --watch.include 'src/**'" + } +} \ No newline at end of file diff --git a/node_modules/@vitest/coverage-v8/LICENSE b/node_modules/@vitest/coverage-v8/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0e5771dddf4e96ebc77c349f53fc763b910e63c0 --- /dev/null +++ b/node_modules/@vitest/coverage-v8/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@vitest/coverage-v8/README.md b/node_modules/@vitest/coverage-v8/README.md new file mode 100644 index 0000000000000000000000000000000000000000..452c7fc1e0d245776f4f1fceb48014110091433b --- /dev/null +++ b/node_modules/@vitest/coverage-v8/README.md @@ -0,0 +1,30 @@ +# @vitest/coverage-v8 + +[![NPM version](https://img.shields.io/npm/v/@vitest/coverage-v8?color=a1b858&label=)](https://npmx.dev/package/@vitest/coverage-v8) + +Vitest coverage provider that supports native code coverage via [v8](https://v8.dev/blog/javascript-code-coverage). + +## Installation + +After installing the package, specify `v8` in the `coverage.provider` field of your Vitest configuration (or leave it empty as it is the default provider): + +```ts +// vitest.config.ts +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + coverage: { + provider: 'v8', + }, + }, +}) +``` + +Then run Vitest with coverage: + +```sh +npx vitest --coverage +``` + +[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/coverage-v8) | [Documentation](https://vitest.dev/guide/coverage) diff --git a/node_modules/@vitest/coverage-v8/package.json b/node_modules/@vitest/coverage-v8/package.json new file mode 100644 index 0000000000000000000000000000000000000000..332f3692bd5c3dd68eb0ed51b9329aca0956d527 --- /dev/null +++ b/node_modules/@vitest/coverage-v8/package.json @@ -0,0 +1,77 @@ +{ + "name": "@vitest/coverage-v8", + "type": "module", + "version": "4.1.9", + "description": "V8 coverage provider for Vitest", + "author": "Anthony Fu ", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://vitest.dev/guide/coverage", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/coverage-v8" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "keywords": [ + "vite", + "vitest", + "test", + "coverage", + "v8" + ], + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./browser": { + "types": "./dist/browser.d.ts", + "default": "./dist/browser.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "peerDependencies": { + "@vitest/browser": "4.1.9", + "vitest": "4.1.9" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + }, + "dependencies": { + "@bcoe/v8-coverage": "^1.0.2", + "ast-v8-to-istanbul": "^1.0.0", + "istanbul-lib-coverage": "^3.2.2", + "istanbul-lib-report": "^3.0.1", + "istanbul-reports": "^3.2.0", + "magicast": "^0.5.2", + "obug": "^2.1.1", + "std-env": "^4.0.0-rc.1", + "tinyrainbow": "^3.1.0", + "@vitest/utils": "4.1.9" + }, + "devDependencies": { + "@types/istanbul-lib-coverage": "^2.0.6", + "@types/istanbul-lib-report": "^3.0.3", + "@types/istanbul-reports": "^3.0.4", + "pathe": "^2.0.3", + "@vitest/browser-playwright": "4.1.9", + "@vitest/browser": "4.1.9", + "vitest": "4.1.9" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch --watch.include 'src/**'" + } +} \ No newline at end of file diff --git a/node_modules/@vitest/expect/LICENSE b/node_modules/@vitest/expect/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0e5771dddf4e96ebc77c349f53fc763b910e63c0 --- /dev/null +++ b/node_modules/@vitest/expect/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@vitest/expect/README.md b/node_modules/@vitest/expect/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d3c72567dfa1801afc71d2118d76c7b8e521b88a --- /dev/null +++ b/node_modules/@vitest/expect/README.md @@ -0,0 +1,25 @@ +# @vitest/expect + +[![NPM version](https://img.shields.io/npm/v/@vitest/runner?color=a1b858&label=)](https://npmx.dev/package/@vitest/runner) + +Jest's expect matchers as a Chai plugin. + +## Usage + +```js +import { + JestAsymmetricMatchers, + JestChaiExpect, + JestExtend, +} from '@vitest/expect' +import * as chai from 'chai' + +// allows using expect.extend instead of chai.use to extend plugins +chai.use(JestExtend) +// adds all jest matchers to expect +chai.use(JestChaiExpect) +// adds asymmetric matchers like stringContaining, objectContaining +chai.use(JestAsymmetricMatchers) +``` + +[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/expect) | [Documentation](https://vitest.dev/api/expect) diff --git a/node_modules/@vitest/expect/package.json b/node_modules/@vitest/expect/package.json new file mode 100644 index 0000000000000000000000000000000000000000..23b9f107b1e3b86fbc22b92d12a5fd24f8bfcc9b --- /dev/null +++ b/node_modules/@vitest/expect/package.json @@ -0,0 +1,52 @@ +{ + "name": "@vitest/expect", + "type": "module", + "version": "4.1.9", + "description": "Jest's expect matchers as a Chai plugin", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://vitest.dev/api/expect", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/expect" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "keywords": [ + "vitest", + "test", + "chai", + "assertion" + ], + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", + "chai": "^6.2.2", + "tinyrainbow": "^3.1.0", + "@vitest/spy": "4.1.9", + "@vitest/utils": "4.1.9" + }, + "devDependencies": { + "@vitest/runner": "4.1.9" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/node_modules/@vitest/mocker/LICENSE b/node_modules/@vitest/mocker/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0e5771dddf4e96ebc77c349f53fc763b910e63c0 --- /dev/null +++ b/node_modules/@vitest/mocker/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@vitest/mocker/README.md b/node_modules/@vitest/mocker/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dae8292f63da0913249fd1866f1479a26c30218f --- /dev/null +++ b/node_modules/@vitest/mocker/README.md @@ -0,0 +1,7 @@ +# @vitest/mocker + +[![NPM version](https://img.shields.io/npm/v/@vitest/mocker?color=a1b858&label=)](https://npmx.dev/package/@vitest/mocker) + +Vitest's module mocker implementation. + +[GitHub](https://github.com/vitest-dev/vitest/blob/main/packages/mocker/) | [Documentation](https://github.com/vitest-dev/vitest/blob/main/packages/mocker/EXPORTS.md) diff --git a/node_modules/@vitest/mocker/package.json b/node_modules/@vitest/mocker/package.json new file mode 100644 index 0000000000000000000000000000000000000000..fd26338b101e20d37cdca62c612fb6585ce3c19b --- /dev/null +++ b/node_modules/@vitest/mocker/package.json @@ -0,0 +1,97 @@ +{ + "name": "@vitest/mocker", + "type": "module", + "version": "4.1.9", + "description": "Vitest module mocker implementation", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/mocker", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/mocker" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "keywords": [ + "vitest", + "test", + "mock" + ], + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./node": { + "types": "./dist/node.d.ts", + "default": "./dist/node.js" + }, + "./browser": { + "types": "./dist/browser.d.ts", + "default": "./dist/browser.js" + }, + "./redirect": { + "types": "./dist/redirect.d.ts", + "default": "./dist/redirect.js" + }, + "./automock": { + "types": "./dist/automock.d.ts", + "default": "./dist/automock.js" + }, + "./register": { + "types": "./dist/register.d.ts", + "default": "./dist/register.js" + }, + "./auto-register": { + "types": "./dist/register.d.ts", + "default": "./dist/register.js" + }, + "./transforms": { + "types": "./dist/transforms.d.ts", + "default": "./dist/transforms.js" + }, + "./package.json": "./package.json" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "*.d.ts", + "dist" + ], + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + }, + "dependencies": { + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21", + "@vitest/spy": "4.1.9" + }, + "devDependencies": { + "@types/estree": "^1.0.8", + "acorn-walk": "^8.3.5", + "cjs-module-lexer": "^2.2.0", + "es-module-lexer": "^2.0.0", + "msw": "^2.12.10", + "pathe": "^2.0.3", + "vite": "^6.3.5", + "@vitest/spy": "4.1.9", + "@vitest/utils": "4.1.9" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/node_modules/@vitest/pretty-format/LICENSE b/node_modules/@vitest/pretty-format/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0e5771dddf4e96ebc77c349f53fc763b910e63c0 --- /dev/null +++ b/node_modules/@vitest/pretty-format/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@vitest/pretty-format/README.md b/node_modules/@vitest/pretty-format/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d36596330431f168ca4bebf351df868eaac5d9e8 --- /dev/null +++ b/node_modules/@vitest/pretty-format/README.md @@ -0,0 +1,7 @@ +# @vitest/pretty-format + +[![NPM version](https://img.shields.io/npm/v/@vitest/pretty-format?color=a1b858&label=)](https://npmx.dev/package/@vitest/pretty-format) + +Vitest's fork of Jest's [`pretty-format`](https://npmx.dev/package/pretty-format). + +[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/pretty-format) | [Documentation](https://github.com/vitest-dev/vitest/blob/main/packages/pretty-format/USAGE.md) diff --git a/node_modules/@vitest/pretty-format/package.json b/node_modules/@vitest/pretty-format/package.json new file mode 100644 index 0000000000000000000000000000000000000000..84aa445fbc0167723cceae8509f51ae1c7c8b0b7 --- /dev/null +++ b/node_modules/@vitest/pretty-format/package.json @@ -0,0 +1,50 @@ +{ + "name": "@vitest/pretty-format", + "type": "module", + "version": "4.1.9", + "description": "Fork of pretty-format with support for ESM", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/pretty-format", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/pretty-format" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "keywords": [ + "vitest", + "test", + "pretty", + "pretty-format" + ], + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "*.d.ts", + "dist" + ], + "dependencies": { + "tinyrainbow": "^3.1.0" + }, + "devDependencies": { + "@types/react-is": "^19.2.0", + "react-is": "^19.2.4", + "react-is-18": "npm:react-is@18.3.1" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/node_modules/@vitest/runner/LICENSE b/node_modules/@vitest/runner/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0e5771dddf4e96ebc77c349f53fc763b910e63c0 --- /dev/null +++ b/node_modules/@vitest/runner/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@vitest/runner/README.md b/node_modules/@vitest/runner/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2f6884dd57c13d664ebda99761ebbd813098c3e2 --- /dev/null +++ b/node_modules/@vitest/runner/README.md @@ -0,0 +1,7 @@ +# @vitest/runner + +[![NPM version](https://img.shields.io/npm/v/@vitest/runner?color=a1b858&label=)](https://npmx.dev/package/@vitest/runner) + +Vitest mechanism to collect and run tests. + +[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/runner) | [Documentation](https://vitest.dev/api/advanced/runner) diff --git a/node_modules/@vitest/runner/package.json b/node_modules/@vitest/runner/package.json new file mode 100644 index 0000000000000000000000000000000000000000..de06fd6a9b939c7ba2b8cd487db254553ed75640 --- /dev/null +++ b/node_modules/@vitest/runner/package.json @@ -0,0 +1,53 @@ +{ + "name": "@vitest/runner", + "type": "module", + "version": "4.1.9", + "description": "Vitest test runner", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://vitest.dev/api/advanced/runner", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/runner" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "keywords": [ + "vitest", + "test", + "test-runner" + ], + "sideEffects": true, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./utils": { + "types": "./dist/utils.d.ts", + "default": "./dist/utils.js" + }, + "./types": { + "types": "./dist/types.d.ts", + "default": "./dist/types.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "*.d.ts", + "dist" + ], + "dependencies": { + "pathe": "^2.0.3", + "@vitest/utils": "4.1.9" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/node_modules/@vitest/runner/types.d.ts b/node_modules/@vitest/runner/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..26a125423d414fa445c87ab4621e8e3286a7875b --- /dev/null +++ b/node_modules/@vitest/runner/types.d.ts @@ -0,0 +1 @@ +export * from './dist/types.js' diff --git a/node_modules/@vitest/runner/utils.d.ts b/node_modules/@vitest/runner/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e3f344e48a8d345df0c9350f51033c85f0e3a3a1 --- /dev/null +++ b/node_modules/@vitest/runner/utils.d.ts @@ -0,0 +1 @@ +export * from './dist/utils.js' diff --git a/node_modules/@vitest/snapshot/LICENSE b/node_modules/@vitest/snapshot/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0e5771dddf4e96ebc77c349f53fc763b910e63c0 --- /dev/null +++ b/node_modules/@vitest/snapshot/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@vitest/snapshot/README.md b/node_modules/@vitest/snapshot/README.md new file mode 100644 index 0000000000000000000000000000000000000000..db0e4f81e457be4425783f5c9cf1c7804ce86dd9 --- /dev/null +++ b/node_modules/@vitest/snapshot/README.md @@ -0,0 +1,88 @@ +# @vitest/snapshot + +[![NPM version](https://img.shields.io/npm/v/@vitest/snapshot?color=a1b858&label=)](https://npmx.dev/package/@vitest/snapshot) + +Lightweight implementation of Jest's snapshots. + +## Usage + +```js +import { SnapshotClient } from '@vitest/snapshot' +import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment' +import { SnapshotManager } from '@vitest/snapshot/manager' + +const client = new SnapshotClient({ + // you need to provide your own equality check implementation if you use it + // this function is called when `.toMatchSnapshot({ property: 1 })` is called + isEqual: (received, expected) => + equals(received, expected, [iterableEquality, subsetEquality]), +}) + +// class that implements snapshot saving and reading +// by default uses fs module, but you can provide your own implementation depending on the environment +const environment = new NodeSnapshotEnvironment() + +// you need to implement this yourselves, +// this depends on your runner +function getCurrentFilepath() { + return '/file.spec.js' +} +function getCurrentTestName() { + return 'test1' +} + +// example for inline snapshots, nothing is required to support regular snapshots, +// just call `assert` with `isInline: false` +function wrapper(received) { + function __INLINE_SNAPSHOT__(inlineSnapshot, message) { + client.assert({ + received, + message, + isInline: true, + inlineSnapshot, + filepath: getCurrentFilepath(), + name: getCurrentTestName(), + }) + } + return { + // the name is hard-coded, it should be inside another function, so Vitest can find the actual test file where it was called (parses call stack trace + 2) + // you can override this behaviour in SnapshotState's `_inferInlineSnapshotStack` method by providing your own SnapshotState to SnapshotClient constructor + toMatchInlineSnapshot: (...args) => __INLINE_SNAPSHOT__(...args), + } +} + +const options = { + updateSnapshot: 'new', + snapshotEnvironment: environment, +} + +await client.startCurrentRun( + getCurrentFilepath(), + getCurrentTestName(), + options +) + +// this will save snapshot to a file which is returned by "snapshotEnvironment.resolvePath" +client.assert({ + received: 'some text', + isInline: false, +}) + +// uses "pretty-format", so it requires quotes +// also naming is hard-coded when parsing test files +wrapper('text 1').toMatchInlineSnapshot() +wrapper('text 2').toMatchInlineSnapshot('"text 2"') + +const result = await client.finishCurrentRun() // this saves files and returns SnapshotResult + +// you can use manager to manage several clients +const manager = new SnapshotManager(options) +manager.add(result) + +// do something +// and then read the summary + +console.log(manager.summary) +``` + +[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/snapshot) | [Documentation](https://vitest.dev/guide/snapshot) diff --git a/node_modules/@vitest/snapshot/environment.d.ts b/node_modules/@vitest/snapshot/environment.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..855f0d10a8c55b2a80dc264d1b3b3677b3ee9094 --- /dev/null +++ b/node_modules/@vitest/snapshot/environment.d.ts @@ -0,0 +1 @@ +export * from './dist/environment.js' diff --git a/node_modules/@vitest/snapshot/manager.d.ts b/node_modules/@vitest/snapshot/manager.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f3e80774b831684b8bfb08e7239407a84dceb955 --- /dev/null +++ b/node_modules/@vitest/snapshot/manager.d.ts @@ -0,0 +1 @@ +export * from './dist/manager.js' diff --git a/node_modules/@vitest/snapshot/package.json b/node_modules/@vitest/snapshot/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b6b91f0802f7702671fd225d9a9d0cc1d3c68e51 --- /dev/null +++ b/node_modules/@vitest/snapshot/package.json @@ -0,0 +1,59 @@ +{ + "name": "@vitest/snapshot", + "type": "module", + "version": "4.1.9", + "description": "Vitest snapshot manager", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://vitest.dev/guide/snapshot", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/snapshot" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "keywords": [ + "vitest", + "test", + "snapshot" + ], + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./environment": { + "types": "./dist/environment.d.ts", + "default": "./dist/environment.js" + }, + "./manager": { + "types": "./dist/manager.d.ts", + "default": "./dist/manager.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "*.d.ts", + "dist" + ], + "dependencies": { + "magic-string": "^0.30.21", + "pathe": "^2.0.3", + "@vitest/pretty-format": "4.1.9", + "@vitest/utils": "4.1.9" + }, + "devDependencies": { + "@types/natural-compare": "^1.4.3", + "natural-compare": "^1.4.0" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/node_modules/@vitest/spy/LICENSE b/node_modules/@vitest/spy/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0e5771dddf4e96ebc77c349f53fc763b910e63c0 --- /dev/null +++ b/node_modules/@vitest/spy/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@vitest/spy/README.md b/node_modules/@vitest/spy/README.md new file mode 100644 index 0000000000000000000000000000000000000000..97129c5ea73dee8deddc16ce9109719df0146bba --- /dev/null +++ b/node_modules/@vitest/spy/README.md @@ -0,0 +1,7 @@ +# @vitest/spy + +[![NPM version](https://img.shields.io/npm/v/@vitest/spy?color=a1b858&label=)](https://npmx.dev/package/@vitest/spy) + +Lightweight Jest-compatible mocking implementation. + +[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/spy) | [Documentation](https://vitest.dev/api/mock) diff --git a/node_modules/@vitest/spy/optional-types.d.ts b/node_modules/@vitest/spy/optional-types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ba94336682fd1539c342061fd7e6490c5c4fbb1a --- /dev/null +++ b/node_modules/@vitest/spy/optional-types.d.ts @@ -0,0 +1,6 @@ +/* eslint-disable ts/ban-ts-comment */ + +export interface Disposable { + // @ts-ignore -- Symbol.dispose might not be in user types + [Symbol.dispose]: () => void +} diff --git a/node_modules/@vitest/spy/package.json b/node_modules/@vitest/spy/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0c6e07dc5f92f0e4f7644a3eb2cd6a409655e1ae --- /dev/null +++ b/node_modules/@vitest/spy/package.json @@ -0,0 +1,46 @@ +{ + "name": "@vitest/spy", + "type": "module", + "version": "4.1.9", + "description": "Lightweight Jest compatible spy implementation", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://vitest.dev/api/mock", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/spy" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "keywords": [ + "vitest", + "test", + "mock", + "spy", + "intercept" + ], + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./optional-types.js": { + "types": "./optional-types.d.ts" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist", + "optional-types.d.ts" + ], + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/node_modules/@vitest/utils/LICENSE b/node_modules/@vitest/utils/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0e5771dddf4e96ebc77c349f53fc763b910e63c0 --- /dev/null +++ b/node_modules/@vitest/utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@vitest/utils/README.md b/node_modules/@vitest/utils/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ee3b768a0d61255c913806140a8d57956594ff21 --- /dev/null +++ b/node_modules/@vitest/utils/README.md @@ -0,0 +1,7 @@ +# @vitest/utils + +[![NPM version](https://img.shields.io/npm/v/@vitest/utils?color=a1b858&label=)](https://npmx.dev/package/@vitest/utils) + +Internal shared utilities used by other Vitest packages. + +[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/utils) | [Documentation](https://vitest.dev/) diff --git a/node_modules/@vitest/utils/diff.d.ts b/node_modules/@vitest/utils/diff.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a66b86595c065228ede7e5adad789331f3efce0 --- /dev/null +++ b/node_modules/@vitest/utils/diff.d.ts @@ -0,0 +1 @@ +export * from './dist/diff.js' diff --git a/node_modules/@vitest/utils/error.d.ts b/node_modules/@vitest/utils/error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9329baa87d94cc608a51d289e80c88bcbb5e0b99 --- /dev/null +++ b/node_modules/@vitest/utils/error.d.ts @@ -0,0 +1 @@ +export * from './dist/error.js' diff --git a/node_modules/@vitest/utils/helpers.d.ts b/node_modules/@vitest/utils/helpers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0add1d0f2bd1444960da3a46d4525117a9b2f1ea --- /dev/null +++ b/node_modules/@vitest/utils/helpers.d.ts @@ -0,0 +1 @@ +export * from './dist/helpers.js' diff --git a/node_modules/@vitest/utils/package.json b/node_modules/@vitest/utils/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d352d6bcf7307911a05ff54b28fd55b0c01127c8 --- /dev/null +++ b/node_modules/@vitest/utils/package.json @@ -0,0 +1,102 @@ +{ + "name": "@vitest/utils", + "type": "module", + "version": "4.1.9", + "description": "Shared Vitest utility functions", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/utils", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/utils" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./diff": { + "types": "./dist/diff.d.ts", + "default": "./dist/diff.js" + }, + "./resolver": { + "types": "./dist/resolver.d.ts", + "default": "./dist/resolver.js" + }, + "./error": { + "types": "./dist/error.d.ts", + "default": "./dist/error.js" + }, + "./helpers": { + "types": "./dist/helpers.d.ts", + "default": "./dist/helpers.js" + }, + "./offset": { + "types": "./dist/offset.d.ts", + "default": "./dist/offset.js" + }, + "./constants": { + "types": "./dist/constants.d.ts", + "default": "./dist/constants.js" + }, + "./timers": { + "types": "./dist/timers.d.ts", + "default": "./dist/timers.js" + }, + "./display": { + "types": "./dist/display.d.ts", + "default": "./dist/display.js" + }, + "./source-map": { + "types": "./dist/source-map.d.ts", + "default": "./dist/source-map.js" + }, + "./source-map/node": { + "types": "./dist/source-map/node.d.ts", + "default": "./dist/source-map/node.js" + }, + "./serialize": { + "types": "./dist/serialize.d.ts", + "default": "./dist/serialize.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "typesVersions": { + "*": { + "source-map": [ + "dist/source-map.d.ts" + ], + "source-map/node": [ + "dist/source-map/node.d.ts" + ] + } + }, + "files": [ + "*.d.ts", + "dist" + ], + "dependencies": { + "convert-source-map": "^2.0.0", + "tinyrainbow": "^3.1.0", + "@vitest/pretty-format": "4.1.9" + }, + "devDependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@types/convert-source-map": "^2.0.3", + "@types/estree": "^1.0.8", + "diff-sequences": "^29.6.3", + "loupe": "^3.2.1" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/node_modules/abs-svg-path/Readme.md b/node_modules/abs-svg-path/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..0f1a6ee4e1b73e82f65677d8592770f2cb3e2bea --- /dev/null +++ b/node_modules/abs-svg-path/Readme.md @@ -0,0 +1,35 @@ + +# abs-svg-path + + redefine an svg path with absolute coordinates + +## Installation + +_With [packin](//github.com/jkroso/packin) or [component](//github.com/component/component)_ + + $ packin add jkroso/abs-svg-path + +then in your app: + +```js +var abs = require('abs-svg-path') +``` + +## API + +### abs(path) + + redefine `path` with absolute coordinates + +```js +abs([['l',10,20],['l',30,40]]) // => [['L',10,20],['L',40,60]] +abs([ + ['q', 1,2, 33,44], + ['L', 50,60], + ['c', 1,2, 3,4, 33,44] +]) // => [['Q',1,2,33,44],['L', 50, 60],['C',51,62, 53,64, 83,104]] +``` + +## Running the tests + +Just run `make test` diff --git a/node_modules/abs-svg-path/index.js b/node_modules/abs-svg-path/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fd5543715797b4450cf7b572ca20af5f41cc4f93 --- /dev/null +++ b/node_modules/abs-svg-path/index.js @@ -0,0 +1,67 @@ + +module.exports = absolutize + +/** + * redefine `path` with absolute coordinates + * + * @param {Array} path + * @return {Array} + */ + +function absolutize(path){ + var startX = 0 + var startY = 0 + var x = 0 + var y = 0 + + return path.map(function(seg){ + seg = seg.slice() + var type = seg[0] + var command = type.toUpperCase() + + // is relative + if (type != command) { + seg[0] = command + switch (type) { + case 'a': + seg[6] += x + seg[7] += y + break + case 'v': + seg[1] += y + break + case 'h': + seg[1] += x + break + default: + for (var i = 1; i < seg.length;) { + seg[i++] += x + seg[i++] += y + } + } + } + + // update cursor state + switch (command) { + case 'Z': + x = startX + y = startY + break + case 'H': + x = seg[1] + break + case 'V': + y = seg[1] + break + case 'M': + x = startX = seg[1] + y = startY = seg[2] + break + default: + x = seg[seg.length - 2] + y = seg[seg.length - 1] + } + + return seg + }) +} diff --git a/node_modules/abs-svg-path/package.json b/node_modules/abs-svg-path/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8616c7c6edb0dc7253d3f72476e5dc4b43122819 --- /dev/null +++ b/node_modules/abs-svg-path/package.json @@ -0,0 +1,19 @@ +{ + "name": "abs-svg-path", + "version": "0.1.1", + "description": "redefine an svg path with absolute coordinates", + "keywords": ["absolute","svg","path"], + "dependencies": {}, + "devDependencies": { + "serve": "jkroso/serve", + "parse-svg-path": "*", + "mocha": "*", + "chai": "*", + "jsmd": "*" + }, + "repository": "git://github.com/jkroso/abs-svg-path.git", + "bugs": "https://github.com/jkroso/abs-svg-path/issues", + "author": "Jake Rosoman", + "files": ["index.js"], + "license": "MIT" +} \ No newline at end of file diff --git a/node_modules/accepts/HISTORY.md b/node_modules/accepts/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..cb5990c7c3620f4936a3ac42b3bf335c95eef7e8 --- /dev/null +++ b/node_modules/accepts/HISTORY.md @@ -0,0 +1,243 @@ +1.3.8 / 2022-02-02 +================== + + * deps: mime-types@~2.1.34 + - deps: mime-db@~1.51.0 + * deps: negotiator@0.6.3 + +1.3.7 / 2019-04-29 +================== + + * deps: negotiator@0.6.2 + - Fix sorting charset, encoding, and language with extra parameters + +1.3.6 / 2019-04-28 +================== + + * deps: mime-types@~2.1.24 + - deps: mime-db@~1.40.0 + +1.3.5 / 2018-02-28 +================== + + * deps: mime-types@~2.1.18 + - deps: mime-db@~1.33.0 + +1.3.4 / 2017-08-22 +================== + + * deps: mime-types@~2.1.16 + - deps: mime-db@~1.29.0 + +1.3.3 / 2016-05-02 +================== + + * deps: mime-types@~2.1.11 + - deps: mime-db@~1.23.0 + * deps: negotiator@0.6.1 + - perf: improve `Accept` parsing speed + - perf: improve `Accept-Charset` parsing speed + - perf: improve `Accept-Encoding` parsing speed + - perf: improve `Accept-Language` parsing speed + +1.3.2 / 2016-03-08 +================== + + * deps: mime-types@~2.1.10 + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + - deps: mime-db@~1.22.0 + +1.3.1 / 2016-01-19 +================== + + * deps: mime-types@~2.1.9 + - deps: mime-db@~1.21.0 + +1.3.0 / 2015-09-29 +================== + + * deps: mime-types@~2.1.7 + - deps: mime-db@~1.19.0 + * deps: negotiator@0.6.0 + - Fix including type extensions in parameters in `Accept` parsing + - Fix parsing `Accept` parameters with quoted equals + - Fix parsing `Accept` parameters with quoted semicolons + - Lazy-load modules from main entry point + - perf: delay type concatenation until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove closures getting spec properties + - perf: remove a closure from media type parsing + - perf: remove property delete from media type parsing + +1.2.13 / 2015-09-06 +=================== + + * deps: mime-types@~2.1.6 + - deps: mime-db@~1.18.0 + +1.2.12 / 2015-07-30 +=================== + + * deps: mime-types@~2.1.4 + - deps: mime-db@~1.16.0 + +1.2.11 / 2015-07-16 +=================== + + * deps: mime-types@~2.1.3 + - deps: mime-db@~1.15.0 + +1.2.10 / 2015-07-01 +=================== + + * deps: mime-types@~2.1.2 + - deps: mime-db@~1.14.0 + +1.2.9 / 2015-06-08 +================== + + * deps: mime-types@~2.1.1 + - perf: fix deopt during mapping + +1.2.8 / 2015-06-07 +================== + + * deps: mime-types@~2.1.0 + - deps: mime-db@~1.13.0 + * perf: avoid argument reassignment & argument slice + * perf: avoid negotiator recursive construction + * perf: enable strict mode + * perf: remove unnecessary bitwise operator + +1.2.7 / 2015-05-10 +================== + + * deps: negotiator@0.5.3 + - Fix media type parameter matching to be case-insensitive + +1.2.6 / 2015-05-07 +================== + + * deps: mime-types@~2.0.11 + - deps: mime-db@~1.9.1 + * deps: negotiator@0.5.2 + - Fix comparing media types with quoted values + - Fix splitting media types with quoted commas + +1.2.5 / 2015-03-13 +================== + + * deps: mime-types@~2.0.10 + - deps: mime-db@~1.8.0 + +1.2.4 / 2015-02-14 +================== + + * Support Node.js 0.6 + * deps: mime-types@~2.0.9 + - deps: mime-db@~1.7.0 + * deps: negotiator@0.5.1 + - Fix preference sorting to be stable for long acceptable lists + +1.2.3 / 2015-01-31 +================== + + * deps: mime-types@~2.0.8 + - deps: mime-db@~1.6.0 + +1.2.2 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - deps: mime-db@~1.5.0 + +1.2.1 / 2014-12-30 +================== + + * deps: mime-types@~2.0.5 + - deps: mime-db@~1.3.1 + +1.2.0 / 2014-12-19 +================== + + * deps: negotiator@0.5.0 + - Fix list return order when large accepted list + - Fix missing identity encoding when q=0 exists + - Remove dynamic building of Negotiator class + +1.1.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - deps: mime-db@~1.3.0 + +1.1.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - deps: mime-db@~1.2.0 + +1.1.2 / 2014-10-14 +================== + + * deps: negotiator@0.4.9 + - Fix error when media type has invalid parameter + +1.1.1 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - deps: mime-db@~1.1.0 + * deps: negotiator@0.4.8 + - Fix all negotiations to be case-insensitive + - Stable sort preferences of same quality according to client order + +1.1.0 / 2014-09-02 +================== + + * update `mime-types` + +1.0.7 / 2014-07-04 +================== + + * Fix wrong type returned from `type` when match after unknown extension + +1.0.6 / 2014-06-24 +================== + + * deps: negotiator@0.4.7 + +1.0.5 / 2014-06-20 +================== + + * fix crash when unknown extension given + +1.0.4 / 2014-06-19 +================== + + * use `mime-types` + +1.0.3 / 2014-06-11 +================== + + * deps: negotiator@0.4.6 + - Order by specificity when quality is the same + +1.0.2 / 2014-05-29 +================== + + * Fix interpretation when header not in request + * deps: pin negotiator@0.4.5 + +1.0.1 / 2014-01-18 +================== + + * Identity encoding isn't always acceptable + * deps: negotiator@~0.4.0 + +1.0.0 / 2013-12-27 +================== + + * Genesis diff --git a/node_modules/accepts/LICENSE b/node_modules/accepts/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..06166077be4d1f620d89b9eb33c76d89e75857da --- /dev/null +++ b/node_modules/accepts/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/accepts/README.md b/node_modules/accepts/README.md new file mode 100644 index 0000000000000000000000000000000000000000..82680c530c3886540f630f643990e2ec707319d1 --- /dev/null +++ b/node_modules/accepts/README.md @@ -0,0 +1,140 @@ +# accepts + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator). +Extracted from [koa](https://www.npmjs.com/package/koa) for general use. + +In addition to negotiator, it allows: + +- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` + as well as `('text/html', 'application/json')`. +- Allows type shorthands such as `json`. +- Returns `false` when no types match +- Treats non-existent headers as `*` + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install accepts +``` + +## API + +```js +var accepts = require('accepts') +``` + +### accepts(req) + +Create a new `Accepts` object for the given `req`. + +#### .charset(charsets) + +Return the first accepted charset. If nothing in `charsets` is accepted, +then `false` is returned. + +#### .charsets() + +Return the charsets that the request accepts, in the order of the client's +preference (most preferred first). + +#### .encoding(encodings) + +Return the first accepted encoding. If nothing in `encodings` is accepted, +then `false` is returned. + +#### .encodings() + +Return the encodings that the request accepts, in the order of the client's +preference (most preferred first). + +#### .language(languages) + +Return the first accepted language. If nothing in `languages` is accepted, +then `false` is returned. + +#### .languages() + +Return the languages that the request accepts, in the order of the client's +preference (most preferred first). + +#### .type(types) + +Return the first accepted type (and it is returned as the same text as what +appears in the `types` array). If nothing in `types` is accepted, then `false` +is returned. + +The `types` array can contain full MIME types or file extensions. Any value +that is not a full MIME types is passed to `require('mime-types').lookup`. + +#### .types() + +Return the types that the request accepts, in the order of the client's +preference (most preferred first). + +## Examples + +### Simple type negotiation + +This simple example shows how to use `accepts` to return a different typed +respond body based on what the client wants to accept. The server lists it's +preferences in order and will get back the best match between the client and +server. + +```js +var accepts = require('accepts') +var http = require('http') + +function app (req, res) { + var accept = accepts(req) + + // the order of this list is significant; should be server preferred order + switch (accept.type(['json', 'html'])) { + case 'json': + res.setHeader('Content-Type', 'application/json') + res.write('{"hello":"world!"}') + break + case 'html': + res.setHeader('Content-Type', 'text/html') + res.write('hello, world!') + break + default: + // the fallback is text/plain, so no need to specify it above + res.setHeader('Content-Type', 'text/plain') + res.write('hello, world!') + break + } + + res.end() +} + +http.createServer(app).listen(3000) +``` + +You can test this out with the cURL program: +```sh +curl -I -H'Accept: text/html' http://localhost:3000/ +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master +[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master +[github-actions-ci-image]: https://badgen.net/github/checks/jshttp/accepts/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/accepts/actions/workflows/ci.yml +[node-version-image]: https://badgen.net/npm/node/accepts +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/accepts +[npm-url]: https://npmjs.org/package/accepts +[npm-version-image]: https://badgen.net/npm/v/accepts diff --git a/node_modules/accepts/index.js b/node_modules/accepts/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e9b2f63fb16f8ecdeb16c8eced302612794ccf65 --- /dev/null +++ b/node_modules/accepts/index.js @@ -0,0 +1,238 @@ +/*! + * accepts + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var Negotiator = require('negotiator') +var mime = require('mime-types') + +/** + * Module exports. + * @public + */ + +module.exports = Accepts + +/** + * Create a new Accepts object for the given req. + * + * @param {object} req + * @public + */ + +function Accepts (req) { + if (!(this instanceof Accepts)) { + return new Accepts(req) + } + + this.headers = req.headers + this.negotiator = new Negotiator(req) +} + +/** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.types('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.types('html'); + * // => "html" + * this.types('text/html'); + * // => "text/html" + * this.types('json', 'text'); + * // => "json" + * this.types('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.types('image/png'); + * this.types('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.types(['html', 'json']); + * this.types('html', 'json'); + * // => "json" + * + * @param {String|Array} types... + * @return {String|Array|Boolean} + * @public + */ + +Accepts.prototype.type = +Accepts.prototype.types = function (types_) { + var types = types_ + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i] + } + } + + // no types, return all requested types + if (!types || types.length === 0) { + return this.negotiator.mediaTypes() + } + + // no accept header, return first given type + if (!this.headers.accept) { + return types[0] + } + + var mimes = types.map(extToMime) + var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) + var first = accepts[0] + + return first + ? types[mimes.indexOf(first)] + : false +} + +/** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encodings... + * @return {String|Array} + * @public + */ + +Accepts.prototype.encoding = +Accepts.prototype.encodings = function (encodings_) { + var encodings = encodings_ + + // support flattened arguments + if (encodings && !Array.isArray(encodings)) { + encodings = new Array(arguments.length) + for (var i = 0; i < encodings.length; i++) { + encodings[i] = arguments[i] + } + } + + // no encodings, return all requested encodings + if (!encodings || encodings.length === 0) { + return this.negotiator.encodings() + } + + return this.negotiator.encodings(encodings)[0] || false +} + +/** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charsets... + * @return {String|Array} + * @public + */ + +Accepts.prototype.charset = +Accepts.prototype.charsets = function (charsets_) { + var charsets = charsets_ + + // support flattened arguments + if (charsets && !Array.isArray(charsets)) { + charsets = new Array(arguments.length) + for (var i = 0; i < charsets.length; i++) { + charsets[i] = arguments[i] + } + } + + // no charsets, return all requested charsets + if (!charsets || charsets.length === 0) { + return this.negotiator.charsets() + } + + return this.negotiator.charsets(charsets)[0] || false +} + +/** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} langs... + * @return {Array|String} + * @public + */ + +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +Accepts.prototype.languages = function (languages_) { + var languages = languages_ + + // support flattened arguments + if (languages && !Array.isArray(languages)) { + languages = new Array(arguments.length) + for (var i = 0; i < languages.length; i++) { + languages[i] = arguments[i] + } + } + + // no languages, return all requested languages + if (!languages || languages.length === 0) { + return this.negotiator.languages() + } + + return this.negotiator.languages(languages)[0] || false +} + +/** + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @private + */ + +function extToMime (type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if mime is valid. + * + * @param {String} type + * @return {String} + * @private + */ + +function validMime (type) { + return typeof type === 'string' +} diff --git a/node_modules/accepts/package.json b/node_modules/accepts/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0f2d15da92b29d328f4da484f494c5442c711b4d --- /dev/null +++ b/node_modules/accepts/package.json @@ -0,0 +1,47 @@ +{ + "name": "accepts", + "description": "Higher-level content negotiation", + "version": "1.3.8", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/accepts", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + }, + "keywords": [ + "content", + "negotiation", + "accept", + "accepts" + ] +} diff --git a/node_modules/acorn-jsx/LICENSE b/node_modules/acorn-jsx/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..695d4b93082bee2494e7a1519c3b6b88b33a1568 --- /dev/null +++ b/node_modules/acorn-jsx/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2012-2017 by Ingvar Stepanyan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/acorn-jsx/README.md b/node_modules/acorn-jsx/README.md new file mode 100644 index 0000000000000000000000000000000000000000..317c3ac4a5534ecda2c0087e7de1fa883b9ccc8f --- /dev/null +++ b/node_modules/acorn-jsx/README.md @@ -0,0 +1,40 @@ +# Acorn-JSX + +[![Build Status](https://travis-ci.org/acornjs/acorn-jsx.svg?branch=master)](https://travis-ci.org/acornjs/acorn-jsx) +[![NPM version](https://img.shields.io/npm/v/acorn-jsx.svg)](https://www.npmjs.org/package/acorn-jsx) + +This is plugin for [Acorn](http://marijnhaverbeke.nl/acorn/) - a tiny, fast JavaScript parser, written completely in JavaScript. + +It was created as an experimental alternative, faster [React.js JSX](http://facebook.github.io/react/docs/jsx-in-depth.html) parser. Later, it replaced the [official parser](https://github.com/facebookarchive/esprima) and these days is used by many prominent development tools. + +## Transpiler + +Please note that this tool only parses source code to JSX AST, which is useful for various language tools and services. If you want to transpile your code to regular ES5-compliant JavaScript with source map, check out [Babel](https://babeljs.io/) and [Buble](https://buble.surge.sh/) transpilers which use `acorn-jsx` under the hood. + +## Usage + +Requiring this module provides you with an Acorn plugin that you can use like this: + +```javascript +var acorn = require("acorn"); +var jsx = require("acorn-jsx"); +acorn.Parser.extend(jsx()).parse("my(, 'code');"); +``` + +Note that official spec doesn't support mix of XML namespaces and object-style access in tag names (#27) like in ``, so it was deprecated in `acorn-jsx@3.0`. If you still want to opt-in to support of such constructions, you can pass the following option: + +```javascript +acorn.Parser.extend(jsx({ allowNamespacedObjects: true })) +``` + +Also, since most apps use pure React transformer, a new option was introduced that allows to prohibit namespaces completely: + +```javascript +acorn.Parser.extend(jsx({ allowNamespaces: false })) +``` + +Note that by default `allowNamespaces` is enabled for spec compliancy. + +## License + +This plugin is issued under the [MIT license](./LICENSE). diff --git a/node_modules/acorn-jsx/index.d.ts b/node_modules/acorn-jsx/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f37b1df4c77c500b68aafa876072448758046f69 --- /dev/null +++ b/node_modules/acorn-jsx/index.d.ts @@ -0,0 +1,12 @@ +import { Parser } from 'acorn' + +declare const jsx: (options?: jsx.Options) => (BaseParser: typeof Parser) => typeof Parser; + +declare namespace jsx { + interface Options { + allowNamespacedObjects?: boolean; + allowNamespaces?: boolean; + } +} + +export = jsx; diff --git a/node_modules/acorn-jsx/index.js b/node_modules/acorn-jsx/index.js new file mode 100644 index 0000000000000000000000000000000000000000..004e0809024006335916314d605090629b73575f --- /dev/null +++ b/node_modules/acorn-jsx/index.js @@ -0,0 +1,488 @@ +'use strict'; + +const XHTMLEntities = require('./xhtml'); + +const hexNumber = /^[\da-fA-F]+$/; +const decimalNumber = /^\d+$/; + +// The map to `acorn-jsx` tokens from `acorn` namespace objects. +const acornJsxMap = new WeakMap(); + +// Get the original tokens for the given `acorn` namespace object. +function getJsxTokens(acorn) { + acorn = acorn.Parser.acorn || acorn; + let acornJsx = acornJsxMap.get(acorn); + if (!acornJsx) { + const tt = acorn.tokTypes; + const TokContext = acorn.TokContext; + const TokenType = acorn.TokenType; + const tc_oTag = new TokContext('...', true, true); + const tokContexts = { + tc_oTag: tc_oTag, + tc_cTag: tc_cTag, + tc_expr: tc_expr + }; + const tokTypes = { + jsxName: new TokenType('jsxName'), + jsxText: new TokenType('jsxText', {beforeExpr: true}), + jsxTagStart: new TokenType('jsxTagStart', {startsExpr: true}), + jsxTagEnd: new TokenType('jsxTagEnd') + }; + + tokTypes.jsxTagStart.updateContext = function() { + this.context.push(tc_expr); // treat as beginning of JSX expression + this.context.push(tc_oTag); // start opening tag context + this.exprAllowed = false; + }; + tokTypes.jsxTagEnd.updateContext = function(prevType) { + let out = this.context.pop(); + if (out === tc_oTag && prevType === tt.slash || out === tc_cTag) { + this.context.pop(); + this.exprAllowed = this.curContext() === tc_expr; + } else { + this.exprAllowed = true; + } + }; + + acornJsx = { tokContexts: tokContexts, tokTypes: tokTypes }; + acornJsxMap.set(acorn, acornJsx); + } + + return acornJsx; +} + +// Transforms JSX element name to string. + +function getQualifiedJSXName(object) { + if (!object) + return object; + + if (object.type === 'JSXIdentifier') + return object.name; + + if (object.type === 'JSXNamespacedName') + return object.namespace.name + ':' + object.name.name; + + if (object.type === 'JSXMemberExpression') + return getQualifiedJSXName(object.object) + '.' + + getQualifiedJSXName(object.property); +} + +module.exports = function(options) { + options = options || {}; + return function(Parser) { + return plugin({ + allowNamespaces: options.allowNamespaces !== false, + allowNamespacedObjects: !!options.allowNamespacedObjects + }, Parser); + }; +}; + +// This is `tokTypes` of the peer dep. +// This can be different instances from the actual `tokTypes` this plugin uses. +Object.defineProperty(module.exports, "tokTypes", { + get: function get_tokTypes() { + return getJsxTokens(require("acorn")).tokTypes; + }, + configurable: true, + enumerable: true +}); + +function plugin(options, Parser) { + const acorn = Parser.acorn || require("acorn"); + const acornJsx = getJsxTokens(acorn); + const tt = acorn.tokTypes; + const tok = acornJsx.tokTypes; + const tokContexts = acorn.tokContexts; + const tc_oTag = acornJsx.tokContexts.tc_oTag; + const tc_cTag = acornJsx.tokContexts.tc_cTag; + const tc_expr = acornJsx.tokContexts.tc_expr; + const isNewLine = acorn.isNewLine; + const isIdentifierStart = acorn.isIdentifierStart; + const isIdentifierChar = acorn.isIdentifierChar; + + return class extends Parser { + // Expose actual `tokTypes` and `tokContexts` to other plugins. + static get acornJsx() { + return acornJsx; + } + + // Reads inline JSX contents token. + jsx_readToken() { + let out = '', chunkStart = this.pos; + for (;;) { + if (this.pos >= this.input.length) + this.raise(this.start, 'Unterminated JSX contents'); + let ch = this.input.charCodeAt(this.pos); + + switch (ch) { + case 60: // '<' + case 123: // '{' + if (this.pos === this.start) { + if (ch === 60 && this.exprAllowed) { + ++this.pos; + return this.finishToken(tok.jsxTagStart); + } + return this.getTokenFromCode(ch); + } + out += this.input.slice(chunkStart, this.pos); + return this.finishToken(tok.jsxText, out); + + case 38: // '&' + out += this.input.slice(chunkStart, this.pos); + out += this.jsx_readEntity(); + chunkStart = this.pos; + break; + + case 62: // '>' + case 125: // '}' + this.raise( + this.pos, + "Unexpected token `" + this.input[this.pos] + "`. Did you mean `" + + (ch === 62 ? ">" : "}") + "` or " + "`{\"" + this.input[this.pos] + "\"}" + "`?" + ); + + default: + if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.pos); + out += this.jsx_readNewLine(true); + chunkStart = this.pos; + } else { + ++this.pos; + } + } + } + } + + jsx_readNewLine(normalizeCRLF) { + let ch = this.input.charCodeAt(this.pos); + let out; + ++this.pos; + if (ch === 13 && this.input.charCodeAt(this.pos) === 10) { + ++this.pos; + out = normalizeCRLF ? '\n' : '\r\n'; + } else { + out = String.fromCharCode(ch); + } + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + + return out; + } + + jsx_readString(quote) { + let out = '', chunkStart = ++this.pos; + for (;;) { + if (this.pos >= this.input.length) + this.raise(this.start, 'Unterminated string constant'); + let ch = this.input.charCodeAt(this.pos); + if (ch === quote) break; + if (ch === 38) { // '&' + out += this.input.slice(chunkStart, this.pos); + out += this.jsx_readEntity(); + chunkStart = this.pos; + } else if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.pos); + out += this.jsx_readNewLine(false); + chunkStart = this.pos; + } else { + ++this.pos; + } + } + out += this.input.slice(chunkStart, this.pos++); + return this.finishToken(tt.string, out); + } + + jsx_readEntity() { + let str = '', count = 0, entity; + let ch = this.input[this.pos]; + if (ch !== '&') + this.raise(this.pos, 'Entity must start with an ampersand'); + let startPos = ++this.pos; + while (this.pos < this.input.length && count++ < 10) { + ch = this.input[this.pos++]; + if (ch === ';') { + if (str[0] === '#') { + if (str[1] === 'x') { + str = str.substr(2); + if (hexNumber.test(str)) + entity = String.fromCharCode(parseInt(str, 16)); + } else { + str = str.substr(1); + if (decimalNumber.test(str)) + entity = String.fromCharCode(parseInt(str, 10)); + } + } else { + entity = XHTMLEntities[str]; + } + break; + } + str += ch; + } + if (!entity) { + this.pos = startPos; + return '&'; + } + return entity; + } + + // Read a JSX identifier (valid tag or attribute name). + // + // Optimized version since JSX identifiers can't contain + // escape characters and so can be read as single slice. + // Also assumes that first character was already checked + // by isIdentifierStart in readToken. + + jsx_readWord() { + let ch, start = this.pos; + do { + ch = this.input.charCodeAt(++this.pos); + } while (isIdentifierChar(ch) || ch === 45); // '-' + return this.finishToken(tok.jsxName, this.input.slice(start, this.pos)); + } + + // Parse next token as JSX identifier + + jsx_parseIdentifier() { + let node = this.startNode(); + if (this.type === tok.jsxName) + node.name = this.value; + else if (this.type.keyword) + node.name = this.type.keyword; + else + this.unexpected(); + this.next(); + return this.finishNode(node, 'JSXIdentifier'); + } + + // Parse namespaced identifier. + + jsx_parseNamespacedName() { + let startPos = this.start, startLoc = this.startLoc; + let name = this.jsx_parseIdentifier(); + if (!options.allowNamespaces || !this.eat(tt.colon)) return name; + var node = this.startNodeAt(startPos, startLoc); + node.namespace = name; + node.name = this.jsx_parseIdentifier(); + return this.finishNode(node, 'JSXNamespacedName'); + } + + // Parses element name in any form - namespaced, member + // or single identifier. + + jsx_parseElementName() { + if (this.type === tok.jsxTagEnd) return ''; + let startPos = this.start, startLoc = this.startLoc; + let node = this.jsx_parseNamespacedName(); + if (this.type === tt.dot && node.type === 'JSXNamespacedName' && !options.allowNamespacedObjects) { + this.unexpected(); + } + while (this.eat(tt.dot)) { + let newNode = this.startNodeAt(startPos, startLoc); + newNode.object = node; + newNode.property = this.jsx_parseIdentifier(); + node = this.finishNode(newNode, 'JSXMemberExpression'); + } + return node; + } + + // Parses any type of JSX attribute value. + + jsx_parseAttributeValue() { + switch (this.type) { + case tt.braceL: + let node = this.jsx_parseExpressionContainer(); + if (node.expression.type === 'JSXEmptyExpression') + this.raise(node.start, 'JSX attributes must only be assigned a non-empty expression'); + return node; + + case tok.jsxTagStart: + case tt.string: + return this.parseExprAtom(); + + default: + this.raise(this.start, 'JSX value should be either an expression or a quoted JSX text'); + } + } + + // JSXEmptyExpression is unique type since it doesn't actually parse anything, + // and so it should start at the end of last read token (left brace) and finish + // at the beginning of the next one (right brace). + + jsx_parseEmptyExpression() { + let node = this.startNodeAt(this.lastTokEnd, this.lastTokEndLoc); + return this.finishNodeAt(node, 'JSXEmptyExpression', this.start, this.startLoc); + } + + // Parses JSX expression enclosed into curly brackets. + + jsx_parseExpressionContainer() { + let node = this.startNode(); + this.next(); + node.expression = this.type === tt.braceR + ? this.jsx_parseEmptyExpression() + : this.parseExpression(); + this.expect(tt.braceR); + return this.finishNode(node, 'JSXExpressionContainer'); + } + + // Parses following JSX attribute name-value pair. + + jsx_parseAttribute() { + let node = this.startNode(); + if (this.eat(tt.braceL)) { + this.expect(tt.ellipsis); + node.argument = this.parseMaybeAssign(); + this.expect(tt.braceR); + return this.finishNode(node, 'JSXSpreadAttribute'); + } + node.name = this.jsx_parseNamespacedName(); + node.value = this.eat(tt.eq) ? this.jsx_parseAttributeValue() : null; + return this.finishNode(node, 'JSXAttribute'); + } + + // Parses JSX opening tag starting after '<'. + + jsx_parseOpeningElementAt(startPos, startLoc) { + let node = this.startNodeAt(startPos, startLoc); + node.attributes = []; + let nodeName = this.jsx_parseElementName(); + if (nodeName) node.name = nodeName; + while (this.type !== tt.slash && this.type !== tok.jsxTagEnd) + node.attributes.push(this.jsx_parseAttribute()); + node.selfClosing = this.eat(tt.slash); + this.expect(tok.jsxTagEnd); + return this.finishNode(node, nodeName ? 'JSXOpeningElement' : 'JSXOpeningFragment'); + } + + // Parses JSX closing tag starting after ''); + } + } + let fragmentOrElement = openingElement.name ? 'Element' : 'Fragment'; + + node['opening' + fragmentOrElement] = openingElement; + node['closing' + fragmentOrElement] = closingElement; + node.children = children; + if (this.type === tt.relational && this.value === "<") { + this.raise(this.start, "Adjacent JSX elements must be wrapped in an enclosing tag"); + } + return this.finishNode(node, 'JSX' + fragmentOrElement); + } + + // Parse JSX text + + jsx_parseText() { + let node = this.parseLiteral(this.value); + node.type = "JSXText"; + return node; + } + + // Parses entire JSX element from current position. + + jsx_parseElement() { + let startPos = this.start, startLoc = this.startLoc; + this.next(); + return this.jsx_parseElementAt(startPos, startLoc); + } + + parseExprAtom(refShortHandDefaultPos) { + if (this.type === tok.jsxText) + return this.jsx_parseText(); + else if (this.type === tok.jsxTagStart) + return this.jsx_parseElement(); + else + return super.parseExprAtom(refShortHandDefaultPos); + } + + readToken(code) { + let context = this.curContext(); + + if (context === tc_expr) return this.jsx_readToken(); + + if (context === tc_oTag || context === tc_cTag) { + if (isIdentifierStart(code)) return this.jsx_readWord(); + + if (code == 62) { + ++this.pos; + return this.finishToken(tok.jsxTagEnd); + } + + if ((code === 34 || code === 39) && context == tc_oTag) + return this.jsx_readString(code); + } + + if (code === 60 && this.exprAllowed && this.input.charCodeAt(this.pos + 1) !== 33) { + ++this.pos; + return this.finishToken(tok.jsxTagStart); + } + return super.readToken(code); + } + + updateContext(prevType) { + if (this.type == tt.braceL) { + var curContext = this.curContext(); + if (curContext == tc_oTag) this.context.push(tokContexts.b_expr); + else if (curContext == tc_expr) this.context.push(tokContexts.b_tmpl); + else super.updateContext(prevType); + this.exprAllowed = true; + } else if (this.type === tt.slash && prevType === tok.jsxTagStart) { + this.context.length -= 2; // do not consider JSX expr -> JSX open tag -> ... anymore + this.context.push(tc_cTag); // reconsider as closing tag context + this.exprAllowed = false; + } else { + return super.updateContext(prevType); + } + } + }; +} diff --git a/node_modules/acorn-jsx/package.json b/node_modules/acorn-jsx/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6debde9caa30ba90f7c4ad48c3fd1b070cd7095b --- /dev/null +++ b/node_modules/acorn-jsx/package.json @@ -0,0 +1,27 @@ +{ + "name": "acorn-jsx", + "description": "Modern, fast React.js JSX parser", + "homepage": "https://github.com/acornjs/acorn-jsx", + "version": "5.3.2", + "maintainers": [ + { + "name": "Ingvar Stepanyan", + "email": "me@rreverser.com", + "web": "http://rreverser.com/" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/acornjs/acorn-jsx" + }, + "license": "MIT", + "scripts": { + "test": "node test/run.js" + }, + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "devDependencies": { + "acorn": "^8.0.1" + } +} diff --git a/node_modules/acorn-jsx/xhtml.js b/node_modules/acorn-jsx/xhtml.js new file mode 100644 index 0000000000000000000000000000000000000000..c1520092f8e31ed589d21605ede2ebd27386b218 --- /dev/null +++ b/node_modules/acorn-jsx/xhtml.js @@ -0,0 +1,255 @@ +module.exports = { + quot: '\u0022', + amp: '&', + apos: '\u0027', + lt: '<', + gt: '>', + nbsp: '\u00A0', + iexcl: '\u00A1', + cent: '\u00A2', + pound: '\u00A3', + curren: '\u00A4', + yen: '\u00A5', + brvbar: '\u00A6', + sect: '\u00A7', + uml: '\u00A8', + copy: '\u00A9', + ordf: '\u00AA', + laquo: '\u00AB', + not: '\u00AC', + shy: '\u00AD', + reg: '\u00AE', + macr: '\u00AF', + deg: '\u00B0', + plusmn: '\u00B1', + sup2: '\u00B2', + sup3: '\u00B3', + acute: '\u00B4', + micro: '\u00B5', + para: '\u00B6', + middot: '\u00B7', + cedil: '\u00B8', + sup1: '\u00B9', + ordm: '\u00BA', + raquo: '\u00BB', + frac14: '\u00BC', + frac12: '\u00BD', + frac34: '\u00BE', + iquest: '\u00BF', + Agrave: '\u00C0', + Aacute: '\u00C1', + Acirc: '\u00C2', + Atilde: '\u00C3', + Auml: '\u00C4', + Aring: '\u00C5', + AElig: '\u00C6', + Ccedil: '\u00C7', + Egrave: '\u00C8', + Eacute: '\u00C9', + Ecirc: '\u00CA', + Euml: '\u00CB', + Igrave: '\u00CC', + Iacute: '\u00CD', + Icirc: '\u00CE', + Iuml: '\u00CF', + ETH: '\u00D0', + Ntilde: '\u00D1', + Ograve: '\u00D2', + Oacute: '\u00D3', + Ocirc: '\u00D4', + Otilde: '\u00D5', + Ouml: '\u00D6', + times: '\u00D7', + Oslash: '\u00D8', + Ugrave: '\u00D9', + Uacute: '\u00DA', + Ucirc: '\u00DB', + Uuml: '\u00DC', + Yacute: '\u00DD', + THORN: '\u00DE', + szlig: '\u00DF', + agrave: '\u00E0', + aacute: '\u00E1', + acirc: '\u00E2', + atilde: '\u00E3', + auml: '\u00E4', + aring: '\u00E5', + aelig: '\u00E6', + ccedil: '\u00E7', + egrave: '\u00E8', + eacute: '\u00E9', + ecirc: '\u00EA', + euml: '\u00EB', + igrave: '\u00EC', + iacute: '\u00ED', + icirc: '\u00EE', + iuml: '\u00EF', + eth: '\u00F0', + ntilde: '\u00F1', + ograve: '\u00F2', + oacute: '\u00F3', + ocirc: '\u00F4', + otilde: '\u00F5', + ouml: '\u00F6', + divide: '\u00F7', + oslash: '\u00F8', + ugrave: '\u00F9', + uacute: '\u00FA', + ucirc: '\u00FB', + uuml: '\u00FC', + yacute: '\u00FD', + thorn: '\u00FE', + yuml: '\u00FF', + OElig: '\u0152', + oelig: '\u0153', + Scaron: '\u0160', + scaron: '\u0161', + Yuml: '\u0178', + fnof: '\u0192', + circ: '\u02C6', + tilde: '\u02DC', + Alpha: '\u0391', + Beta: '\u0392', + Gamma: '\u0393', + Delta: '\u0394', + Epsilon: '\u0395', + Zeta: '\u0396', + Eta: '\u0397', + Theta: '\u0398', + Iota: '\u0399', + Kappa: '\u039A', + Lambda: '\u039B', + Mu: '\u039C', + Nu: '\u039D', + Xi: '\u039E', + Omicron: '\u039F', + Pi: '\u03A0', + Rho: '\u03A1', + Sigma: '\u03A3', + Tau: '\u03A4', + Upsilon: '\u03A5', + Phi: '\u03A6', + Chi: '\u03A7', + Psi: '\u03A8', + Omega: '\u03A9', + alpha: '\u03B1', + beta: '\u03B2', + gamma: '\u03B3', + delta: '\u03B4', + epsilon: '\u03B5', + zeta: '\u03B6', + eta: '\u03B7', + theta: '\u03B8', + iota: '\u03B9', + kappa: '\u03BA', + lambda: '\u03BB', + mu: '\u03BC', + nu: '\u03BD', + xi: '\u03BE', + omicron: '\u03BF', + pi: '\u03C0', + rho: '\u03C1', + sigmaf: '\u03C2', + sigma: '\u03C3', + tau: '\u03C4', + upsilon: '\u03C5', + phi: '\u03C6', + chi: '\u03C7', + psi: '\u03C8', + omega: '\u03C9', + thetasym: '\u03D1', + upsih: '\u03D2', + piv: '\u03D6', + ensp: '\u2002', + emsp: '\u2003', + thinsp: '\u2009', + zwnj: '\u200C', + zwj: '\u200D', + lrm: '\u200E', + rlm: '\u200F', + ndash: '\u2013', + mdash: '\u2014', + lsquo: '\u2018', + rsquo: '\u2019', + sbquo: '\u201A', + ldquo: '\u201C', + rdquo: '\u201D', + bdquo: '\u201E', + dagger: '\u2020', + Dagger: '\u2021', + bull: '\u2022', + hellip: '\u2026', + permil: '\u2030', + prime: '\u2032', + Prime: '\u2033', + lsaquo: '\u2039', + rsaquo: '\u203A', + oline: '\u203E', + frasl: '\u2044', + euro: '\u20AC', + image: '\u2111', + weierp: '\u2118', + real: '\u211C', + trade: '\u2122', + alefsym: '\u2135', + larr: '\u2190', + uarr: '\u2191', + rarr: '\u2192', + darr: '\u2193', + harr: '\u2194', + crarr: '\u21B5', + lArr: '\u21D0', + uArr: '\u21D1', + rArr: '\u21D2', + dArr: '\u21D3', + hArr: '\u21D4', + forall: '\u2200', + part: '\u2202', + exist: '\u2203', + empty: '\u2205', + nabla: '\u2207', + isin: '\u2208', + notin: '\u2209', + ni: '\u220B', + prod: '\u220F', + sum: '\u2211', + minus: '\u2212', + lowast: '\u2217', + radic: '\u221A', + prop: '\u221D', + infin: '\u221E', + ang: '\u2220', + and: '\u2227', + or: '\u2228', + cap: '\u2229', + cup: '\u222A', + 'int': '\u222B', + there4: '\u2234', + sim: '\u223C', + cong: '\u2245', + asymp: '\u2248', + ne: '\u2260', + equiv: '\u2261', + le: '\u2264', + ge: '\u2265', + sub: '\u2282', + sup: '\u2283', + nsub: '\u2284', + sube: '\u2286', + supe: '\u2287', + oplus: '\u2295', + otimes: '\u2297', + perp: '\u22A5', + sdot: '\u22C5', + lceil: '\u2308', + rceil: '\u2309', + lfloor: '\u230A', + rfloor: '\u230B', + lang: '\u2329', + rang: '\u232A', + loz: '\u25CA', + spades: '\u2660', + clubs: '\u2663', + hearts: '\u2665', + diams: '\u2666' +}; diff --git a/node_modules/acorn/CHANGELOG.md b/node_modules/acorn/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..6efbc332df56bb278c83ceefd7f59b6234ca282e --- /dev/null +++ b/node_modules/acorn/CHANGELOG.md @@ -0,0 +1,986 @@ +## 8.17.0 (2026-06-11) + +### New features + +The new `strict` option can be used to start script sources in strict mode. + +### Bug fixes + +Fix a number of corner case bugs when `using` or `await using` appear in `for` loop specs. + +Disallow `new super()` expressions. + +Don't allow the conditional in a ternary expression to be a (naked) arrow function. + +## 8.16.0 (2026-02-19) + +### New features + +The `sourceType` option can now be set to `"commonjs"` to have the parser treat the top level scope as a function scope. + +Add support for Unicode 17. + +### Bug fixes + +Don't recognize `await using` as contextual keywords when followed directly by a backslash. + +Fix an issue where the parser would allow `return` statements in `static` blocks when `allowReturnOutsideFunction` was enabled. + +Properly reject `using` declarations that appear directly in `switch` or `for` head scopes. + +Fix some corner case issues in the recognition of `using` syntax. + +## 8.15.0 (2025-06-08) + +### New features + +Support `using` and `await using` syntax. + +The `AnyNode` type is now defined in such a way that plugins can extend it. + +### Bug fixes + +Fix an issue where the `bigint` property of literal nodes for non-decimal bigints had the wrong format. + +The `acorn` CLI tool no longer crashes when emitting a tree that contains a bigint. + +## 8.14.1 (2025-03-05) + +### Bug fixes + +Fix an issue where `await` expressions in class field initializers were inappropriately allowed. + +Properly allow await inside an async arrow function inside a class field initializer. + +Mention the source file name in syntax error messages when given. + +Properly add an empty `attributes` property to every form of `ExportNamedDeclaration`. + +## 8.14.0 (2024-10-27) + +### New features + +Support ES2025 import attributes. + +Support ES2025 RegExp modifiers. + +### Bug fixes + +Support some missing Unicode properties. + +## 8.13.0 (2024-10-16) + +### New features + +Upgrade to Unicode 16.0. + +## 8.12.1 (2024-07-03) + +### Bug fixes + +Fix a regression that caused Acorn to no longer run on Node versions <8.10. + +## 8.12.0 (2024-06-14) + +### New features + +Support ES2025 duplicate capture group names in regular expressions. + +### Bug fixes + +Include `VariableDeclarator` in the `AnyNode` type so that walker objects can refer to it without getting a type error. + +Properly raise a parse error for invalid `for`/`of` statements using `async` as binding name. + +Properly recognize \"use strict\" when preceded by a string with an escaped newline. + +Mark the `Parser` constructor as protected, not private, so plugins can extend it without type errors. + +Fix a bug where some invalid `delete` expressions were let through when the operand was parenthesized and `preserveParens` was enabled. + +Properly normalize line endings in raw strings of invalid template tokens. + +Properly track line numbers for escaped newlines in strings. + +Fix a bug that broke line number accounting after a template literal with invalid escape sequences. + +## 8.11.3 (2023-12-29) + +### Bug fixes + +Add `Function` and `Class` to the `AggregateType` type, so that they can be used in walkers without raising a type error. + +Make sure `onToken` get an `import` keyword token when parsing `import.meta`. + +Fix a bug where `.loc.start` could be undefined for `new.target` `meta` nodes. + +## 8.11.2 (2023-10-27) + +### Bug fixes + +Fix a bug that caused regular expressions after colon tokens to not be properly tokenized in some circumstances. + +## 8.11.1 (2023-10-26) + +### Bug fixes + +Fix a regression where `onToken` would receive 'name' tokens for 'new' keyword tokens. + +## 8.11.0 (2023-10-26) + +### Bug fixes + +Fix an issue where tokenizing (without parsing) an object literal with a property named `class` or `function` could, in some circumstance, put the tokenizer into an invalid state. + +Fix an issue where a slash after a call to a propery named the same as some keywords would be tokenized as a regular expression. + +### New features + +Upgrade to Unicode 15.1. + +Use a set of new, much more precise, TypeScript types. + +## 8.10.0 (2023-07-05) + +### New features + +Add a `checkPrivateFields` option that disables strict checking of private property use. + +## 8.9.0 (2023-06-16) + +### Bug fixes + +Forbid dynamic import after `new`, even when part of a member expression. + +### New features + +Add Unicode properties for ES2023. + +Add support for the `v` flag to regular expressions. + +## 8.8.2 (2023-01-23) + +### Bug fixes + +Fix a bug that caused `allowHashBang` to be set to false when not provided, even with `ecmaVersion >= 14`. + +Fix an exception when passing no option object to `parse` or `new Parser`. + +Fix incorrect parse error on `if (0) let\n[astral identifier char]`. + +## 8.8.1 (2022-10-24) + +### Bug fixes + +Make type for `Comment` compatible with estree types. + +## 8.8.0 (2022-07-21) + +### Bug fixes + +Allow parentheses around spread args in destructuring object assignment. + +Fix an issue where the tree contained `directive` properties in when parsing with a language version that doesn't support them. + +### New features + +Support hashbang comments by default in ECMAScript 2023 and later. + +## 8.7.1 (2021-04-26) + +### Bug fixes + +Stop handling `"use strict"` directives in ECMAScript versions before 5. + +Fix an issue where duplicate quoted export names in `export *` syntax were incorrectly checked. + +Add missing type for `tokTypes`. + +## 8.7.0 (2021-12-27) + +### New features + +Support quoted export names. + +Upgrade to Unicode 14. + +Add support for Unicode 13 properties in regular expressions. + +### Bug fixes + +Use a loop to find line breaks, because the existing regexp search would overrun the end of the searched range and waste a lot of time in minified code. + +## 8.6.0 (2021-11-18) + +### Bug fixes + +Fix a bug where an object literal with multiple `__proto__` properties would incorrectly be accepted if a later property value held an assigment. + +### New features + +Support class private fields with the `in` operator. + +## 8.5.0 (2021-09-06) + +### Bug fixes + +Improve context-dependent tokenization in a number of corner cases. + +Fix location tracking after a 0x2028 or 0x2029 character in a string literal (which before did not increase the line number). + +Fix an issue where arrow function bodies in for loop context would inappropriately consume `in` operators. + +Fix wrong end locations stored on SequenceExpression nodes. + +Implement restriction that `for`/`of` loop LHS can't start with `let`. + +### New features + +Add support for ES2022 class static blocks. + +Allow multiple input files to be passed to the CLI tool. + +## 8.4.1 (2021-06-24) + +### Bug fixes + +Fix a bug where `allowAwaitOutsideFunction` would allow `await` in class field initializers, and setting `ecmaVersion` to 13 or higher would allow top-level await in non-module sources. + +## 8.4.0 (2021-06-11) + +### New features + +A new option, `allowSuperOutsideMethod`, can be used to suppress the error when `super` is used in the wrong context. + +## 8.3.0 (2021-05-31) + +### New features + +Default `allowAwaitOutsideFunction` to true for ECMAScript 2022 an higher. + +Add support for the `d` ([indices](https://github.com/tc39/proposal-regexp-match-indices)) regexp flag. + +## 8.2.4 (2021-05-04) + +### Bug fixes + +Fix spec conformity in corner case 'for await (async of ...)'. + +## 8.2.3 (2021-05-04) + +### Bug fixes + +Fix an issue where the library couldn't parse 'for (async of ...)'. + +Fix a bug in UTF-16 decoding that would read characters incorrectly in some circumstances. + +## 8.2.2 (2021-04-29) + +### Bug fixes + +Fix a bug where a class field initialized to an async arrow function wouldn't allow await inside it. Same issue existed for generator arrow functions with yield. + +## 8.2.1 (2021-04-24) + +### Bug fixes + +Fix a regression introduced in 8.2.0 where static or async class methods with keyword names fail to parse. + +## 8.2.0 (2021-04-24) + +### New features + +Add support for ES2022 class fields and private methods. + +## 8.1.1 (2021-04-12) + +### Various + +Stop shipping source maps in the NPM package. + +## 8.1.0 (2021-03-09) + +### Bug fixes + +Fix a spurious error in nested destructuring arrays. + +### New features + +Expose `allowAwaitOutsideFunction` in CLI interface. + +Make `allowImportExportAnywhere` also apply to `import.meta`. + +## 8.0.5 (2021-01-25) + +### Bug fixes + +Adjust package.json to work with Node 12.16.0 and 13.0-13.6. + +## 8.0.4 (2020-10-05) + +### Bug fixes + +Make `await x ** y` an error, following the spec. + +Fix potentially exponential regular expression. + +## 8.0.3 (2020-10-02) + +### Bug fixes + +Fix a wasteful loop during `Parser` creation when setting `ecmaVersion` to `"latest"`. + +## 8.0.2 (2020-09-30) + +### Bug fixes + +Make the TypeScript types reflect the current allowed values for `ecmaVersion`. + +Fix another regexp/division tokenizer issue. + +## 8.0.1 (2020-08-12) + +### Bug fixes + +Provide the correct value in the `version` export. + +## 8.0.0 (2020-08-12) + +### Bug fixes + +Disallow expressions like `(a = b) = c`. + +Make non-octal escape sequences a syntax error in strict mode. + +### New features + +The package can now be loaded directly as an ECMAScript module in node 13+. + +Update to the set of Unicode properties from ES2021. + +### Breaking changes + +The `ecmaVersion` option is now required. For the moment, omitting it will still work with a warning, but that will change in a future release. + +Some changes to method signatures that may be used by plugins. + +## 7.4.0 (2020-08-03) + +### New features + +Add support for logical assignment operators. + +Add support for numeric separators. + +## 7.3.1 (2020-06-11) + +### Bug fixes + +Make the string in the `version` export match the actual library version. + +## 7.3.0 (2020-06-11) + +### Bug fixes + +Fix a bug that caused parsing of object patterns with a property named `set` that had a default value to fail. + +### New features + +Add support for optional chaining (`?.`). + +## 7.2.0 (2020-05-09) + +### Bug fixes + +Fix precedence issue in parsing of async arrow functions. + +### New features + +Add support for nullish coalescing. + +Add support for `import.meta`. + +Support `export * as ...` syntax. + +Upgrade to Unicode 13. + +## 6.4.1 (2020-03-09) + +### Bug fixes + +More carefully check for valid UTF16 surrogate pairs in regexp validator. + +## 7.1.1 (2020-03-01) + +### Bug fixes + +Treat `\8` and `\9` as invalid escapes in template strings. + +Allow unicode escapes in property names that are keywords. + +Don't error on an exponential operator expression as argument to `await`. + +More carefully check for valid UTF16 surrogate pairs in regexp validator. + +## 7.1.0 (2019-09-24) + +### Bug fixes + +Disallow trailing object literal commas when ecmaVersion is less than 5. + +### New features + +Add a static `acorn` property to the `Parser` class that contains the entire module interface, to allow plugins to access the instance of the library that they are acting on. + +## 7.0.0 (2019-08-13) + +### Breaking changes + +Changes the node format for dynamic imports to use the `ImportExpression` node type, as defined in [ESTree](https://github.com/estree/estree/blob/master/es2020.md#importexpression). + +Makes 10 (ES2019) the default value for the `ecmaVersion` option. + +## 6.3.0 (2019-08-12) + +### New features + +`sourceType: "module"` can now be used even when `ecmaVersion` is less than 6, to parse module-style code that otherwise conforms to an older standard. + +## 6.2.1 (2019-07-21) + +### Bug fixes + +Fix bug causing Acorn to treat some characters as identifier characters that shouldn't be treated as such. + +Fix issue where setting the `allowReserved` option to `"never"` allowed reserved words in some circumstances. + +## 6.2.0 (2019-07-04) + +### Bug fixes + +Improve valid assignment checking in `for`/`in` and `for`/`of` loops. + +Disallow binding `let` in patterns. + +### New features + +Support bigint syntax with `ecmaVersion` >= 11. + +Support dynamic `import` syntax with `ecmaVersion` >= 11. + +Upgrade to Unicode version 12. + +## 6.1.1 (2019-02-27) + +### Bug fixes + +Fix bug that caused parsing default exports of with names to fail. + +## 6.1.0 (2019-02-08) + +### Bug fixes + +Fix scope checking when redefining a `var` as a lexical binding. + +### New features + +Split up `parseSubscripts` to use an internal `parseSubscript` method to make it easier to extend with plugins. + +## 6.0.7 (2019-02-04) + +### Bug fixes + +Check that exported bindings are defined. + +Don't treat `\u180e` as a whitespace character. + +Check for duplicate parameter names in methods. + +Don't allow shorthand properties when they are generators or async methods. + +Forbid binding `await` in async arrow function's parameter list. + +## 6.0.6 (2019-01-30) + +### Bug fixes + +The content of class declarations and expressions is now always parsed in strict mode. + +Don't allow `let` or `const` to bind the variable name `let`. + +Treat class declarations as lexical. + +Don't allow a generator function declaration as the sole body of an `if` or `else`. + +Ignore `"use strict"` when after an empty statement. + +Allow string line continuations with special line terminator characters. + +Treat `for` bodies as part of the `for` scope when checking for conflicting bindings. + +Fix bug with parsing `yield` in a `for` loop initializer. + +Implement special cases around scope checking for functions. + +## 6.0.5 (2019-01-02) + +### Bug fixes + +Fix TypeScript type for `Parser.extend` and add `allowAwaitOutsideFunction` to options type. + +Don't treat `let` as a keyword when the next token is `{` on the next line. + +Fix bug that broke checking for parentheses around an object pattern in a destructuring assignment when `preserveParens` was on. + +## 6.0.4 (2018-11-05) + +### Bug fixes + +Further improvements to tokenizing regular expressions in corner cases. + +## 6.0.3 (2018-11-04) + +### Bug fixes + +Fix bug in tokenizing an expression-less return followed by a function followed by a regular expression. + +Remove stray symlink in the package tarball. + +## 6.0.2 (2018-09-26) + +### Bug fixes + +Fix bug where default expressions could fail to parse inside an object destructuring assignment expression. + +## 6.0.1 (2018-09-14) + +### Bug fixes + +Fix wrong value in `version` export. + +## 6.0.0 (2018-09-14) + +### Bug fixes + +Better handle variable-redefinition checks for catch bindings and functions directly under if statements. + +Forbid `new.target` in top-level arrow functions. + +Fix issue with parsing a regexp after `yield` in some contexts. + +### New features + +The package now comes with TypeScript definitions. + +### Breaking changes + +The default value of the `ecmaVersion` option is now 9 (2018). + +Plugins work differently, and will have to be rewritten to work with this version. + +The loose parser and walker have been moved into separate packages (`acorn-loose` and `acorn-walk`). + +## 5.7.3 (2018-09-10) + +### Bug fixes + +Fix failure to tokenize regexps after expressions like `x.of`. + +Better error message for unterminated template literals. + +## 5.7.2 (2018-08-24) + +### Bug fixes + +Properly handle `allowAwaitOutsideFunction` in for statements. + +Treat function declarations at the top level of modules like let bindings. + +Don't allow async function declarations as the only statement under a label. + +## 5.7.0 (2018-06-15) + +### New features + +Upgraded to Unicode 11. + +## 5.6.0 (2018-05-31) + +### New features + +Allow U+2028 and U+2029 in string when ECMAVersion >= 10. + +Allow binding-less catch statements when ECMAVersion >= 10. + +Add `allowAwaitOutsideFunction` option for parsing top-level `await`. + +## 5.5.3 (2018-03-08) + +### Bug fixes + +A _second_ republish of the code in 5.5.1, this time with yarn, to hopefully get valid timestamps. + +## 5.5.2 (2018-03-08) + +### Bug fixes + +A republish of the code in 5.5.1 in an attempt to solve an issue with the file timestamps in the npm package being 0. + +## 5.5.1 (2018-03-06) + +### Bug fixes + +Fix misleading error message for octal escapes in template strings. + +## 5.5.0 (2018-02-27) + +### New features + +The identifier character categorization is now based on Unicode version 10. + +Acorn will now validate the content of regular expressions, including new ES9 features. + +## 5.4.0 (2018-02-01) + +### Bug fixes + +Disallow duplicate or escaped flags on regular expressions. + +Disallow octal escapes in strings in strict mode. + +### New features + +Add support for async iteration. + +Add support for object spread and rest. + +## 5.3.0 (2017-12-28) + +### Bug fixes + +Fix parsing of floating point literals with leading zeroes in loose mode. + +Allow duplicate property names in object patterns. + +Don't allow static class methods named `prototype`. + +Disallow async functions directly under `if` or `else`. + +Parse right-hand-side of `for`/`of` as an assignment expression. + +Stricter parsing of `for`/`in`. + +Don't allow unicode escapes in contextual keywords. + +### New features + +Parsing class members was factored into smaller methods to allow plugins to hook into it. + +## 5.2.1 (2017-10-30) + +### Bug fixes + +Fix a token context corruption bug. + +## 5.2.0 (2017-10-30) + +### Bug fixes + +Fix token context tracking for `class` and `function` in property-name position. + +Make sure `%*` isn't parsed as a valid operator. + +Allow shorthand properties `get` and `set` to be followed by default values. + +Disallow `super` when not in callee or object position. + +### New features + +Support [`directive` property](https://github.com/estree/estree/compare/b3de58c9997504d6fba04b72f76e6dd1619ee4eb...1da8e603237144f44710360f8feb7a9977e905e0) on directive expression statements. + +## 5.1.2 (2017-09-04) + +### Bug fixes + +Disable parsing of legacy HTML-style comments in modules. + +Fix parsing of async methods whose names are keywords. + +## 5.1.1 (2017-07-06) + +### Bug fixes + +Fix problem with disambiguating regexp and division after a class. + +## 5.1.0 (2017-07-05) + +### Bug fixes + +Fix tokenizing of regexps in an object-desctructuring `for`/`of` loop and after `yield`. + +Parse zero-prefixed numbers with non-octal digits as decimal. + +Allow object/array patterns in rest parameters. + +Don't error when `yield` is used as a property name. + +Allow `async` as a shorthand object property. + +### New features + +Implement the [template literal revision proposal](https://github.com/tc39/proposal-template-literal-revision) for ES9. + +## 5.0.3 (2017-04-01) + +### Bug fixes + +Fix spurious duplicate variable definition errors for named functions. + +## 5.0.2 (2017-03-30) + +### Bug fixes + +A binary operator after a parenthesized arrow expression is no longer incorrectly treated as an error. + +## 5.0.0 (2017-03-28) + +### Bug fixes + +Raise an error for duplicated lexical bindings. + +Fix spurious error when an assignement expression occurred after a spread expression. + +Accept regular expressions after `of` (in `for`/`of`), `yield` (in a generator), and braced arrow functions. + +Allow labels in front or `var` declarations, even in strict mode. + +### Breaking changes + +Parse declarations following `export default` as declaration nodes, not expressions. This means that class and function declarations nodes can now have `null` as their `id`. + +## 4.0.11 (2017-02-07) + +### Bug fixes + +Allow all forms of member expressions to be parenthesized as lvalue. + +## 4.0.10 (2017-02-07) + +### Bug fixes + +Don't expect semicolons after default-exported functions or classes, even when they are expressions. + +Check for use of `'use strict'` directives in non-simple parameter functions, even when already in strict mode. + +## 4.0.9 (2017-02-06) + +### Bug fixes + +Fix incorrect error raised for parenthesized simple assignment targets, so that `(x) = 1` parses again. + +## 4.0.8 (2017-02-03) + +### Bug fixes + +Solve spurious parenthesized pattern errors by temporarily erring on the side of accepting programs that our delayed errors don't handle correctly yet. + +## 4.0.7 (2017-02-02) + +### Bug fixes + +Accept invalidly rejected code like `(x).y = 2` again. + +Don't raise an error when a function _inside_ strict code has a non-simple parameter list. + +## 4.0.6 (2017-02-02) + +### Bug fixes + +Fix exponential behavior (manifesting itself as a complete hang for even relatively small source files) introduced by the new 'use strict' check. + +## 4.0.5 (2017-02-02) + +### Bug fixes + +Disallow parenthesized pattern expressions. + +Allow keywords as export names. + +Don't allow the `async` keyword to be parenthesized. + +Properly raise an error when a keyword contains a character escape. + +Allow `"use strict"` to appear after other string literal expressions. + +Disallow labeled declarations. + +## 4.0.4 (2016-12-19) + +### Bug fixes + +Fix crash when `export` was followed by a keyword that can't be +exported. + +## 4.0.3 (2016-08-16) + +### Bug fixes + +Allow regular function declarations inside single-statement `if` branches in loose mode. Forbid them entirely in strict mode. + +Properly parse properties named `async` in ES2017 mode. + +Fix bug where reserved words were broken in ES2017 mode. + +## 4.0.2 (2016-08-11) + +### Bug fixes + +Don't ignore period or 'e' characters after octal numbers. + +Fix broken parsing for call expressions in default parameter values of arrow functions. + +## 4.0.1 (2016-08-08) + +### Bug fixes + +Fix false positives in duplicated export name errors. + +## 4.0.0 (2016-08-07) + +### Breaking changes + +The default `ecmaVersion` option value is now 7. + +A number of internal method signatures changed, so plugins might need to be updated. + +### Bug fixes + +The parser now raises errors on duplicated export names. + +`arguments` and `eval` can now be used in shorthand properties. + +Duplicate parameter names in non-simple argument lists now always produce an error. + +### New features + +The `ecmaVersion` option now also accepts year-style version numbers +(2015, etc). + +Support for `async`/`await` syntax when `ecmaVersion` is >= 8. + +Support for trailing commas in call expressions when `ecmaVersion` is >= 8. + +## 3.3.0 (2016-07-25) + +### Bug fixes + +Fix bug in tokenizing of regexp operator after a function declaration. + +Fix parser crash when parsing an array pattern with a hole. + +### New features + +Implement check against complex argument lists in functions that enable strict mode in ES7. + +## 3.2.0 (2016-06-07) + +### Bug fixes + +Improve handling of lack of unicode regexp support in host +environment. + +Properly reject shorthand properties whose name is a keyword. + +### New features + +Visitors created with `visit.make` now have their base as _prototype_, rather than copying properties into a fresh object. + +## 3.1.0 (2016-04-18) + +### Bug fixes + +Properly tokenize the division operator directly after a function expression. + +Allow trailing comma in destructuring arrays. + +## 3.0.4 (2016-02-25) + +### Fixes + +Allow update expressions as left-hand-side of the ES7 exponential operator. + +## 3.0.2 (2016-02-10) + +### Fixes + +Fix bug that accidentally made `undefined` a reserved word when parsing ES7. + +## 3.0.0 (2016-02-10) + +### Breaking changes + +The default value of the `ecmaVersion` option is now 6 (used to be 5). + +Support for comprehension syntax (which was dropped from the draft spec) has been removed. + +### Fixes + +`let` and `yield` are now “contextual keywords”, meaning you can mostly use them as identifiers in ES5 non-strict code. + +A parenthesized class or function expression after `export default` is now parsed correctly. + +### New features + +When `ecmaVersion` is set to 7, Acorn will parse the exponentiation operator (`**`). + +The identifier character ranges are now based on Unicode 8.0.0. + +Plugins can now override the `raiseRecoverable` method to override the way non-critical errors are handled. + +## 2.7.0 (2016-01-04) + +### Fixes + +Stop allowing rest parameters in setters. + +Disallow `y` rexexp flag in ES5. + +Disallow `\00` and `\000` escapes in strict mode. + +Raise an error when an import name is a reserved word. + +## 2.6.2 (2015-11-10) + +### Fixes + +Don't crash when no options object is passed. + +## 2.6.0 (2015-11-09) + +### Fixes + +Add `await` as a reserved word in module sources. + +Disallow `yield` in a parameter default value for a generator. + +Forbid using a comma after a rest pattern in an array destructuring. + +### New features + +Support parsing stdin in command-line tool. + +## 2.5.0 (2015-10-27) + +### Fixes + +Fix tokenizer support in the command-line tool. + +Stop allowing `new.target` outside of functions. + +Remove legacy `guard` and `guardedHandler` properties from try nodes. + +Stop allowing multiple `__proto__` properties on an object literal in strict mode. + +Don't allow rest parameters to be non-identifier patterns. + +Check for duplicate paramter names in arrow functions. diff --git a/node_modules/acorn/LICENSE b/node_modules/acorn/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9d71cc63a35e7d878787e5159b5b163739486220 --- /dev/null +++ b/node_modules/acorn/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2012-2022 by various contributors (see AUTHORS) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/acorn/README.md b/node_modules/acorn/README.md new file mode 100644 index 0000000000000000000000000000000000000000..313acd65c2cf7ac290fa623211d81965b0f12f7f --- /dev/null +++ b/node_modules/acorn/README.md @@ -0,0 +1,304 @@ +# Acorn + +A tiny, fast JavaScript parser written in JavaScript. + +## Community + +Acorn is open source software released under an +[MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE). + +You are welcome to +[report bugs](https://github.com/acornjs/acorn/issues) or create pull +requests on [github](https://github.com/acornjs/acorn). + +## Installation + +The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): + +```sh +npm install acorn +``` + +Alternately, you can download the source and build acorn yourself: + +```sh +git clone https://github.com/acornjs/acorn.git +cd acorn +npm install +``` +## Importing acorn + +ESM as well as CommonJS is supported for all 3: `acorn`, `acorn-walk` and `acorn-loose`. + +ESM example for `acorn`: + +```js +import * as acorn from "acorn" +``` + +CommonJS example for `acorn`: + +```js +let acorn = require("acorn") +``` + +ESM is preferred, as it allows better editor auto-completions by offering TypeScript support. +For this reason, following examples will use ESM imports. + +## Interface + +**parse**`(input, options)` is the main interface to the library. The +`input` parameter is a string, `options` must be an object setting +some of the options listed below. The return value will be an abstract +syntax tree object as specified by the [ESTree +spec](https://github.com/estree/estree). + +```javascript +import * as acorn from "acorn" +console.log(acorn.parse("1 + 1", {ecmaVersion: 2020})) +``` + +When encountering a syntax error, the parser will raise a +`SyntaxError` object with a meaningful message. The error object will +have a `pos` property that indicates the string offset at which the +error occurred, and a `loc` object that contains a `{line, column}` +object referring to that same position. + +Options are provided by in a second argument, which should be an +object containing any of these fields (only `ecmaVersion` is +required): + +- **ecmaVersion**: Indicates the ECMAScript version to parse. Can be a + number, either in year (`2022`) or plain version number (`6`) form, + or `"latest"` (the latest the library supports). This influences + support for strict mode, the set of reserved words, and support for + new syntax features. + + **NOTE**: Only 'stage 4' (finalized) ECMAScript features are being + implemented by Acorn. Other proposed new features must be + implemented through plugins. + +- **sourceType**: Indicate the mode the code should be parsed in. Can be + either `"script"`, `"module"` or `"commonjs"`. This influences global strict mode + and parsing of `import` and `export` declarations. + + **NOTE**: If set to `"module"`, then static `import` / `export` syntax + will be valid, even if `ecmaVersion` is less than 6. If set to `"commonjs"`, + it is the same as `"script"` except that the top-level scope behaves like a function. + +- **strict**: When set to true, enable strict parsing mode even if + `sourceType` is `"script"`. + +- **onInsertedSemicolon**: If given a callback, that callback will be + called whenever a missing semicolon is inserted by the parser. The + callback will be given the character offset of the point where the + semicolon is inserted as argument, and if `locations` is on, also a + `{line, column}` object representing this position. + +- **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing + commas. + +- **allowReserved**: If `false`, using a reserved word will generate + an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher + versions. When given the value `"never"`, reserved words and + keywords can also not be used as property names (as in Internet + Explorer's old parser). + +- **allowReturnOutsideFunction**: By default, a return statement at + the top level raises an error. Set this to `true` to accept such + code. + +- **allowImportExportEverywhere**: By default, `import` and `export` + declarations can only appear at a program's top level. Setting this + option to `true` allows them anywhere where a statement is allowed, + and also allows `import.meta` expressions to appear in scripts + (when `sourceType` is not `"module"`). + +- **allowAwaitOutsideFunction**: If `false`, `await` expressions can + only appear inside `async` functions. Defaults to `true` in modules + for `ecmaVersion` 2022 and later, `false` for lower versions. + Setting this option to `true` allows to have top-level `await` + expressions. They are still not allowed in non-`async` functions, + though. Setting this option to `true` is not allowed when `sourceType: "commonjs"`. + +- **allowSuperOutsideMethod**: By default, `super` outside a method + raises an error. Set this to `true` to accept such code. + +- **allowHashBang**: When this is enabled, if the code starts with the + characters `#!` (as in a shellscript), the first line will be + treated as a comment. Defaults to true when `ecmaVersion` >= 2023. + +- **checkPrivateFields**: By default, the parser will verify that + private properties are only used in places where they are valid and + have been declared. Set this to false to turn such checks off. + +- **locations**: When `true`, each node has a `loc` object attached + with `start` and `end` subobjects, each of which contains the + one-based line and zero-based column numbers in `{line, column}` + form. Default is `false`. + +- **onToken**: If a function is passed for this option, each found + token will be passed in same format as tokens returned from + `tokenizer().getToken()`. + + If array is passed, each found token is pushed to it. + + Note that you are not allowed to call the parser from the + callback—that will corrupt its internal state. + +- **onComment**: If a function is passed for this option, whenever a + comment is encountered the function will be called with the + following parameters: + + - `block`: `true` if the comment is a block comment, false if it + is a line comment. + - `text`: The content of the comment. + - `start`: Character offset of the start of the comment. + - `end`: Character offset of the end of the comment. + + When the `locations` options is on, the `{line, column}` locations + of the comment’s start and end are passed as two additional + parameters. + + If array is passed for this option, each found comment is pushed + to it as object in Esprima format: + + ```javascript + { + "type": "Line" | "Block", + "value": "comment text", + "start": Number, + "end": Number, + // If `locations` option is on: + "loc": { + "start": {line: Number, column: Number} + "end": {line: Number, column: Number} + }, + // If `ranges` option is on: + "range": [Number, Number] + } + ``` + + Note that you are not allowed to call the parser from the + callback—that will corrupt its internal state. + +- **ranges**: Nodes have their start and end characters offsets + recorded in `start` and `end` properties (directly on the node, + rather than the `loc` object, which holds line/column data. To also + add a + [semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678) + `range` property holding a `[start, end]` array with the same + numbers, set the `ranges` option to `true`. + +- **program**: It is possible to parse multiple files into a single + AST by passing the tree produced by parsing the first file as the + `program` option in subsequent parses. This will add the toplevel + forms of the parsed file to the "Program" (top) node of an existing + parse tree. + +- **sourceFile**: When the `locations` option is `true`, you can pass + this option to add a `source` attribute in every node’s `loc` + object. Note that the contents of this option are not examined or + processed in any way; you are free to use whatever format you + choose. + +- **directSourceFile**: Like `sourceFile`, but a `sourceFile` property + will be added (regardless of the `location` option) directly to the + nodes, rather than the `loc` object. + +- **preserveParens**: If this option is `true`, parenthesized expressions + are represented by (non-standard) `ParenthesizedExpression` nodes + that have a single `expression` property containing the expression + inside parentheses. + +**parseExpressionAt**`(input, offset, options)` will parse a single +expression in a string, and return its AST. It will not complain if +there is more of the string left after the expression. + +**tokenizer**`(input, options)` returns an object with a `getToken` +method that can be called repeatedly to get the next token, a `{start, +end, type, value}` object (with added `loc` property when the +`locations` option is enabled and `range` property when the `ranges` +option is enabled). When the token's type is `tokTypes.eof`, you +should stop calling the method, since it will keep returning that same +token forever. + +Note that tokenizing JavaScript without parsing it is, in modern +versions of the language, not really possible due to the way syntax is +overloaded in ways that can only be disambiguated by the parse +context. This package applies a bunch of heuristics to try and do a +reasonable job, but you are advised to use `parse` with the `onToken` +option instead of this. + +In ES6 environment, returned result can be used as any other +protocol-compliant iterable: + +```javascript +for (let token of acorn.tokenizer(str)) { + // iterate over the tokens +} + +// transform code to array of tokens: +var tokens = [...acorn.tokenizer(str)] +``` + +**tokTypes** holds an object mapping names to the token type objects +that end up in the `type` properties of tokens. + +**getLineInfo**`(input, offset)` can be used to get a `{line, +column}` object for a given program string and offset. + +### The `Parser` class + +Instances of the **`Parser`** class contain all the state and logic +that drives a parse. It has static methods `parse`, +`parseExpressionAt`, and `tokenizer` that match the top-level +functions by the same name. + +When extending the parser with plugins, you need to call these methods +on the extended version of the class. To extend a parser with plugins, +you can use its static `extend` method. + +```javascript +var acorn = require("acorn") +var jsx = require("acorn-jsx") +var JSXParser = acorn.Parser.extend(jsx()) +JSXParser.parse("foo()", {ecmaVersion: 2020}) +``` + +The `extend` method takes any number of plugin values, and returns a +new `Parser` class that includes the extra parser logic provided by +the plugins. + +## Command line interface + +The `bin/acorn` utility can be used to parse a file from the command +line. It accepts as arguments its input file and the following +options: + +- `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version + to parse. Default is version 9. + +- `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise. + +- `--locations`: Attaches a "loc" object to each node with "start" and + "end" subobjects, each of which contains the one-based line and + zero-based column numbers in `{line, column}` form. + +- `--allow-hash-bang`: If the code starts with the characters #! (as + in a shellscript), the first line will be treated as a comment. + +- `--allow-await-outside-function`: Allows top-level `await` expressions. + See the `allowAwaitOutsideFunction` option for more information. + +- `--compact`: No whitespace is used in the AST output. + +- `--silent`: Do not output the AST, just return the exit status. + +- `--help`: Print the usage information and quit. + +The utility spits out the syntax tree as JSON data. + +## Existing plugins + + - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx) diff --git a/node_modules/acorn/bin/acorn b/node_modules/acorn/bin/acorn new file mode 100644 index 0000000000000000000000000000000000000000..3ef3c124b08bd4fb0f27cd13301dfeeae4a6464c --- /dev/null +++ b/node_modules/acorn/bin/acorn @@ -0,0 +1,4 @@ +#!/usr/bin/env node +"use strict" + +require("../dist/bin.js") diff --git a/node_modules/acorn/package.json b/node_modules/acorn/package.json new file mode 100644 index 0000000000000000000000000000000000000000..79846140ed3d9614146769c5310b91763b07e11d --- /dev/null +++ b/node_modules/acorn/package.json @@ -0,0 +1,50 @@ +{ + "name": "acorn", + "description": "ECMAScript parser", + "homepage": "https://github.com/acornjs/acorn", + "main": "dist/acorn.js", + "types": "dist/acorn.d.ts", + "module": "dist/acorn.mjs", + "exports": { + ".": [ + { + "import": "./dist/acorn.mjs", + "require": "./dist/acorn.js", + "default": "./dist/acorn.js" + }, + "./dist/acorn.js" + ], + "./package.json": "./package.json" + }, + "version": "8.17.0", + "engines": { + "node": ">=0.4.0" + }, + "maintainers": [ + { + "name": "Marijn Haverbeke", + "email": "marijn@haverbeke.berlin", + "web": "https://marijnhaverbeke.nl" + }, + { + "name": "Ingvar Stepanyan", + "email": "me@rreverser.com", + "web": "https://rreverser.com/" + }, + { + "name": "Adrian Heine", + "web": "http://adrianheine.de" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/acornjs/acorn.git" + }, + "license": "MIT", + "scripts": { + "prepare": "cd ..; npm run build:main" + }, + "bin": { + "acorn": "bin/acorn" + } +} diff --git a/node_modules/agent-base/README.md b/node_modules/agent-base/README.md new file mode 100644 index 0000000000000000000000000000000000000000..256f1f32196c60a970bd2b0bd75f669b135112bf --- /dev/null +++ b/node_modules/agent-base/README.md @@ -0,0 +1,145 @@ +agent-base +========== +### Turn a function into an [`http.Agent`][http.Agent] instance +[![Build Status](https://github.com/TooTallNate/node-agent-base/workflows/Node%20CI/badge.svg)](https://github.com/TooTallNate/node-agent-base/actions?workflow=Node+CI) + +This module provides an `http.Agent` generator. That is, you pass it an async +callback function, and it returns a new `http.Agent` instance that will invoke the +given callback function when sending outbound HTTP requests. + +#### Some subclasses: + +Here's some more interesting uses of `agent-base`. +Send a pull request to list yours! + + * [`http-proxy-agent`][http-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTP endpoints + * [`https-proxy-agent`][https-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTPS endpoints + * [`pac-proxy-agent`][pac-proxy-agent]: A PAC file proxy `http.Agent` implementation for HTTP and HTTPS + * [`socks-proxy-agent`][socks-proxy-agent]: A SOCKS proxy `http.Agent` implementation for HTTP and HTTPS + + +Installation +------------ + +Install with `npm`: + +``` bash +$ npm install agent-base +``` + + +Example +------- + +Here's a minimal example that creates a new `net.Socket` connection to the server +for every HTTP request (i.e. the equivalent of `agent: false` option): + +```js +var net = require('net'); +var tls = require('tls'); +var url = require('url'); +var http = require('http'); +var agent = require('agent-base'); + +var endpoint = 'http://nodejs.org/api/'; +var parsed = url.parse(endpoint); + +// This is the important part! +parsed.agent = agent(function (req, opts) { + var socket; + // `secureEndpoint` is true when using the https module + if (opts.secureEndpoint) { + socket = tls.connect(opts); + } else { + socket = net.connect(opts); + } + return socket; +}); + +// Everything else works just like normal... +http.get(parsed, function (res) { + console.log('"response" event!', res.headers); + res.pipe(process.stdout); +}); +``` + +Returning a Promise or using an `async` function is also supported: + +```js +agent(async function (req, opts) { + await sleep(1000); + // etc… +}); +``` + +Return another `http.Agent` instance to "pass through" the responsibility +for that HTTP request to that agent: + +```js +agent(function (req, opts) { + return opts.secureEndpoint ? https.globalAgent : http.globalAgent; +}); +``` + + +API +--- + +## Agent(Function callback[, Object options]) → [http.Agent][] + +Creates a base `http.Agent` that will execute the callback function `callback` +for every HTTP request that it is used as the `agent` for. The callback function +is responsible for creating a `stream.Duplex` instance of some kind that will be +used as the underlying socket in the HTTP request. + +The `options` object accepts the following properties: + + * `timeout` - Number - Timeout for the `callback()` function in milliseconds. Defaults to Infinity (optional). + +The callback function should have the following signature: + +### callback(http.ClientRequest req, Object options, Function cb) → undefined + +The ClientRequest `req` can be accessed to read request headers and +and the path, etc. The `options` object contains the options passed +to the `http.request()`/`https.request()` function call, and is formatted +to be directly passed to `net.connect()`/`tls.connect()`, or however +else you want a Socket to be created. Pass the created socket to +the callback function `cb` once created, and the HTTP request will +continue to proceed. + +If the `https` module is used to invoke the HTTP request, then the +`secureEndpoint` property on `options` _will be set to `true`_. + + +License +------- + +(The MIT License) + +Copyright (c) 2013 Nathan Rajlich <nathan@tootallnate.net> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +[http-proxy-agent]: https://github.com/TooTallNate/node-http-proxy-agent +[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent +[pac-proxy-agent]: https://github.com/TooTallNate/node-pac-proxy-agent +[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent +[http.Agent]: https://nodejs.org/api/http.html#http_class_http_agent diff --git a/node_modules/agent-base/package.json b/node_modules/agent-base/package.json new file mode 100644 index 0000000000000000000000000000000000000000..fadce3ad99f22df16cf1e9be85c8598f812339c9 --- /dev/null +++ b/node_modules/agent-base/package.json @@ -0,0 +1,64 @@ +{ + "name": "agent-base", + "version": "6.0.2", + "description": "Turn a function into an `http.Agent` instance", + "main": "dist/src/index", + "typings": "dist/src/index", + "files": [ + "dist/src", + "src" + ], + "scripts": { + "prebuild": "rimraf dist", + "build": "tsc", + "postbuild": "cpy --parents src test '!**/*.ts' dist", + "test": "mocha --reporter spec dist/test/*.js", + "test-lint": "eslint src --ext .js,.ts", + "prepublishOnly": "npm run build" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/node-agent-base.git" + }, + "keywords": [ + "http", + "agent", + "base", + "barebones", + "https" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/node-agent-base/issues" + }, + "dependencies": { + "debug": "4" + }, + "devDependencies": { + "@types/debug": "4", + "@types/mocha": "^5.2.7", + "@types/node": "^14.0.20", + "@types/semver": "^7.1.0", + "@types/ws": "^6.0.3", + "@typescript-eslint/eslint-plugin": "1.6.0", + "@typescript-eslint/parser": "1.1.0", + "async-listen": "^1.2.0", + "cpy-cli": "^2.0.0", + "eslint": "5.16.0", + "eslint-config-airbnb": "17.1.0", + "eslint-config-prettier": "4.1.0", + "eslint-import-resolver-typescript": "1.1.1", + "eslint-plugin-import": "2.16.0", + "eslint-plugin-jsx-a11y": "6.2.1", + "eslint-plugin-react": "7.12.4", + "mocha": "^6.2.0", + "rimraf": "^3.0.0", + "semver": "^7.1.2", + "typescript": "^3.5.3", + "ws": "^3.0.0" + }, + "engines": { + "node": ">= 6.0.0" + } +} diff --git a/node_modules/agent-base/src/index.ts b/node_modules/agent-base/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..a47ccd493f90a82794ba0f5b28f5063f889d6a29 --- /dev/null +++ b/node_modules/agent-base/src/index.ts @@ -0,0 +1,345 @@ +import net from 'net'; +import http from 'http'; +import https from 'https'; +import { Duplex } from 'stream'; +import { EventEmitter } from 'events'; +import createDebug from 'debug'; +import promisify from './promisify'; + +const debug = createDebug('agent-base'); + +function isAgent(v: any): v is createAgent.AgentLike { + return Boolean(v) && typeof v.addRequest === 'function'; +} + +function isSecureEndpoint(): boolean { + const { stack } = new Error(); + if (typeof stack !== 'string') return false; + return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); +} + +function createAgent(opts?: createAgent.AgentOptions): createAgent.Agent; +function createAgent( + callback: createAgent.AgentCallback, + opts?: createAgent.AgentOptions +): createAgent.Agent; +function createAgent( + callback?: createAgent.AgentCallback | createAgent.AgentOptions, + opts?: createAgent.AgentOptions +) { + return new createAgent.Agent(callback, opts); +} + +namespace createAgent { + export interface ClientRequest extends http.ClientRequest { + _last?: boolean; + _hadError?: boolean; + method: string; + } + + export interface AgentRequestOptions { + host?: string; + path?: string; + // `port` on `http.RequestOptions` can be a string or undefined, + // but `net.TcpNetConnectOpts` expects only a number + port: number; + } + + export interface HttpRequestOptions + extends AgentRequestOptions, + Omit { + secureEndpoint: false; + } + + export interface HttpsRequestOptions + extends AgentRequestOptions, + Omit { + secureEndpoint: true; + } + + export type RequestOptions = HttpRequestOptions | HttpsRequestOptions; + + export type AgentLike = Pick | http.Agent; + + export type AgentCallbackReturn = Duplex | AgentLike; + + export type AgentCallbackCallback = ( + err?: Error | null, + socket?: createAgent.AgentCallbackReturn + ) => void; + + export type AgentCallbackPromise = ( + req: createAgent.ClientRequest, + opts: createAgent.RequestOptions + ) => + | createAgent.AgentCallbackReturn + | Promise; + + export type AgentCallback = typeof Agent.prototype.callback; + + export type AgentOptions = { + timeout?: number; + }; + + /** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ + export class Agent extends EventEmitter { + public timeout: number | null; + public maxFreeSockets: number; + public maxTotalSockets: number; + public maxSockets: number; + public sockets: { + [key: string]: net.Socket[]; + }; + public freeSockets: { + [key: string]: net.Socket[]; + }; + public requests: { + [key: string]: http.IncomingMessage[]; + }; + public options: https.AgentOptions; + private promisifiedCallback?: createAgent.AgentCallbackPromise; + private explicitDefaultPort?: number; + private explicitProtocol?: string; + + constructor( + callback?: createAgent.AgentCallback | createAgent.AgentOptions, + _opts?: createAgent.AgentOptions + ) { + super(); + + let opts = _opts; + if (typeof callback === 'function') { + this.callback = callback; + } else if (callback) { + opts = callback; + } + + // Timeout for the socket to be returned from the callback + this.timeout = null; + if (opts && typeof opts.timeout === 'number') { + this.timeout = opts.timeout; + } + + // These aren't actually used by `agent-base`, but are required + // for the TypeScript definition files in `@types/node` :/ + this.maxFreeSockets = 1; + this.maxSockets = 1; + this.maxTotalSockets = Infinity; + this.sockets = {}; + this.freeSockets = {}; + this.requests = {}; + this.options = {}; + } + + get defaultPort(): number { + if (typeof this.explicitDefaultPort === 'number') { + return this.explicitDefaultPort; + } + return isSecureEndpoint() ? 443 : 80; + } + + set defaultPort(v: number) { + this.explicitDefaultPort = v; + } + + get protocol(): string { + if (typeof this.explicitProtocol === 'string') { + return this.explicitProtocol; + } + return isSecureEndpoint() ? 'https:' : 'http:'; + } + + set protocol(v: string) { + this.explicitProtocol = v; + } + + callback( + req: createAgent.ClientRequest, + opts: createAgent.RequestOptions, + fn: createAgent.AgentCallbackCallback + ): void; + callback( + req: createAgent.ClientRequest, + opts: createAgent.RequestOptions + ): + | createAgent.AgentCallbackReturn + | Promise; + callback( + req: createAgent.ClientRequest, + opts: createAgent.AgentOptions, + fn?: createAgent.AgentCallbackCallback + ): + | createAgent.AgentCallbackReturn + | Promise + | void { + throw new Error( + '"agent-base" has no default implementation, you must subclass and override `callback()`' + ); + } + + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req: ClientRequest, _opts: RequestOptions): void { + const opts: RequestOptions = { ..._opts }; + + if (typeof opts.secureEndpoint !== 'boolean') { + opts.secureEndpoint = isSecureEndpoint(); + } + + if (opts.host == null) { + opts.host = 'localhost'; + } + + if (opts.port == null) { + opts.port = opts.secureEndpoint ? 443 : 80; + } + + if (opts.protocol == null) { + opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; + } + + if (opts.host && opts.path) { + // If both a `host` and `path` are specified then it's most + // likely the result of a `url.parse()` call... we need to + // remove the `path` portion so that `net.connect()` doesn't + // attempt to open that as a unix socket file. + delete opts.path; + } + + delete opts.agent; + delete opts.hostname; + delete opts._defaultAgent; + delete opts.defaultPort; + delete opts.createConnection; + + // Hint to use "Connection: close" + // XXX: non-documented `http` module API :( + req._last = true; + req.shouldKeepAlive = false; + + let timedOut = false; + let timeoutId: ReturnType | null = null; + const timeoutMs = opts.timeout || this.timeout; + + const onerror = (err: NodeJS.ErrnoException) => { + if (req._hadError) return; + req.emit('error', err); + // For Safety. Some additional errors might fire later on + // and we need to make sure we don't double-fire the error event. + req._hadError = true; + }; + + const ontimeout = () => { + timeoutId = null; + timedOut = true; + const err: NodeJS.ErrnoException = new Error( + `A "socket" was not created for HTTP request before ${timeoutMs}ms` + ); + err.code = 'ETIMEOUT'; + onerror(err); + }; + + const callbackError = (err: NodeJS.ErrnoException) => { + if (timedOut) return; + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } + onerror(err); + }; + + const onsocket = (socket: AgentCallbackReturn) => { + if (timedOut) return; + if (timeoutId != null) { + clearTimeout(timeoutId); + timeoutId = null; + } + + if (isAgent(socket)) { + // `socket` is actually an `http.Agent` instance, so + // relinquish responsibility for this `req` to the Agent + // from here on + debug( + 'Callback returned another Agent instance %o', + socket.constructor.name + ); + (socket as createAgent.Agent).addRequest(req, opts); + return; + } + + if (socket) { + socket.once('free', () => { + this.freeSocket(socket as net.Socket, opts); + }); + req.onSocket(socket as net.Socket); + return; + } + + const err = new Error( + `no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\`` + ); + onerror(err); + }; + + if (typeof this.callback !== 'function') { + onerror(new Error('`callback` is not defined')); + return; + } + + if (!this.promisifiedCallback) { + if (this.callback.length >= 3) { + debug('Converting legacy callback function to promise'); + this.promisifiedCallback = promisify(this.callback); + } else { + this.promisifiedCallback = this.callback; + } + } + + if (typeof timeoutMs === 'number' && timeoutMs > 0) { + timeoutId = setTimeout(ontimeout, timeoutMs); + } + + if ('port' in opts && typeof opts.port !== 'number') { + opts.port = Number(opts.port); + } + + try { + debug( + 'Resolving socket for %o request: %o', + opts.protocol, + `${req.method} ${req.path}` + ); + Promise.resolve(this.promisifiedCallback(req, opts)).then( + onsocket, + callbackError + ); + } catch (err) { + Promise.reject(err).catch(callbackError); + } + } + + freeSocket(socket: net.Socket, opts: AgentOptions) { + debug('Freeing socket %o %o', socket.constructor.name, opts); + socket.destroy(); + } + + destroy() { + debug('Destroying agent %o', this.constructor.name); + } + } + + // So that `instanceof` works correctly + createAgent.prototype = createAgent.Agent.prototype; +} + +export = createAgent; diff --git a/node_modules/agent-base/src/promisify.ts b/node_modules/agent-base/src/promisify.ts new file mode 100644 index 0000000000000000000000000000000000000000..60cc6627100b8142677d0f109c84cbb99f97d2a1 --- /dev/null +++ b/node_modules/agent-base/src/promisify.ts @@ -0,0 +1,33 @@ +import { + Agent, + ClientRequest, + RequestOptions, + AgentCallbackCallback, + AgentCallbackPromise, + AgentCallbackReturn +} from './index'; + +type LegacyCallback = ( + req: ClientRequest, + opts: RequestOptions, + fn: AgentCallbackCallback +) => void; + +export default function promisify(fn: LegacyCallback): AgentCallbackPromise { + return function(this: Agent, req: ClientRequest, opts: RequestOptions) { + return new Promise((resolve, reject) => { + fn.call( + this, + req, + opts, + (err: Error | null | undefined, rtn?: AgentCallbackReturn) => { + if (err) { + reject(err); + } else { + resolve(rtn); + } + } + ); + }); + }; +} diff --git a/node_modules/ajv-formats/LICENSE b/node_modules/ajv-formats/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a3f8ba0278836d0d02b845aec548a21db114e984 --- /dev/null +++ b/node_modules/ajv-formats/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/ajv-formats/README.md b/node_modules/ajv-formats/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b4264cd6f86fdd2f34c28de82ebec5756955c18d --- /dev/null +++ b/node_modules/ajv-formats/README.md @@ -0,0 +1,125 @@ +# ajv-formats + +JSON Schema formats for Ajv + +[![Build Status](https://travis-ci.org/ajv-validator/ajv-formats.svg?branch=master)](https://travis-ci.org/ajv-validator/ajv-formats) +[![npm](https://img.shields.io/npm/v/ajv-formats.svg)](https://www.npmjs.com/package/ajv-formats) +[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) +[![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin) + +## Usage + +```javascript +// ESM/TypeScript import +import Ajv from "ajv" +import addFormats from "ajv-formats" +// Node.js require: +const Ajv = require("ajv") +const addFormats = require("ajv-formats") + +const ajv = new Ajv() +addFormats(ajv) +``` + +## Formats + +The package defines these formats: + +- _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6). +- _time_: time (time-zone is mandatory). +- _date-time_: date-time (time-zone is mandatory). +- _iso-time_: time with optional time-zone. +- _iso-date-time_: date-time with optional time-zone. +- _duration_: duration from [RFC3339](https://tools.ietf.org/html/rfc3339#appendix-A) +- _uri_: full URI. +- _uri-reference_: URI reference, including full and relative URIs. +- _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570) +- _url_ (deprecated): [URL record](https://url.spec.whatwg.org/#concept-url). +- _email_: email address. +- _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5). +- _ipv4_: IP address v4. +- _ipv6_: IP address v6. +- _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor. +- _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122). +- _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901). +- _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00). +- _byte_: base64 encoded data according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types) +- _int32_: signed 32 bits integer according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types) +- _int64_: signed 64 bits according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types) +- _float_: float according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types) +- _double_: double according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types) +- _password_: password string according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types) +- _binary_: binary string according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types) + +See regular expressions used for format validation and the sources that were used in [formats.ts](https://github.com/ajv-validator/ajv-formats/blob/master/src/formats.ts). + +**Please note**: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. These formats are available in [ajv-formats-draft2019](https://github.com/luzlab/ajv-formats-draft2019) plugin. + +## Keywords to compare values: `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` + +These keywords allow to define minimum/maximum constraints when the format keyword defines ordering (`compare` function in format definition). + +These keywords are added to ajv instance when ajv-formats is used without options or with option `keywords: true`. + +These keywords apply only to strings. If the data is not a string, the validation succeeds. + +The value of keywords `formatMaximum`/`formatMinimum` and `formatExclusiveMaximum`/`formatExclusiveMinimum` should be a string or [\$data reference](https://github.com/ajv-validator/ajv/blob/master/docs/validation.md#data-reference). This value is the maximum (minimum) allowed value for the data to be valid as determined by `format` keyword. If `format` keyword is not present schema compilation will throw exception. + +When these keyword are added, they also add comparison functions to formats `"date"`, `"time"` and `"date-time"`. User-defined formats also can have comparison functions. See [addFormat](https://github.com/ajv-validator/ajv/blob/master/docs/api.md#api-addformat) method. + +```javascript +require("ajv-formats")(ajv) + +const schema = { + type: "string", + format: "date", + formatMinimum: "2016-02-06", + formatExclusiveMaximum: "2016-12-27", +} + +const validDataList = ["2016-02-06", "2016-12-26"] + +const invalidDataList = ["2016-02-05", "2016-12-27", "abc"] +``` + +## Options + +Options can be passed via the second parameter. Options value can be + +1. The list of format names that will be added to ajv instance: + +```javascript +addFormats(ajv, ["date", "time"]) +``` + +**Please note**: when ajv encounters an undefined format it throws exception (unless ajv instance was configured with `strict: false` option). To allow specific undefined formats they have to be passed to ajv instance via `formats` option with `true` value: + +```javascript +const ajv = new Ajv((formats: {date: true, time: true})) // to ignore "date" and "time" formats in schemas. +``` + +2. Format validation mode (default is `"full"`) with optional list of format names and `keywords` option to add additional format comparison keywords: + +```javascript +addFormats(ajv, {mode: "fast"}) +``` + +or + +```javascript +addFormats(ajv, {mode: "fast", formats: ["date", "time"], keywords: true}) +``` + +In `"fast"` mode the following formats are simplified: `"date"`, `"time"`, `"date-time"`, `"iso-time"`, `"iso-date-time"`, `"uri"`, `"uri-reference"`, `"email"`. For example, `"date"`, `"time"` and `"date-time"` do not validate ranges in `"fast"` mode, only string structure, and other formats have simplified regular expressions. + +## Tests + +```bash +npm install +git submodule update --init +npm test +``` + +## License + +[MIT](https://github.com/ajv-validator/ajv-formats/blob/master/LICENSE) diff --git a/node_modules/ajv-formats/package.json b/node_modules/ajv-formats/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e673a8fc4722278dad7103e108229fd12d4db725 --- /dev/null +++ b/node_modules/ajv-formats/package.json @@ -0,0 +1,74 @@ +{ + "name": "ajv-formats", + "version": "3.0.1", + "description": "Format validation for Ajv v7+", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "files": [ + "src/", + "dist/" + ], + "scripts": { + "build": "tsc", + "prettier:write": "prettier --write \"./**/*.{md,json,yaml,js,ts}\"", + "prettier:check": "prettier --list-different \"./**/*.{md,json,yaml,js,ts}\"", + "eslint": "eslint --ext .ts ./src/**/*", + "test-spec": "jest", + "test-cov": "jest --coverage", + "test": "npm run prettier:check && npm run build && npm run eslint && npm run test-cov", + "ci-test": "npm run test" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ajv-validator/ajv-formats.git" + }, + "keywords": [ + "Ajv", + "JSON-Schema", + "format", + "validation" + ], + "author": "Evgeny Poberezkin", + "license": "MIT", + "bugs": { + "url": "https://github.com/ajv-validator/ajv-formats/issues" + }, + "homepage": "https://github.com/ajv-validator/ajv-formats#readme", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + }, + "devDependencies": { + "@ajv-validator/config": "^0.3.0", + "@types/jest": "^26.0.5", + "@types/node": "^14.10.1", + "@typescript-eslint/eslint-plugin": "^3.7.0", + "@typescript-eslint/parser": "^3.7.0", + "ajv": "^8.0.0", + "eslint": "^7.5.0", + "eslint-config-prettier": "^6.11.0", + "husky": "^4.2.5", + "jest": "^26.1.0", + "json-schema-test": "^2.0.0", + "lint-staged": "^10.2.11", + "prettier": "^2.3.2", + "ts-jest": "^26.1.3", + "typescript": "^4.0.0" + }, + "prettier": "@ajv-validator/config/prettierrc.json", + "husky": { + "hooks": { + "pre-commit": "lint-staged && npm test" + } + }, + "lint-staged": { + "*.{md,json,yaml,js,ts}": "prettier --write" + } +} diff --git a/node_modules/ajv-formats/src/formats.ts b/node_modules/ajv-formats/src/formats.ts new file mode 100644 index 0000000000000000000000000000000000000000..d3cde9bcaf124a57fd49ba15fdb979e24259a17f --- /dev/null +++ b/node_modules/ajv-formats/src/formats.ts @@ -0,0 +1,269 @@ +import type {Format, FormatDefinition} from "ajv" +import type {FormatValidator, FormatCompare} from "ajv/dist/types" + +export type FormatMode = "fast" | "full" + +export type FormatName = + | "date" + | "time" + | "date-time" + | "iso-time" + | "iso-date-time" + | "duration" + | "uri" + | "uri-reference" + | "uri-template" + | "url" + | "email" + | "hostname" + | "ipv4" + | "ipv6" + | "regex" + | "uuid" + | "json-pointer" + | "json-pointer-uri-fragment" + | "relative-json-pointer" + | "byte" + | "int32" + | "int64" + | "float" + | "double" + | "password" + | "binary" + +export type DefinedFormats = { + [key in FormatName]: Format +} + +function fmtDef( + validate: RegExp | FormatValidator, + compare: FormatCompare +): FormatDefinition { + return {validate, compare} +} + +export const fullFormats: DefinedFormats = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: fmtDef(date, compareDate), + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + // duration: https://tools.ietf.org/html/rfc3339#appendix-A + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": + /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, + // uri-template: https://tools.ietf.org/html/rfc6570 + "uri-template": + /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, + // For the source: https://gist.github.com/dperini/729294 + // For test cases: https://mathiasbynens.be/demo/url-regex + url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: + /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: + /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, + ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, + regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, + "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, + // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types + // byte: https://github.com/miguelmota/is-base64 + byte, + // signed 32 bit integer + int32: {type: "number", validate: validateInt32}, + // signed 64 bit integer + int64: {type: "number", validate: validateInt64}, + // C-type float + float: {type: "number", validate: validateNumber}, + // C-type double + double: {type: "number", validate: validateNumber}, + // hint to the UI to hide input strings + password: true, + // unchecked string payload + binary: true, +} + +export const fastFormats: DefinedFormats = { + ...fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef( + /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, + compareTime + ), + "date-time": fmtDef( + /^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, + compareDateTime + ), + "iso-time": fmtDef( + /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, + compareIsoTime + ), + "iso-date-time": fmtDef( + /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, + compareIsoDateTime + ), + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') + email: + /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, +} + +export const formatNames = Object.keys(fullFormats) as FormatName[] + +function isLeapYear(year: number): boolean { + // https://tools.ietf.org/html/rfc3339#appendix-C + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) +} + +const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/ +const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + +function date(str: string): boolean { + // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 + const matches: string[] | null = DATE.exec(str) + if (!matches) return false + const year: number = +matches[1] + const month: number = +matches[2] + const day: number = +matches[3] + return ( + month >= 1 && + month <= 12 && + day >= 1 && + day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]) + ) +} + +function compareDate(d1: string, d2: string): number | undefined { + if (!(d1 && d2)) return undefined + if (d1 > d2) return 1 + if (d1 < d2) return -1 + return 0 +} + +const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i + +function getTime(strictTimeZone?: boolean): (str: string) => boolean { + return function time(str: string): boolean { + const matches: string[] | null = TIME.exec(str) + if (!matches) return false + const hr: number = +matches[1] + const min: number = +matches[2] + const sec: number = +matches[3] + const tz: string | undefined = matches[4] + const tzSign: number = matches[5] === "-" ? -1 : 1 + const tzH: number = +(matches[6] || 0) + const tzM: number = +(matches[7] || 0) + if (tzH > 23 || tzM > 59 || (strictTimeZone && !tz)) return false + if (hr <= 23 && min <= 59 && sec < 60) return true + // leap second + const utcMin = min - tzM * tzSign + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0) + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61 + } +} + +function compareTime(s1: string, s2: string): number | undefined { + if (!(s1 && s2)) return undefined + const t1 = new Date("2020-01-01T" + s1).valueOf() + const t2 = new Date("2020-01-01T" + s2).valueOf() + if (!(t1 && t2)) return undefined + return t1 - t2 +} + +function compareIsoTime(t1: string, t2: string): number | undefined { + if (!(t1 && t2)) return undefined + const a1 = TIME.exec(t1) + const a2 = TIME.exec(t2) + if (!(a1 && a2)) return undefined + t1 = a1[1] + a1[2] + a1[3] + t2 = a2[1] + a2[2] + a2[3] + if (t1 > t2) return 1 + if (t1 < t2) return -1 + return 0 +} + +const DATE_TIME_SEPARATOR = /t|\s/i +function getDateTime(strictTimeZone?: boolean): (str: string) => boolean { + const time = getTime(strictTimeZone) + + return function date_time(str: string): boolean { + // http://tools.ietf.org/html/rfc3339#section-5.6 + const dateTime: string[] = str.split(DATE_TIME_SEPARATOR) + return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]) + } +} + +function compareDateTime(dt1: string, dt2: string): number | undefined { + if (!(dt1 && dt2)) return undefined + const d1 = new Date(dt1).valueOf() + const d2 = new Date(dt2).valueOf() + if (!(d1 && d2)) return undefined + return d1 - d2 +} + +function compareIsoDateTime(dt1: string, dt2: string): number | undefined { + if (!(dt1 && dt2)) return undefined + const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR) + const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR) + const res = compareDate(d1, d2) + if (res === undefined) return undefined + return res || compareTime(t1, t2) +} + +const NOT_URI_FRAGMENT = /\/|:/ +const URI = + /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i + +function uri(str: string): boolean { + // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." + return NOT_URI_FRAGMENT.test(str) && URI.test(str) +} + +const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm + +function byte(str: string): boolean { + BYTE.lastIndex = 0 + return BYTE.test(str) +} + +const MIN_INT32 = -(2 ** 31) +const MAX_INT32 = 2 ** 31 - 1 + +function validateInt32(value: number): boolean { + return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32 +} + +function validateInt64(value: number): boolean { + // JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64 + return Number.isInteger(value) +} + +function validateNumber(): boolean { + return true +} + +const Z_ANCHOR = /[^\\]\\Z/ +function regex(str: string): boolean { + if (Z_ANCHOR.test(str)) return false + try { + new RegExp(str) + return true + } catch (e) { + return false + } +} diff --git a/node_modules/ajv-formats/src/index.ts b/node_modules/ajv-formats/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..8fd944a09021a795e86c3285c838f65ca0a957d9 --- /dev/null +++ b/node_modules/ajv-formats/src/index.ts @@ -0,0 +1,62 @@ +import { + DefinedFormats, + FormatMode, + FormatName, + formatNames, + fastFormats, + fullFormats, +} from "./formats" +import formatLimit from "./limit" +import type Ajv from "ajv" +import type {Plugin, Format} from "ajv" +import {_, Name} from "ajv/dist/compile/codegen" + +export {FormatMode, FormatName} from "./formats" +export {LimitFormatError} from "./limit" +export interface FormatOptions { + mode?: FormatMode + formats?: FormatName[] + keywords?: boolean +} + +export type FormatsPluginOptions = FormatName[] | FormatOptions + +export interface FormatsPlugin extends Plugin { + get: (format: FormatName, mode?: FormatMode) => Format +} + +const fullName = new Name("fullFormats") +const fastName = new Name("fastFormats") + +const formatsPlugin: FormatsPlugin = ( + ajv: Ajv, + opts: FormatsPluginOptions = {keywords: true} +): Ajv => { + if (Array.isArray(opts)) { + addFormats(ajv, opts, fullFormats, fullName) + return ajv + } + const [formats, exportName] = + opts.mode === "fast" ? [fastFormats, fastName] : [fullFormats, fullName] + const list = opts.formats || formatNames + addFormats(ajv, list, formats, exportName) + if (opts.keywords) formatLimit(ajv) + return ajv +} + +formatsPlugin.get = (name: FormatName, mode: FormatMode = "full"): Format => { + const formats = mode === "fast" ? fastFormats : fullFormats + const f = formats[name] + if (!f) throw new Error(`Unknown format "${name}"`) + return f +} + +function addFormats(ajv: Ajv, list: FormatName[], fs: DefinedFormats, exportName: Name): void { + ajv.opts.code.formats ??= _`require("ajv-formats/dist/formats").${exportName}` + for (const f of list) ajv.addFormat(f, fs[f]) +} + +module.exports = exports = formatsPlugin +Object.defineProperty(exports, "__esModule", {value: true}) + +export default formatsPlugin diff --git a/node_modules/ajv-formats/src/limit.ts b/node_modules/ajv-formats/src/limit.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf6a57cb9d728658e8461b9e02b5d59fcaff74b1 --- /dev/null +++ b/node_modules/ajv-formats/src/limit.ts @@ -0,0 +1,99 @@ +import type Ajv from "ajv" +import type { + Plugin, + CodeKeywordDefinition, + KeywordErrorDefinition, + Code, + Name, + ErrorObject, +} from "ajv" +import type {AddedFormat} from "ajv/dist/types" +import type {Rule} from "ajv/dist/compile/rules" +import {KeywordCxt} from "ajv" +import {_, str, or, getProperty, operators} from "ajv/dist/compile/codegen" + +type Kwd = "formatMaximum" | "formatMinimum" | "formatExclusiveMaximum" | "formatExclusiveMinimum" + +type Comparison = "<=" | ">=" | "<" | ">" + +const ops = operators + +const KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = { + formatMaximum: {okStr: "<=", ok: ops.LTE, fail: ops.GT}, + formatMinimum: {okStr: ">=", ok: ops.GTE, fail: ops.LT}, + formatExclusiveMaximum: {okStr: "<", ok: ops.LT, fail: ops.GTE}, + formatExclusiveMinimum: {okStr: ">", ok: ops.GT, fail: ops.LTE}, +} + +export type LimitFormatError = ErrorObject + +const error: KeywordErrorDefinition = { + message: ({keyword, schemaCode}) => str`should be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`, + params: ({keyword, schemaCode}) => + _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`, +} + +export const formatLimitDefinition: CodeKeywordDefinition = { + keyword: Object.keys(KWDs), + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt) { + const {gen, data, schemaCode, keyword, it} = cxt + const {opts, self} = it + if (!opts.validateFormats) return + + const fCxt = new KeywordCxt(it, (self.RULES.all.format as Rule).definition, "format") + if (fCxt.$data) validate$DataFormat() + else validateFormat() + + function validate$DataFormat(): void { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats, + }) + const fmt = gen.const("fmt", _`${fmts}[${fCxt.schemaCode}]`) + cxt.fail$data( + or( + _`typeof ${fmt} != "object"`, + _`${fmt} instanceof RegExp`, + _`typeof ${fmt}.compare != "function"`, + compareCode(fmt) + ) + ) + } + + function validateFormat(): void { + const format = fCxt.schema as string + const fmtDef: AddedFormat | undefined = self.formats[format] + if (!fmtDef || fmtDef === true) return + if ( + typeof fmtDef != "object" || + fmtDef instanceof RegExp || + typeof fmtDef.compare != "function" + ) { + throw new Error(`"${keyword}": format "${format}" does not define "compare" function`) + } + const fmt = gen.scopeValue("formats", { + key: format, + ref: fmtDef, + code: opts.code.formats ? _`${opts.code.formats}${getProperty(format)}` : undefined, + }) + + cxt.fail$data(compareCode(fmt)) + } + + function compareCode(fmt: Name): Code { + return _`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword as Kwd].fail} 0` + } + }, + dependencies: ["format"], +} + +const formatLimitPlugin: Plugin = (ajv: Ajv): Ajv => { + ajv.addKeyword(formatLimitDefinition) + return ajv +} + +export default formatLimitPlugin diff --git a/node_modules/ajv/.runkit_example.js b/node_modules/ajv/.runkit_example.js new file mode 100644 index 0000000000000000000000000000000000000000..0d578d5d51e51a3e03b8a69f0eea05c3a3d8913a --- /dev/null +++ b/node_modules/ajv/.runkit_example.js @@ -0,0 +1,23 @@ +const Ajv = require("ajv") +const ajv = new Ajv({allErrors: true}) + +const schema = { + type: "object", + properties: { + foo: {type: "string"}, + bar: {type: "number", maximum: 3}, + }, + required: ["foo", "bar"], + additionalProperties: false, +} + +const validate = ajv.compile(schema) + +test({foo: "abc", bar: 2}) +test({foo: 2, bar: 4}) + +function test(data) { + const valid = validate(data) + if (valid) console.log("Valid!") + else console.log("Invalid: " + ajv.errorsText(validate.errors)) +} diff --git a/node_modules/ajv/LICENSE b/node_modules/ajv/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..139162ad2c389a18d3d66e159a2821b2e40087fc --- /dev/null +++ b/node_modules/ajv/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015-2021 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/ajv/README.md b/node_modules/ajv/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d0c4c08a5bd5ac198a84298da09d3e76a7684322 --- /dev/null +++ b/node_modules/ajv/README.md @@ -0,0 +1,207 @@ +Ajv logo + +  + +# Ajv JSON schema validator + +The fastest JSON validator for Node.js and browser. + +Supports JSON Schema draft-04/06/07/2019-09/2020-12 ([draft-04 support](https://ajv.js.org/json-schema.html#draft-04) requires ajv-draft-04 package) and JSON Type Definition [RFC8927](https://datatracker.ietf.org/doc/rfc8927/). + +[![build](https://github.com/ajv-validator/ajv/actions/workflows/build.yml/badge.svg)](https://github.com/ajv-validator/ajv/actions?query=workflow%3Abuild) +[![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) +[![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) +[![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master) +[![SimpleX](https://img.shields.io/badge/chat-on%20SimpleX-70F0F9)](https://simplex.chat/contact#/?v=1-2&smp=smp%3A%2F%2Fu2dS9sG8nMNURyZwqASV4yROM28Er0luVTx5X1CsMrU%3D%40smp4.simplex.im%2F8KvvURM6J38Gdq9dCuPswMOkMny0xCOJ%23%2F%3Fv%3D1-2%26dh%3DMCowBQYDK2VuAyEAr8rPVRuMOXv6kwF2yUAap-eoVg-9ssOFCi1fIrxTUw0%253D%26srv%3Do5vmywmrnaxalvz6wi3zicyftgio6psuvyniis6gco6bp6ekl4cqj4id.onion&data=%7B%22type%22%3A%22group%22%2C%22groupLinkId%22%3A%224pwLRgWHU9tlroMWHz0uOg%3D%3D%22%7D) +[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) +[![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin) + +## Ajv sponsors + +[Mozilla](https://www.mozilla.org)[](https://opencollective.com/ajv) + +[Microsoft](https://opensource.microsoft.com)[](https://opencollective.com/ajv)[](https://opencollective.com/ajv) + +[Retool](https://retool.com/?utm_source=sponsor&utm_campaign=ajv)[Tidelift](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=enterprise)[SimpleX](https://github.com/simplex-chat/simplex-chat)[](https://opencollective.com/ajv) + +## Contributing + +More than 100 people contributed to Ajv, and we would love to have you join the development. We welcome implementing new features that will benefit many users and ideas to improve our documentation. + +Please review [Contributing guidelines](./CONTRIBUTING.md) and [Code components](https://ajv.js.org/components.html). + +## Documentation + +All documentation is available on the [Ajv website](https://ajv.js.org). + +Some useful site links: + +- [Getting started](https://ajv.js.org/guide/getting-started.html) +- [JSON Schema vs JSON Type Definition](https://ajv.js.org/guide/schema-language.html) +- [API reference](https://ajv.js.org/api.html) +- [Strict mode](https://ajv.js.org/strict-mode.html) +- [Standalone validation code](https://ajv.js.org/standalone.html) +- [Security considerations](https://ajv.js.org/security.html) +- [Command line interface](https://ajv.js.org/packages/ajv-cli.html) +- [Frequently Asked Questions](https://ajv.js.org/faq.html) + +## Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin) + +Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant! + +Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released. + +Please sponsor Ajv via: + +- [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it) +- [Ajv Open Collective](https://opencollective.com/ajv) + +Thank you. + +#### Open Collective sponsors + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Performance + +Ajv generates code to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. + +Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: + +- [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place +- [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster +- [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) +- [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) + +Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): + +[![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=62,4,1&chs=600x416&chxl=-1:|ajv|@exodus/schemasafe|is-my-json-valid|djv|@cfworker/json-schema|jsonschema/=t:100,69.2,51.5,13.1,5.1,1.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) + +## Features + +- Ajv implements JSON Schema [draft-06/07/2019-09/2020-12](http://json-schema.org/) standards (draft-04 is supported in v6): + - all validation keywords (see [JSON Schema validation keywords](https://ajv.js.org/json-schema.html)) + - [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md) extensions: + - NEW: keyword [discriminator](https://ajv.js.org/json-schema.html#discriminator). + - keyword [nullable](https://ajv.js.org/json-schema.html#nullable). + - full support of remote references (remote schemas have to be added with `addSchema` or compiled to be available) + - support of recursive references between schemas + - correct string lengths for strings with unicode pairs + - JSON Schema [formats](https://ajv.js.org/guide/formats.html) (with [ajv-formats](https://github.com/ajv-validator/ajv-formats) plugin). + - [validates schemas against meta-schema](https://ajv.js.org/api.html#api-validateschema) +- NEW: supports [JSON Type Definition](https://datatracker.ietf.org/doc/rfc8927/): + - all keywords (see [JSON Type Definition schema forms](https://ajv.js.org/json-type-definition.html)) + - meta-schema for JTD schemas + - "union" keyword and user-defined keywords (can be used inside "metadata" member of the schema) +- supports [browsers](https://ajv.js.org/guide/environments.html#browsers) and Node.js 18.x - current +- [asynchronous loading](https://ajv.js.org/guide/managing-schemas.html#asynchronous-schema-loading) of referenced schemas during compilation +- "All errors" validation mode with [option allErrors](https://ajv.js.org/options.html#allerrors) +- [error messages with parameters](https://ajv.js.org/api.html#validation-errors) describing error reasons to allow error message generation +- i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package +- [removing-additional-properties](https://ajv.js.org/guide/modifying-data.html#removing-additional-properties) +- [assigning defaults](https://ajv.js.org/guide/modifying-data.html#assigning-defaults) to missing properties and items +- [coercing data](https://ajv.js.org/guide/modifying-data.html#coercing-data-types) to the types specified in `type` keywords +- [user-defined keywords](https://ajv.js.org/guide/user-keywords.html) +- additional extension keywords with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package +- [\$data reference](https://ajv.js.org/guide/combining-schemas.html#data-reference) to use values from the validated data as values for the schema keywords +- [asynchronous validation](https://ajv.js.org/guide/async-validation.html) of user-defined formats and keywords + +## Install + +To install version 8: + +``` +npm install ajv +``` + +## Getting started + +Try it in the Node.js REPL: https://runkit.com/npm/ajv + +In JavaScript: + +```javascript +// or ESM/TypeScript import +import Ajv from "ajv" +// Node.js require: +const Ajv = require("ajv") + +const ajv = new Ajv() // options can be passed, e.g. {allErrors: true} + +const schema = { + type: "object", + properties: { + foo: {type: "integer"}, + bar: {type: "string"}, + }, + required: ["foo"], + additionalProperties: false, +} + +const data = { + foo: 1, + bar: "abc", +} + +const validate = ajv.compile(schema) +const valid = validate(data) +if (!valid) console.log(validate.errors) +``` + +Learn how to use Ajv and see more examples in the [Guide: getting started](https://ajv.js.org/guide/getting-started.html) + +## Changes history + +See [https://github.com/ajv-validator/ajv/releases](https://github.com/ajv-validator/ajv/releases) + +**Please note**: [Changes in version 8.0.0](https://github.com/ajv-validator/ajv/releases/tag/v8.0.0) + +[Version 7.0.0](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0) + +[Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0). + +## Code of conduct + +Please review and follow the [Code of conduct](./CODE_OF_CONDUCT.md). + +Please report any unacceptable behaviour to ajv.validator@gmail.com - it will be reviewed by the project team. + +## Security contact + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues. + +## Open-source software support + +Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers. + +## License + +[MIT](./LICENSE) diff --git a/node_modules/ajv/lib/2019.ts b/node_modules/ajv/lib/2019.ts new file mode 100644 index 0000000000000000000000000000000000000000..3f7194f1bce5f23075cb95ba7e0191a716768e4f --- /dev/null +++ b/node_modules/ajv/lib/2019.ts @@ -0,0 +1,81 @@ +import type {AnySchemaObject} from "./types" +import AjvCore, {Options} from "./core" + +import draft7Vocabularies from "./vocabularies/draft7" +import dynamicVocabulary from "./vocabularies/dynamic" +import nextVocabulary from "./vocabularies/next" +import unevaluatedVocabulary from "./vocabularies/unevaluated" +import discriminator from "./vocabularies/discriminator" +import addMetaSchema2019 from "./refs/json-schema-2019-09" + +const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema" + +export class Ajv2019 extends AjvCore { + constructor(opts: Options = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true, + }) + } + + _addVocabularies(): void { + super._addVocabularies() + this.addVocabulary(dynamicVocabulary) + draft7Vocabularies.forEach((v) => this.addVocabulary(v)) + this.addVocabulary(nextVocabulary) + this.addVocabulary(unevaluatedVocabulary) + if (this.opts.discriminator) this.addKeyword(discriminator) + } + + _addDefaultMetaSchema(): void { + super._addDefaultMetaSchema() + const {$data, meta} = this.opts + if (!meta) return + addMetaSchema2019.call(this, $data) + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID + } + + defaultMeta(): string | AnySchemaObject | undefined { + return (this.opts.defaultMeta = + super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)) + } +} + +module.exports = exports = Ajv2019 +module.exports.Ajv2019 = Ajv2019 +Object.defineProperty(exports, "__esModule", {value: true}) + +export default Ajv2019 + +export { + Format, + FormatDefinition, + AsyncFormatDefinition, + KeywordDefinition, + KeywordErrorDefinition, + CodeKeywordDefinition, + MacroKeywordDefinition, + FuncKeywordDefinition, + Vocabulary, + Schema, + SchemaObject, + AnySchemaObject, + AsyncSchema, + AnySchema, + ValidateFunction, + AsyncValidateFunction, + ErrorObject, + ErrorNoParams, +} from "./types" + +export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core" +export {SchemaCxt, SchemaObjCxt} from "./compile" +export {KeywordCxt} from "./compile/validate" +export {DefinedError} from "./vocabularies/errors" +export {JSONType} from "./compile/rules" +export {JSONSchemaType} from "./types/json-schema" +export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen" +export {default as ValidationError} from "./runtime/validation_error" +export {default as MissingRefError} from "./compile/ref_error" diff --git a/node_modules/ajv/lib/2020.ts b/node_modules/ajv/lib/2020.ts new file mode 100644 index 0000000000000000000000000000000000000000..cfb36af9d7822ec5d2a1783806d85d16e018b6b8 --- /dev/null +++ b/node_modules/ajv/lib/2020.ts @@ -0,0 +1,75 @@ +import type {AnySchemaObject} from "./types" +import AjvCore, {Options} from "./core" + +import draft2020Vocabularies from "./vocabularies/draft2020" +import discriminator from "./vocabularies/discriminator" +import addMetaSchema2020 from "./refs/json-schema-2020-12" + +const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema" + +export class Ajv2020 extends AjvCore { + constructor(opts: Options = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true, + }) + } + + _addVocabularies(): void { + super._addVocabularies() + draft2020Vocabularies.forEach((v) => this.addVocabulary(v)) + if (this.opts.discriminator) this.addKeyword(discriminator) + } + + _addDefaultMetaSchema(): void { + super._addDefaultMetaSchema() + const {$data, meta} = this.opts + if (!meta) return + addMetaSchema2020.call(this, $data) + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID + } + + defaultMeta(): string | AnySchemaObject | undefined { + return (this.opts.defaultMeta = + super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)) + } +} + +module.exports = exports = Ajv2020 +module.exports.Ajv2020 = Ajv2020 +Object.defineProperty(exports, "__esModule", {value: true}) + +export default Ajv2020 + +export { + Format, + FormatDefinition, + AsyncFormatDefinition, + KeywordDefinition, + KeywordErrorDefinition, + CodeKeywordDefinition, + MacroKeywordDefinition, + FuncKeywordDefinition, + Vocabulary, + Schema, + SchemaObject, + AnySchemaObject, + AsyncSchema, + AnySchema, + ValidateFunction, + AsyncValidateFunction, + ErrorObject, + ErrorNoParams, +} from "./types" + +export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core" +export {SchemaCxt, SchemaObjCxt} from "./compile" +export {KeywordCxt} from "./compile/validate" +export {DefinedError} from "./vocabularies/errors" +export {JSONType} from "./compile/rules" +export {JSONSchemaType} from "./types/json-schema" +export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen" +export {default as ValidationError} from "./runtime/validation_error" +export {default as MissingRefError} from "./compile/ref_error" diff --git a/node_modules/ajv/lib/ajv.ts b/node_modules/ajv/lib/ajv.ts new file mode 100644 index 0000000000000000000000000000000000000000..8275b93a8ecea2cd36ebaaa5bc0255548de67428 --- /dev/null +++ b/node_modules/ajv/lib/ajv.ts @@ -0,0 +1,70 @@ +import type {AnySchemaObject} from "./types" +import AjvCore from "./core" +import draft7Vocabularies from "./vocabularies/draft7" +import discriminator from "./vocabularies/discriminator" +import * as draft7MetaSchema from "./refs/json-schema-draft-07.json" + +const META_SUPPORT_DATA = ["/properties"] + +const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema" + +export class Ajv extends AjvCore { + _addVocabularies(): void { + super._addVocabularies() + draft7Vocabularies.forEach((v) => this.addVocabulary(v)) + if (this.opts.discriminator) this.addKeyword(discriminator) + } + + _addDefaultMetaSchema(): void { + super._addDefaultMetaSchema() + if (!this.opts.meta) return + const metaSchema = this.opts.$data + ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) + : draft7MetaSchema + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false) + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID + } + + defaultMeta(): string | AnySchemaObject | undefined { + return (this.opts.defaultMeta = + super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)) + } +} + +module.exports = exports = Ajv +module.exports.Ajv = Ajv +Object.defineProperty(exports, "__esModule", {value: true}) + +export default Ajv + +export { + Format, + FormatDefinition, + AsyncFormatDefinition, + KeywordDefinition, + KeywordErrorDefinition, + CodeKeywordDefinition, + MacroKeywordDefinition, + FuncKeywordDefinition, + Vocabulary, + Schema, + SchemaObject, + AnySchemaObject, + AsyncSchema, + AnySchema, + ValidateFunction, + AsyncValidateFunction, + SchemaValidateFunction, + ErrorObject, + ErrorNoParams, +} from "./types" + +export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core" +export {SchemaCxt, SchemaObjCxt} from "./compile" +export {KeywordCxt} from "./compile/validate" +export {DefinedError} from "./vocabularies/errors" +export {JSONType} from "./compile/rules" +export {JSONSchemaType} from "./types/json-schema" +export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen" +export {default as ValidationError} from "./runtime/validation_error" +export {default as MissingRefError} from "./compile/ref_error" diff --git a/node_modules/ajv/lib/compile/codegen/code.ts b/node_modules/ajv/lib/compile/codegen/code.ts new file mode 100644 index 0000000000000000000000000000000000000000..9d4de6149f9451273ae7e3ca547cb69baed7877c --- /dev/null +++ b/node_modules/ajv/lib/compile/codegen/code.ts @@ -0,0 +1,169 @@ +// eslint-disable-next-line @typescript-eslint/no-extraneous-class +export abstract class _CodeOrName { + abstract readonly str: string + abstract readonly names: UsedNames + abstract toString(): string + abstract emptyStr(): boolean +} + +export const IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i + +export class Name extends _CodeOrName { + readonly str: string + constructor(s: string) { + super() + if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier") + this.str = s + } + + toString(): string { + return this.str + } + + emptyStr(): boolean { + return false + } + + get names(): UsedNames { + return {[this.str]: 1} + } +} + +export class _Code extends _CodeOrName { + readonly _items: readonly CodeItem[] + private _str?: string + private _names?: UsedNames + + constructor(code: string | readonly CodeItem[]) { + super() + this._items = typeof code === "string" ? [code] : code + } + + toString(): string { + return this.str + } + + emptyStr(): boolean { + if (this._items.length > 1) return false + const item = this._items[0] + return item === "" || item === '""' + } + + get str(): string { + return (this._str ??= this._items.reduce((s: string, c: CodeItem) => `${s}${c}`, "")) + } + + get names(): UsedNames { + return (this._names ??= this._items.reduce((names: UsedNames, c) => { + if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1 + return names + }, {})) + } +} + +export type CodeItem = Name | string | number | boolean | null + +export type UsedNames = Record + +export type Code = _Code | Name + +export type SafeExpr = Code | number | boolean | null + +export const nil = new _Code("") + +type CodeArg = SafeExpr | string | undefined + +export function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code { + const code: CodeItem[] = [strs[0]] + let i = 0 + while (i < args.length) { + addCodeArg(code, args[i]) + code.push(strs[++i]) + } + return new _Code(code) +} + +const plus = new _Code("+") + +export function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code { + const expr: CodeItem[] = [safeStringify(strs[0])] + let i = 0 + while (i < args.length) { + expr.push(plus) + addCodeArg(expr, args[i]) + expr.push(plus, safeStringify(strs[++i])) + } + optimize(expr) + return new _Code(expr) +} + +export function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void { + if (arg instanceof _Code) code.push(...arg._items) + else if (arg instanceof Name) code.push(arg) + else code.push(interpolate(arg)) +} + +function optimize(expr: CodeItem[]): void { + let i = 1 + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]) + if (res !== undefined) { + expr.splice(i - 1, 3, res) + continue + } + expr[i++] = "+" + } + i++ + } +} + +function mergeExprItems(a: CodeItem, b: CodeItem): CodeItem | undefined { + if (b === '""') return a + if (a === '""') return b + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== '"') return + if (typeof b != "string") return `${a.slice(0, -1)}${b}"` + if (b[0] === '"') return a.slice(0, -1) + b.slice(1) + return + } + if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}` + return +} + +export function strConcat(c1: Code, c2: Code): Code { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}` +} + +// TODO do not allow arrays here +function interpolate(x?: string | string[] | number | boolean | null): SafeExpr | string { + return typeof x == "number" || typeof x == "boolean" || x === null + ? x + : safeStringify(Array.isArray(x) ? x.join(",") : x) +} + +export function stringify(x: unknown): Code { + return new _Code(safeStringify(x)) +} + +export function safeStringify(x: unknown): string { + return JSON.stringify(x) + .replace(/\u2028/g, "\\u2028") + .replace(/\u2029/g, "\\u2029") +} + +export function getProperty(key: Code | string | number): Code { + return typeof key == "string" && IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]` +} + +//Does best effort to format the name properly +export function getEsmExportName(key: Code | string | number): Code { + if (typeof key == "string" && IDENTIFIER.test(key)) { + return new _Code(`${key}`) + } + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`) +} + +export function regexpCode(rx: RegExp): Code { + return new _Code(rx.toString()) +} diff --git a/node_modules/ajv/lib/compile/codegen/index.ts b/node_modules/ajv/lib/compile/codegen/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..5a6d1ee58c106245ba8a1b56f929fe3a23f337b8 --- /dev/null +++ b/node_modules/ajv/lib/compile/codegen/index.ts @@ -0,0 +1,852 @@ +import type {ScopeValueSets, NameValue, ValueScope, ValueScopeName} from "./scope" +import {_, nil, _Code, Code, Name, UsedNames, CodeItem, addCodeArg, _CodeOrName} from "./code" +import {Scope, varKinds} from "./scope" + +export {_, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code} from "./code" +export {Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds} from "./scope" + +// type for expressions that can be safely inserted in code without quotes +export type SafeExpr = Code | number | boolean | null + +// type that is either Code of function that adds code to CodeGen instance using its methods +export type Block = Code | (() => void) + +export const operators = { + GT: new _Code(">"), + GTE: new _Code(">="), + LT: new _Code("<"), + LTE: new _Code("<="), + EQ: new _Code("==="), + NEQ: new _Code("!=="), + NOT: new _Code("!"), + OR: new _Code("||"), + AND: new _Code("&&"), + ADD: new _Code("+"), +} + +abstract class Node { + abstract readonly names: UsedNames + + optimizeNodes(): this | ChildNode | ChildNode[] | undefined { + return this + } + + optimizeNames(_names: UsedNames, _constants: Constants): this | undefined { + return this + } + + // get count(): number { + // return 1 + // } +} + +class Def extends Node { + constructor( + private readonly varKind: Name, + private readonly name: Name, + private rhs?: SafeExpr + ) { + super() + } + + render({es5, _n}: CGOptions): string { + const varKind = es5 ? varKinds.var : this.varKind + const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}` + return `${varKind} ${this.name}${rhs};` + _n + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + if (!names[this.name.str]) return + if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants) + return this + } + + get names(): UsedNames { + return this.rhs instanceof _CodeOrName ? this.rhs.names : {} + } +} + +class Assign extends Node { + constructor( + readonly lhs: Code, + public rhs: SafeExpr, + private readonly sideEffects?: boolean + ) { + super() + } + + render({_n}: CGOptions): string { + return `${this.lhs} = ${this.rhs};` + _n + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return + this.rhs = optimizeExpr(this.rhs, names, constants) + return this + } + + get names(): UsedNames { + const names = this.lhs instanceof Name ? {} : {...this.lhs.names} + return addExprNames(names, this.rhs) + } +} + +class AssignOp extends Assign { + constructor( + lhs: Code, + private readonly op: Code, + rhs: SafeExpr, + sideEffects?: boolean + ) { + super(lhs, rhs, sideEffects) + } + + render({_n}: CGOptions): string { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n + } +} + +class Label extends Node { + readonly names: UsedNames = {} + constructor(readonly label: Name) { + super() + } + + render({_n}: CGOptions): string { + return `${this.label}:` + _n + } +} + +class Break extends Node { + readonly names: UsedNames = {} + constructor(readonly label?: Code) { + super() + } + + render({_n}: CGOptions): string { + const label = this.label ? ` ${this.label}` : "" + return `break${label};` + _n + } +} + +class Throw extends Node { + constructor(readonly error: Code) { + super() + } + + render({_n}: CGOptions): string { + return `throw ${this.error};` + _n + } + + get names(): UsedNames { + return this.error.names + } +} + +class AnyCode extends Node { + constructor(private code: SafeExpr) { + super() + } + + render({_n}: CGOptions): string { + return `${this.code};` + _n + } + + optimizeNodes(): this | undefined { + return `${this.code}` ? this : undefined + } + + optimizeNames(names: UsedNames, constants: Constants): this { + this.code = optimizeExpr(this.code, names, constants) + return this + } + + get names(): UsedNames { + return this.code instanceof _CodeOrName ? this.code.names : {} + } +} + +abstract class ParentNode extends Node { + constructor(readonly nodes: ChildNode[] = []) { + super() + } + + render(opts: CGOptions): string { + return this.nodes.reduce((code, n) => code + n.render(opts), "") + } + + optimizeNodes(): this | ChildNode | ChildNode[] | undefined { + const {nodes} = this + let i = nodes.length + while (i--) { + const n = nodes[i].optimizeNodes() + if (Array.isArray(n)) nodes.splice(i, 1, ...n) + else if (n) nodes[i] = n + else nodes.splice(i, 1) + } + return nodes.length > 0 ? this : undefined + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + const {nodes} = this + let i = nodes.length + while (i--) { + // iterating backwards improves 1-pass optimization + const n = nodes[i] + if (n.optimizeNames(names, constants)) continue + subtractNames(names, n.names) + nodes.splice(i, 1) + } + return nodes.length > 0 ? this : undefined + } + + get names(): UsedNames { + return this.nodes.reduce((names: UsedNames, n) => addNames(names, n.names), {}) + } + + // get count(): number { + // return this.nodes.reduce((c, n) => c + n.count, 1) + // } +} + +abstract class BlockNode extends ParentNode { + render(opts: CGOptions): string { + return "{" + opts._n + super.render(opts) + "}" + opts._n + } +} + +class Root extends ParentNode {} + +class Else extends BlockNode { + static readonly kind = "else" +} + +class If extends BlockNode { + static readonly kind = "if" + else?: If | Else + constructor( + private condition: Code | boolean, + nodes?: ChildNode[] + ) { + super(nodes) + } + + render(opts: CGOptions): string { + let code = `if(${this.condition})` + super.render(opts) + if (this.else) code += "else " + this.else.render(opts) + return code + } + + optimizeNodes(): If | ChildNode[] | undefined { + super.optimizeNodes() + const cond = this.condition + if (cond === true) return this.nodes // else is ignored here + let e = this.else + if (e) { + const ns = e.optimizeNodes() + e = this.else = Array.isArray(ns) ? new Else(ns) : (ns as Else | undefined) + } + if (e) { + if (cond === false) return e instanceof If ? e : e.nodes + if (this.nodes.length) return this + return new If(not(cond), e instanceof If ? [e] : e.nodes) + } + if (cond === false || !this.nodes.length) return undefined + return this + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + this.else = this.else?.optimizeNames(names, constants) + if (!(super.optimizeNames(names, constants) || this.else)) return + this.condition = optimizeExpr(this.condition, names, constants) + return this + } + + get names(): UsedNames { + const names = super.names + addExprNames(names, this.condition) + if (this.else) addNames(names, this.else.names) + return names + } + + // get count(): number { + // return super.count + (this.else?.count || 0) + // } +} + +abstract class For extends BlockNode { + static readonly kind = "for" +} + +class ForLoop extends For { + constructor(private iteration: Code) { + super() + } + + render(opts: CGOptions): string { + return `for(${this.iteration})` + super.render(opts) + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + if (!super.optimizeNames(names, constants)) return + this.iteration = optimizeExpr(this.iteration, names, constants) + return this + } + + get names(): UsedNames { + return addNames(super.names, this.iteration.names) + } +} + +class ForRange extends For { + constructor( + private readonly varKind: Name, + private readonly name: Name, + private readonly from: SafeExpr, + private readonly to: SafeExpr + ) { + super() + } + + render(opts: CGOptions): string { + const varKind = opts.es5 ? varKinds.var : this.varKind + const {name, from, to} = this + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts) + } + + get names(): UsedNames { + const names = addExprNames(super.names, this.from) + return addExprNames(names, this.to) + } +} + +class ForIter extends For { + constructor( + private readonly loop: "of" | "in", + private readonly varKind: Name, + private readonly name: Name, + private iterable: Code + ) { + super() + } + + render(opts: CGOptions): string { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts) + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + if (!super.optimizeNames(names, constants)) return + this.iterable = optimizeExpr(this.iterable, names, constants) + return this + } + + get names(): UsedNames { + return addNames(super.names, this.iterable.names) + } +} + +class Func extends BlockNode { + static readonly kind = "func" + constructor( + public name: Name, + public args: Code, + public async?: boolean + ) { + super() + } + + render(opts: CGOptions): string { + const _async = this.async ? "async " : "" + return `${_async}function ${this.name}(${this.args})` + super.render(opts) + } +} + +class Return extends ParentNode { + static readonly kind = "return" + + render(opts: CGOptions): string { + return "return " + super.render(opts) + } +} + +class Try extends BlockNode { + catch?: Catch + finally?: Finally + + render(opts: CGOptions): string { + let code = "try" + super.render(opts) + if (this.catch) code += this.catch.render(opts) + if (this.finally) code += this.finally.render(opts) + return code + } + + optimizeNodes(): this { + super.optimizeNodes() + this.catch?.optimizeNodes() as Catch | undefined + this.finally?.optimizeNodes() as Finally | undefined + return this + } + + optimizeNames(names: UsedNames, constants: Constants): this { + super.optimizeNames(names, constants) + this.catch?.optimizeNames(names, constants) + this.finally?.optimizeNames(names, constants) + return this + } + + get names(): UsedNames { + const names = super.names + if (this.catch) addNames(names, this.catch.names) + if (this.finally) addNames(names, this.finally.names) + return names + } + + // get count(): number { + // return super.count + (this.catch?.count || 0) + (this.finally?.count || 0) + // } +} + +class Catch extends BlockNode { + static readonly kind = "catch" + constructor(readonly error: Name) { + super() + } + + render(opts: CGOptions): string { + return `catch(${this.error})` + super.render(opts) + } +} + +class Finally extends BlockNode { + static readonly kind = "finally" + render(opts: CGOptions): string { + return "finally" + super.render(opts) + } +} + +type StartBlockNode = If | For | Func | Return | Try + +type LeafNode = Def | Assign | Label | Break | Throw | AnyCode + +type ChildNode = StartBlockNode | LeafNode + +type EndBlockNodeType = + | typeof If + | typeof Else + | typeof For + | typeof Func + | typeof Return + | typeof Catch + | typeof Finally + +type Constants = Record + +export interface CodeGenOptions { + es5?: boolean + lines?: boolean + ownProperties?: boolean +} + +interface CGOptions extends CodeGenOptions { + _n: "\n" | "" +} + +export class CodeGen { + readonly _scope: Scope + readonly _extScope: ValueScope + readonly _values: ScopeValueSets = {} + private readonly _nodes: ParentNode[] + private readonly _blockStarts: number[] = [] + private readonly _constants: Constants = {} + private readonly opts: CGOptions + + constructor(extScope: ValueScope, opts: CodeGenOptions = {}) { + this.opts = {...opts, _n: opts.lines ? "\n" : ""} + this._extScope = extScope + this._scope = new Scope({parent: extScope}) + this._nodes = [new Root()] + } + + toString(): string { + return this._root.render(this.opts) + } + + // returns unique name in the internal scope + name(prefix: string): Name { + return this._scope.name(prefix) + } + + // reserves unique name in the external scope + scopeName(prefix: string): ValueScopeName { + return this._extScope.name(prefix) + } + + // reserves unique name in the external scope and assigns value to it + scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name { + const name = this._extScope.value(prefixOrName, value) + const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set()) + vs.add(name) + return name + } + + getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined { + return this._extScope.getValue(prefix, keyOrRef) + } + + // return code that assigns values in the external scope to the names that are used internally + // (same names that were returned by gen.scopeName or gen.scopeValue) + scopeRefs(scopeName: Name): Code { + return this._extScope.scopeRefs(scopeName, this._values) + } + + scopeCode(): Code { + return this._extScope.scopeCode(this._values) + } + + private _def( + varKind: Name, + nameOrPrefix: Name | string, + rhs?: SafeExpr, + constant?: boolean + ): Name { + const name = this._scope.toName(nameOrPrefix) + if (rhs !== undefined && constant) this._constants[name.str] = rhs + this._leafNode(new Def(varKind, name, rhs)) + return name + } + + // `const` declaration (`var` in es5 mode) + const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name { + return this._def(varKinds.const, nameOrPrefix, rhs, _constant) + } + + // `let` declaration with optional assignment (`var` in es5 mode) + let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name { + return this._def(varKinds.let, nameOrPrefix, rhs, _constant) + } + + // `var` declaration with optional assignment + var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name { + return this._def(varKinds.var, nameOrPrefix, rhs, _constant) + } + + // assignment code + assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen { + return this._leafNode(new Assign(lhs, rhs, sideEffects)) + } + + // `+=` code + add(lhs: Code, rhs: SafeExpr): CodeGen { + return this._leafNode(new AssignOp(lhs, operators.ADD, rhs)) + } + + // appends passed SafeExpr to code or executes Block + code(c: Block | SafeExpr): CodeGen { + if (typeof c == "function") c() + else if (c !== nil) this._leafNode(new AnyCode(c)) + return this + } + + // returns code for object literal for the passed argument list of key-value pairs + object(...keyValues: [Name | string, SafeExpr | string][]): _Code { + const code: CodeItem[] = ["{"] + for (const [key, value] of keyValues) { + if (code.length > 1) code.push(",") + code.push(key) + if (key !== value || this.opts.es5) { + code.push(":") + addCodeArg(code, value) + } + } + code.push("}") + return new _Code(code) + } + + // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) + if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen { + this._blockNode(new If(condition)) + + if (thenBody && elseBody) { + this.code(thenBody).else().code(elseBody).endIf() + } else if (thenBody) { + this.code(thenBody).endIf() + } else if (elseBody) { + throw new Error('CodeGen: "else" body without "then" body') + } + return this + } + + // `else if` clause - invalid without `if` or after `else` clauses + elseIf(condition: Code | boolean): CodeGen { + return this._elseNode(new If(condition)) + } + + // `else` clause - only valid after `if` or `else if` clauses + else(): CodeGen { + return this._elseNode(new Else()) + } + + // end `if` statement (needed if gen.if was used only with condition) + endIf(): CodeGen { + return this._endBlockNode(If, Else) + } + + private _for(node: For, forBody?: Block): CodeGen { + this._blockNode(node) + if (forBody) this.code(forBody).endFor() + return this + } + + // a generic `for` clause (or statement if `forBody` is passed) + for(iteration: Code, forBody?: Block): CodeGen { + return this._for(new ForLoop(iteration), forBody) + } + + // `for` statement for a range of values + forRange( + nameOrPrefix: Name | string, + from: SafeExpr, + to: SafeExpr, + forBody: (index: Name) => void, + varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let + ): CodeGen { + const name = this._scope.toName(nameOrPrefix) + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)) + } + + // `for-of` statement (in es5 mode replace with a normal for loop) + forOf( + nameOrPrefix: Name | string, + iterable: Code, + forBody: (item: Name) => void, + varKind: Code = varKinds.const + ): CodeGen { + const name = this._scope.toName(nameOrPrefix) + if (this.opts.es5) { + const arr = iterable instanceof Name ? iterable : this.var("_arr", iterable) + return this.forRange("_i", 0, _`${arr}.length`, (i) => { + this.var(name, _`${arr}[${i}]`) + forBody(name) + }) + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)) + } + + // `for-in` statement. + // With option `ownProperties` replaced with a `for-of` loop for object keys + forIn( + nameOrPrefix: Name | string, + obj: Code, + forBody: (item: Name) => void, + varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const + ): CodeGen { + if (this.opts.ownProperties) { + return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody) + } + const name = this._scope.toName(nameOrPrefix) + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)) + } + + // end `for` loop + endFor(): CodeGen { + return this._endBlockNode(For) + } + + // `label` statement + label(label: Name): CodeGen { + return this._leafNode(new Label(label)) + } + + // `break` statement + break(label?: Code): CodeGen { + return this._leafNode(new Break(label)) + } + + // `return` statement + return(value: Block | SafeExpr): CodeGen { + const node = new Return() + this._blockNode(node) + this.code(value) + if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node') + return this._endBlockNode(Return) + } + + // `try` statement + try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen { + if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"') + const node = new Try() + this._blockNode(node) + this.code(tryBody) + if (catchCode) { + const error = this.name("e") + this._currNode = node.catch = new Catch(error) + catchCode(error) + } + if (finallyCode) { + this._currNode = node.finally = new Finally() + this.code(finallyCode) + } + return this._endBlockNode(Catch, Finally) + } + + // `throw` statement + throw(error: Code): CodeGen { + return this._leafNode(new Throw(error)) + } + + // start self-balancing block + block(body?: Block, nodeCount?: number): CodeGen { + this._blockStarts.push(this._nodes.length) + if (body) this.code(body).endBlock(nodeCount) + return this + } + + // end the current self-balancing block + endBlock(nodeCount?: number): CodeGen { + const len = this._blockStarts.pop() + if (len === undefined) throw new Error("CodeGen: not in self-balancing block") + const toClose = this._nodes.length - len + if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) { + throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`) + } + this._nodes.length = len + return this + } + + // `function` heading (or definition if funcBody is passed) + func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen { + this._blockNode(new Func(name, args, async)) + if (funcBody) this.code(funcBody).endFunc() + return this + } + + // end function definition + endFunc(): CodeGen { + return this._endBlockNode(Func) + } + + optimize(n = 1): void { + while (n-- > 0) { + this._root.optimizeNodes() + this._root.optimizeNames(this._root.names, this._constants) + } + } + + private _leafNode(node: LeafNode): CodeGen { + this._currNode.nodes.push(node) + return this + } + + private _blockNode(node: StartBlockNode): void { + this._currNode.nodes.push(node) + this._nodes.push(node) + } + + private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen { + const n = this._currNode + if (n instanceof N1 || (N2 && n instanceof N2)) { + this._nodes.pop() + return this + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`) + } + + private _elseNode(node: If | Else): CodeGen { + const n = this._currNode + if (!(n instanceof If)) { + throw new Error('CodeGen: "else" without "if"') + } + this._currNode = n.else = node + return this + } + + private get _root(): Root { + return this._nodes[0] as Root + } + + private get _currNode(): ParentNode { + const ns = this._nodes + return ns[ns.length - 1] + } + + private set _currNode(node: ParentNode) { + const ns = this._nodes + ns[ns.length - 1] = node + } + + // get nodeCount(): number { + // return this._root.count + // } +} + +function addNames(names: UsedNames, from: UsedNames): UsedNames { + for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0) + return names +} + +function addExprNames(names: UsedNames, from: SafeExpr): UsedNames { + return from instanceof _CodeOrName ? addNames(names, from.names) : names +} + +function optimizeExpr(expr: T, names: UsedNames, constants: Constants): T +function optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr { + if (expr instanceof Name) return replaceName(expr) + if (!canOptimize(expr)) return expr + return new _Code( + expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => { + if (c instanceof Name) c = replaceName(c) + if (c instanceof _Code) items.push(...c._items) + else items.push(c) + return items + }, []) + ) + + function replaceName(n: Name): SafeExpr { + const c = constants[n.str] + if (c === undefined || names[n.str] !== 1) return n + delete names[n.str] + return c + } + + function canOptimize(e: SafeExpr): e is _Code { + return ( + e instanceof _Code && + e._items.some( + (c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined + ) + ) + } +} + +function subtractNames(names: UsedNames, from: UsedNames): void { + for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0) +} + +export function not(x: T): T +export function not(x: Code | SafeExpr): Code | SafeExpr { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : _`!${par(x)}` +} + +const andCode = mappend(operators.AND) + +// boolean AND (&&) expression with the passed arguments +export function and(...args: Code[]): Code { + return args.reduce(andCode) +} + +const orCode = mappend(operators.OR) + +// boolean OR (||) expression with the passed arguments +export function or(...args: Code[]): Code { + return args.reduce(orCode) +} + +type MAppend = (x: Code, y: Code) => Code + +function mappend(op: Code): MAppend { + return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`) +} + +function par(x: Code): Code { + return x instanceof Name ? x : _`(${x})` +} diff --git a/node_modules/ajv/lib/compile/codegen/scope.ts b/node_modules/ajv/lib/compile/codegen/scope.ts new file mode 100644 index 0000000000000000000000000000000000000000..511992297d08f661ef4cf826eba9fbdbf0854db0 --- /dev/null +++ b/node_modules/ajv/lib/compile/codegen/scope.ts @@ -0,0 +1,215 @@ +import {_, nil, Code, Name} from "./code" + +interface NameGroup { + prefix: string + index: number +} + +export interface NameValue { + ref: ValueReference // this is the reference to any value that can be referred to from generated code via `globals` var in the closure + key?: unknown // any key to identify a global to avoid duplicates, if not passed ref is used + code?: Code // this is the code creating the value needed for standalone code wit_out closure - can be a primitive value, function or import (`require`) +} + +export type ValueReference = unknown // possibly make CodeGen parameterized type on this type + +class ValueError extends Error { + readonly value?: NameValue + constructor(name: ValueScopeName) { + super(`CodeGen: "code" for ${name} not defined`) + this.value = name.value + } +} + +interface ScopeOptions { + prefixes?: Set + parent?: Scope +} + +interface ValueScopeOptions extends ScopeOptions { + scope: ScopeStore + es5?: boolean + lines?: boolean +} + +export type ScopeStore = Record + +type ScopeValues = { + [Prefix in string]?: Map +} + +export type ScopeValueSets = { + [Prefix in string]?: Set +} + +export enum UsedValueState { + Started, + Completed, +} + +export type UsedScopeValues = { + [Prefix in string]?: Map +} + +export const varKinds = { + const: new Name("const"), + let: new Name("let"), + var: new Name("var"), +} + +export class Scope { + protected readonly _names: {[Prefix in string]?: NameGroup} = {} + protected readonly _prefixes?: Set + protected readonly _parent?: Scope + + constructor({prefixes, parent}: ScopeOptions = {}) { + this._prefixes = prefixes + this._parent = parent + } + + toName(nameOrPrefix: Name | string): Name { + return nameOrPrefix instanceof Name ? nameOrPrefix : this.name(nameOrPrefix) + } + + name(prefix: string): Name { + return new Name(this._newName(prefix)) + } + + protected _newName(prefix: string): string { + const ng = this._names[prefix] || this._nameGroup(prefix) + return `${prefix}${ng.index++}` + } + + private _nameGroup(prefix: string): NameGroup { + if (this._parent?._prefixes?.has(prefix) || (this._prefixes && !this._prefixes.has(prefix))) { + throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`) + } + return (this._names[prefix] = {prefix, index: 0}) + } +} + +interface ScopePath { + property: string + itemIndex: number +} + +export class ValueScopeName extends Name { + readonly prefix: string + value?: NameValue + scopePath?: Code + + constructor(prefix: string, nameStr: string) { + super(nameStr) + this.prefix = prefix + } + + setValue(value: NameValue, {property, itemIndex}: ScopePath): void { + this.value = value + this.scopePath = _`.${new Name(property)}[${itemIndex}]` + } +} + +interface VSOptions extends ValueScopeOptions { + _n: Code +} + +const line = _`\n` + +export class ValueScope extends Scope { + protected readonly _values: ScopeValues = {} + protected readonly _scope: ScopeStore + readonly opts: VSOptions + + constructor(opts: ValueScopeOptions) { + super(opts) + this._scope = opts.scope + this.opts = {...opts, _n: opts.lines ? line : nil} + } + + get(): ScopeStore { + return this._scope + } + + name(prefix: string): ValueScopeName { + return new ValueScopeName(prefix, this._newName(prefix)) + } + + value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName { + if (value.ref === undefined) throw new Error("CodeGen: ref must be passed in value") + const name = this.toName(nameOrPrefix) as ValueScopeName + const {prefix} = name + const valueKey = value.key ?? value.ref + let vs = this._values[prefix] + if (vs) { + const _name = vs.get(valueKey) + if (_name) return _name + } else { + vs = this._values[prefix] = new Map() + } + vs.set(valueKey, name) + + const s = this._scope[prefix] || (this._scope[prefix] = []) + const itemIndex = s.length + s[itemIndex] = value.ref + name.setValue(value, {property: prefix, itemIndex}) + return name + } + + getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined { + const vs = this._values[prefix] + if (!vs) return + return vs.get(keyOrRef) + } + + scopeRefs(scopeName: Name, values: ScopeValues | ScopeValueSets = this._values): Code { + return this._reduceValues(values, (name: ValueScopeName) => { + if (name.scopePath === undefined) throw new Error(`CodeGen: name "${name}" has no value`) + return _`${scopeName}${name.scopePath}` + }) + } + + scopeCode( + values: ScopeValues | ScopeValueSets = this._values, + usedValues?: UsedScopeValues, + getCode?: (n: ValueScopeName) => Code | undefined + ): Code { + return this._reduceValues( + values, + (name: ValueScopeName) => { + if (name.value === undefined) throw new Error(`CodeGen: name "${name}" has no value`) + return name.value.code + }, + usedValues, + getCode + ) + } + + private _reduceValues( + values: ScopeValues | ScopeValueSets, + valueCode: (n: ValueScopeName) => Code | undefined, + usedValues: UsedScopeValues = {}, + getCode?: (n: ValueScopeName) => Code | undefined + ): Code { + let code: Code = nil + for (const prefix in values) { + const vs = values[prefix] + if (!vs) continue + const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map()) + vs.forEach((name: ValueScopeName) => { + if (nameSet.has(name)) return + nameSet.set(name, UsedValueState.Started) + let c = valueCode(name) + if (c) { + const def = this.opts.es5 ? varKinds.var : varKinds.const + code = _`${code}${def} ${name} = ${c};${this.opts._n}` + } else if ((c = getCode?.(name))) { + code = _`${code}${c}${this.opts._n}` + } else { + throw new ValueError(name) + } + nameSet.set(name, UsedValueState.Completed) + }) + } + return code + } +} diff --git a/node_modules/ajv/lib/compile/errors.ts b/node_modules/ajv/lib/compile/errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..18424a0fc62917fa720aee28e97280865f8bf1f5 --- /dev/null +++ b/node_modules/ajv/lib/compile/errors.ts @@ -0,0 +1,184 @@ +import type {KeywordErrorCxt, KeywordErrorDefinition} from "../types" +import type {SchemaCxt} from "./index" +import {CodeGen, _, str, strConcat, Code, Name} from "./codegen" +import {SafeExpr} from "./codegen/code" +import {getErrorPath, Type} from "./util" +import N from "./names" + +export const keywordError: KeywordErrorDefinition = { + message: ({keyword}) => str`must pass "${keyword}" keyword validation`, +} + +export const keyword$DataError: KeywordErrorDefinition = { + message: ({keyword, schemaType}) => + schemaType + ? str`"${keyword}" keyword must be ${schemaType} ($data)` + : str`"${keyword}" keyword is invalid ($data)`, +} + +export interface ErrorPaths { + instancePath?: Code + schemaPath?: string + parentSchema?: boolean +} + +export function reportError( + cxt: KeywordErrorCxt, + error: KeywordErrorDefinition = keywordError, + errorPaths?: ErrorPaths, + overrideAllErrors?: boolean +): void { + const {it} = cxt + const {gen, compositeRule, allErrors} = it + const errObj = errorObjectCode(cxt, error, errorPaths) + if (overrideAllErrors ?? (compositeRule || allErrors)) { + addError(gen, errObj) + } else { + returnErrors(it, _`[${errObj}]`) + } +} + +export function reportExtraError( + cxt: KeywordErrorCxt, + error: KeywordErrorDefinition = keywordError, + errorPaths?: ErrorPaths +): void { + const {it} = cxt + const {gen, compositeRule, allErrors} = it + const errObj = errorObjectCode(cxt, error, errorPaths) + addError(gen, errObj) + if (!(compositeRule || allErrors)) { + returnErrors(it, N.vErrors) + } +} + +export function resetErrorsCount(gen: CodeGen, errsCount: Name): void { + gen.assign(N.errors, errsCount) + gen.if(_`${N.vErrors} !== null`, () => + gen.if( + errsCount, + () => gen.assign(_`${N.vErrors}.length`, errsCount), + () => gen.assign(N.vErrors, null) + ) + ) +} + +export function extendErrors({ + gen, + keyword, + schemaValue, + data, + errsCount, + it, +}: KeywordErrorCxt): void { + /* istanbul ignore if */ + if (errsCount === undefined) throw new Error("ajv implementation error") + const err = gen.name("err") + gen.forRange("i", errsCount, N.errors, (i) => { + gen.const(err, _`${N.vErrors}[${i}]`) + gen.if(_`${err}.instancePath === undefined`, () => + gen.assign(_`${err}.instancePath`, strConcat(N.instancePath, it.errorPath)) + ) + gen.assign(_`${err}.schemaPath`, str`${it.errSchemaPath}/${keyword}`) + if (it.opts.verbose) { + gen.assign(_`${err}.schema`, schemaValue) + gen.assign(_`${err}.data`, data) + } + }) +} + +function addError(gen: CodeGen, errObj: Code): void { + const err = gen.const("err", errObj) + gen.if( + _`${N.vErrors} === null`, + () => gen.assign(N.vErrors, _`[${err}]`), + _`${N.vErrors}.push(${err})` + ) + gen.code(_`${N.errors}++`) +} + +function returnErrors(it: SchemaCxt, errs: Code): void { + const {gen, validateName, schemaEnv} = it + if (schemaEnv.$async) { + gen.throw(_`new ${it.ValidationError as Name}(${errs})`) + } else { + gen.assign(_`${validateName}.errors`, errs) + gen.return(false) + } +} + +const E = { + keyword: new Name("keyword"), + schemaPath: new Name("schemaPath"), // also used in JTD errors + params: new Name("params"), + propertyName: new Name("propertyName"), + message: new Name("message"), + schema: new Name("schema"), + parentSchema: new Name("parentSchema"), +} + +function errorObjectCode( + cxt: KeywordErrorCxt, + error: KeywordErrorDefinition, + errorPaths?: ErrorPaths +): Code { + const {createErrors} = cxt.it + if (createErrors === false) return _`{}` + return errorObject(cxt, error, errorPaths) +} + +function errorObject( + cxt: KeywordErrorCxt, + error: KeywordErrorDefinition, + errorPaths: ErrorPaths = {} +): Code { + const {gen, it} = cxt + const keyValues: [Name, SafeExpr | string][] = [ + errorInstancePath(it, errorPaths), + errorSchemaPath(cxt, errorPaths), + ] + extraErrorProps(cxt, error, keyValues) + return gen.object(...keyValues) +} + +function errorInstancePath({errorPath}: SchemaCxt, {instancePath}: ErrorPaths): [Name, Code] { + const instPath = instancePath + ? str`${errorPath}${getErrorPath(instancePath, Type.Str)}` + : errorPath + return [N.instancePath, strConcat(N.instancePath, instPath)] +} + +function errorSchemaPath( + {keyword, it: {errSchemaPath}}: KeywordErrorCxt, + {schemaPath, parentSchema}: ErrorPaths +): [Name, string | Code] { + let schPath = parentSchema ? errSchemaPath : str`${errSchemaPath}/${keyword}` + if (schemaPath) { + schPath = str`${schPath}${getErrorPath(schemaPath, Type.Str)}` + } + return [E.schemaPath, schPath] +} + +function extraErrorProps( + cxt: KeywordErrorCxt, + {params, message}: KeywordErrorDefinition, + keyValues: [Name, SafeExpr | string][] +): void { + const {keyword, data, schemaValue, it} = cxt + const {opts, propertyName, topSchemaRef, schemaPath} = it + keyValues.push( + [E.keyword, keyword], + [E.params, typeof params == "function" ? params(cxt) : params || _`{}`] + ) + if (opts.messages) { + keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]) + } + if (opts.verbose) { + keyValues.push( + [E.schema, schemaValue], + [E.parentSchema, _`${topSchemaRef}${schemaPath}`], + [N.data, data] + ) + } + if (propertyName) keyValues.push([E.propertyName, propertyName]) +} diff --git a/node_modules/ajv/lib/compile/index.ts b/node_modules/ajv/lib/compile/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfc39345526afe62f8c1d52eabf5b25b7959537f --- /dev/null +++ b/node_modules/ajv/lib/compile/index.ts @@ -0,0 +1,324 @@ +import type { + AnySchema, + AnySchemaObject, + AnyValidateFunction, + AsyncValidateFunction, + EvaluatedProperties, + EvaluatedItems, +} from "../types" +import type Ajv from "../core" +import type {InstanceOptions} from "../core" +import {CodeGen, _, nil, stringify, Name, Code, ValueScopeName} from "./codegen" +import ValidationError from "../runtime/validation_error" +import N from "./names" +import {LocalRefs, getFullPath, _getFullPath, inlineRef, normalizeId, resolveUrl} from "./resolve" +import {schemaHasRulesButRef, unescapeFragment} from "./util" +import {validateFunctionCode} from "./validate" +import {URIComponent} from "fast-uri" +import {JSONType} from "./rules" + +export type SchemaRefs = { + [Ref in string]?: SchemaEnv | AnySchema +} + +export interface SchemaCxt { + readonly gen: CodeGen + readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error + readonly data: Name // Name with reference to the current part of data instance + readonly parentData: Name // should be used in keywords modifying data + readonly parentDataProperty: Code | number // should be used in keywords modifying data + readonly dataNames: Name[] + readonly dataPathArr: (Code | number)[] + readonly dataLevel: number // the level of the currently validated data, + // it can be used to access both the property names and the data on all levels from the top. + dataTypes: JSONType[] // data types applied to the current part of data instance + definedProperties: Set // set of properties to keep track of for required checks + readonly topSchemaRef: Code + readonly validateName: Name + evaluated?: Name + readonly ValidationError?: Name + readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt + readonly schemaEnv: SchemaEnv + readonly rootId: string + baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\$ref) + readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema + readonly errSchemaPath: string // this is actual string, should not be changed to Code + readonly errorPath: Code + readonly propertyName?: Name + readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword, + // where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`). + // This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true. + // You only need to use it if you have many steps in your keywords and potentially can define multiple errors. + props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function + items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function + jtdDiscriminator?: string + jtdMetadata?: boolean + readonly createErrors?: boolean + readonly opts: InstanceOptions // Ajv instance option. + readonly self: Ajv // current Ajv instance +} + +export interface SchemaObjCxt extends SchemaCxt { + readonly schema: AnySchemaObject +} +interface SchemaEnvArgs { + readonly schema: AnySchema + readonly schemaId?: "$id" | "id" + readonly root?: SchemaEnv + readonly baseId?: string + readonly schemaPath?: string + readonly localRefs?: LocalRefs + readonly meta?: boolean +} + +export class SchemaEnv implements SchemaEnvArgs { + readonly schema: AnySchema + readonly schemaId?: "$id" | "id" + readonly root: SchemaEnv + baseId: string // TODO possibly, it should be readonly + schemaPath?: string + localRefs?: LocalRefs + readonly meta?: boolean + readonly $async?: boolean // true if the current schema is asynchronous. + readonly refs: SchemaRefs = {} + readonly dynamicAnchors: {[Ref in string]?: true} = {} + validate?: AnyValidateFunction + validateName?: ValueScopeName + serialize?: (data: unknown) => string + serializeName?: ValueScopeName + parse?: (data: string) => unknown + parseName?: ValueScopeName + + constructor(env: SchemaEnvArgs) { + let schema: AnySchemaObject | undefined + if (typeof env.schema == "object") schema = env.schema + this.schema = env.schema + this.schemaId = env.schemaId + this.root = env.root || this + this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || "$id"]) + this.schemaPath = env.schemaPath + this.localRefs = env.localRefs + this.meta = env.meta + this.$async = schema?.$async + this.refs = {} + } +} + +// let codeSize = 0 +// let nodeCount = 0 + +// Compiles schema in SchemaEnv +export function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv { + // TODO refactor - remove compilations + const _sch = getCompilingSchema.call(this, sch) + if (_sch) return _sch + const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails + const {es5, lines} = this.opts.code + const {ownProperties} = this.opts + const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) + let _ValidationError + if (sch.$async) { + _ValidationError = gen.scopeValue("Error", { + ref: ValidationError, + code: _`require("ajv/dist/runtime/validation_error").default`, + }) + } + + const validateName = gen.scopeName("validate") + sch.validateName = validateName + + const schemaCxt: SchemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: N.data, + parentData: N.parentData, + parentDataProperty: N.parentDataProperty, + dataNames: [N.data], + dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed? + dataLevel: 0, + dataTypes: [], + definedProperties: new Set(), + topSchemaRef: gen.scopeValue( + "schema", + this.opts.code.source === true + ? {ref: sch.schema, code: stringify(sch.schema)} + : {ref: sch.schema} + ), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: _`""`, + opts: this.opts, + self: this, + } + + let sourceCode: string | undefined + try { + this._compilations.add(sch) + validateFunctionCode(schemaCxt) + gen.optimize(this.opts.code.optimize) + // gen.optimize(1) + const validateCode = gen.toString() + sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}` + // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount)) + if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch) + // console.log("\n\n\n *** \n", sourceCode) + const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode) + const validate: AnyValidateFunction = makeValidate(this, this.scope.get()) + this.scope.value(validateName, {ref: validate}) + + validate.errors = null + validate.schema = sch.schema + validate.schemaEnv = sch + if (sch.$async) (validate as AsyncValidateFunction).$async = true + if (this.opts.code.source === true) { + validate.source = {validateName, validateCode, scopeValues: gen._values} + } + if (this.opts.unevaluated) { + const {props, items} = schemaCxt + validate.evaluated = { + props: props instanceof Name ? undefined : props, + items: items instanceof Name ? undefined : items, + dynamicProps: props instanceof Name, + dynamicItems: items instanceof Name, + } + if (validate.source) validate.source.evaluated = stringify(validate.evaluated) + } + sch.validate = validate + return sch + } catch (e) { + delete sch.validate + delete sch.validateName + if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode) + // console.log("\n\n\n *** \n", sourceCode, this.opts) + throw e + } finally { + this._compilations.delete(sch) + } +} + +export function resolveRef( + this: Ajv, + root: SchemaEnv, + baseId: string, + ref: string +): AnySchema | SchemaEnv | undefined { + ref = resolveUrl(this.opts.uriResolver, baseId, ref) + const schOrFunc = root.refs[ref] + if (schOrFunc) return schOrFunc + + let _sch = resolve.call(this, root, ref) + if (_sch === undefined) { + const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv + const {schemaId} = this.opts + if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId}) + } + + if (_sch === undefined) return + return (root.refs[ref] = inlineOrCompile.call(this, _sch)) +} + +function inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv { + if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema + return sch.validate ? sch : compileSchema.call(this, sch) +} + +// Index of schema compilation in the currently compiled list +export function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void { + for (const sch of this._compilations) { + if (sameSchemaEnv(sch, schEnv)) return sch + } +} + +function sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId +} + +// resolve and compile the references ($ref) +// TODO returns AnySchemaObject (if the schema can be inlined) or validation function +function resolve( + this: Ajv, + root: SchemaEnv, // information about the root schema for the current schema + ref: string // reference to resolve +): SchemaEnv | undefined { + let sch + while (typeof (sch = this.refs[ref]) == "string") ref = sch + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref) +} + +// Resolve schema, its root and baseId +export function resolveSchema( + this: Ajv, + root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it + ref: string // reference to resolve +): SchemaEnv | undefined { + const p = this.opts.uriResolver.parse(ref) + const refPath = _getFullPath(this.opts.uriResolver, p) + let baseId = getFullPath(this.opts.uriResolver, root.baseId, undefined) + // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests + if (Object.keys(root.schema).length > 0 && refPath === baseId) { + return getJsonPointer.call(this, p, root) + } + + const id = normalizeId(refPath) + const schOrRef = this.refs[id] || this.schemas[id] + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef) + if (typeof sch?.schema !== "object") return + return getJsonPointer.call(this, p, sch) + } + + if (typeof schOrRef?.schema !== "object") return + if (!schOrRef.validate) compileSchema.call(this, schOrRef) + if (id === normalizeId(ref)) { + const {schema} = schOrRef + const {schemaId} = this.opts + const schId = schema[schemaId] + if (schId) baseId = resolveUrl(this.opts.uriResolver, baseId, schId) + return new SchemaEnv({schema, schemaId, root, baseId}) + } + return getJsonPointer.call(this, p, schOrRef) +} + +const PREVENT_SCOPE_CHANGE = new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions", +]) + +function getJsonPointer( + this: Ajv, + parsedRef: URIComponent, + {baseId, schema, root}: SchemaEnv +): SchemaEnv | undefined { + if (parsedRef.fragment?.[0] !== "/") return + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") return + const partSchema = schema[unescapeFragment(part)] + if (partSchema === undefined) return + schema = partSchema + // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def? + const schId = typeof schema === "object" && schema[this.opts.schemaId] + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { + baseId = resolveUrl(this.opts.uriResolver, baseId, schId) + } + } + let env: SchemaEnv | undefined + if (typeof schema != "boolean" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) { + const $ref = resolveUrl(this.opts.uriResolver, baseId, schema.$ref) + env = resolveSchema.call(this, root, $ref) + } + // even though resolution failed we need to return SchemaEnv to throw exception + // so that compileAsync loads missing schema. + const {schemaId} = this.opts + env = env || new SchemaEnv({schema, schemaId, root, baseId}) + if (env.schema !== env.root.schema) return env + return undefined +} diff --git a/node_modules/ajv/lib/compile/jtd/parse.ts b/node_modules/ajv/lib/compile/jtd/parse.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0141c770c7029ce1d41db61bcd9a19fbd0c08d5 --- /dev/null +++ b/node_modules/ajv/lib/compile/jtd/parse.ts @@ -0,0 +1,411 @@ +import type Ajv from "../../core" +import type {SchemaObject} from "../../types" +import {jtdForms, JTDForm, SchemaObjectMap} from "./types" +import {SchemaEnv, getCompilingSchema} from ".." +import {_, str, and, or, nil, not, CodeGen, Code, Name, SafeExpr} from "../codegen" +import MissingRefError from "../ref_error" +import N from "../names" +import {hasPropFunc} from "../../vocabularies/code" +import {hasRef} from "../../vocabularies/jtd/ref" +import {intRange, IntType} from "../../vocabularies/jtd/type" +import {parseJson, parseJsonNumber, parseJsonString} from "../../runtime/parseJson" +import {useFunc} from "../util" +import validTimestamp from "../../runtime/timestamp" + +type GenParse = (cxt: ParseCxt) => void + +const genParse: {[F in JTDForm]: GenParse} = { + elements: parseElements, + values: parseValues, + discriminator: parseDiscriminator, + properties: parseProperties, + optionalProperties: parseProperties, + enum: parseEnum, + type: parseType, + ref: parseRef, +} + +interface ParseCxt { + readonly gen: CodeGen + readonly self: Ajv // current Ajv instance + readonly schemaEnv: SchemaEnv + readonly definitions: SchemaObjectMap + schema: SchemaObject + data: Code + parseName: Name + char: Name +} + +export default function compileParser( + this: Ajv, + sch: SchemaEnv, + definitions: SchemaObjectMap +): SchemaEnv { + const _sch = getCompilingSchema.call(this, sch) + if (_sch) return _sch + const {es5, lines} = this.opts.code + const {ownProperties} = this.opts + const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) + const parseName = gen.scopeName("parse") + const cxt: ParseCxt = { + self: this, + gen, + schema: sch.schema as SchemaObject, + schemaEnv: sch, + definitions, + data: N.data, + parseName, + char: gen.name("c"), + } + + let sourceCode: string | undefined + try { + this._compilations.add(sch) + sch.parseName = parseName + parserFunction(cxt) + gen.optimize(this.opts.code.optimize) + const parseFuncCode = gen.toString() + sourceCode = `${gen.scopeRefs(N.scope)}return ${parseFuncCode}` + const makeParse = new Function(`${N.scope}`, sourceCode) + const parse: (json: string) => unknown = makeParse(this.scope.get()) + this.scope.value(parseName, {ref: parse}) + sch.parse = parse + } catch (e) { + if (sourceCode) this.logger.error("Error compiling parser, function code:", sourceCode) + delete sch.parse + delete sch.parseName + throw e + } finally { + this._compilations.delete(sch) + } + return sch +} + +const undef = _`undefined` + +function parserFunction(cxt: ParseCxt): void { + const {gen, parseName, char} = cxt + gen.func(parseName, _`${N.json}, ${N.jsonPos}, ${N.jsonPart}`, false, () => { + gen.let(N.data) + gen.let(char) + gen.assign(_`${parseName}.message`, undef) + gen.assign(_`${parseName}.position`, undef) + gen.assign(N.jsonPos, _`${N.jsonPos} || 0`) + gen.const(N.jsonLen, _`${N.json}.length`) + parseCode(cxt) + skipWhitespace(cxt) + gen.if(N.jsonPart, () => { + gen.assign(_`${parseName}.position`, N.jsonPos) + gen.return(N.data) + }) + gen.if(_`${N.jsonPos} === ${N.jsonLen}`, () => gen.return(N.data)) + jsonSyntaxError(cxt) + }) +} + +function parseCode(cxt: ParseCxt): void { + let form: JTDForm | undefined + for (const key of jtdForms) { + if (key in cxt.schema) { + form = key + break + } + } + if (form) parseNullable(cxt, genParse[form]) + else parseEmpty(cxt) +} + +const parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError)) + +function parseNullable(cxt: ParseCxt, parseForm: GenParse): void { + const {gen, schema, data} = cxt + if (!schema.nullable) return parseForm(cxt) + tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null)) +} + +function parseElements(cxt: ParseCxt): void { + const {gen, schema, data} = cxt + parseToken(cxt, "[") + const ix = gen.let("i", 0) + gen.assign(data, _`[]`) + parseItems(cxt, "]", () => { + const el = gen.let("el") + parseCode({...cxt, schema: schema.elements, data: el}) + gen.assign(_`${data}[${ix}++]`, el) + }) +} + +function parseValues(cxt: ParseCxt): void { + const {gen, schema, data} = cxt + parseToken(cxt, "{") + gen.assign(data, _`{}`) + parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values)) +} + +function parseItems(cxt: ParseCxt, endToken: string, block: () => void): void { + tryParseItems(cxt, endToken, block) + parseToken(cxt, endToken) +} + +function tryParseItems(cxt: ParseCxt, endToken: string, block: () => void): void { + const {gen} = cxt + gen.for(_`;${N.jsonPos}<${N.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => { + block() + tryParseToken(cxt, ",", () => gen.break(), hasItem) + }) + + function hasItem(): void { + tryParseToken(cxt, endToken, () => {}, jsonSyntaxError) + } +} + +function parseKeyValue(cxt: ParseCxt, schema: SchemaObject): void { + const {gen} = cxt + const key = gen.let("key") + parseString({...cxt, data: key}) + parseToken(cxt, ":") + parsePropertyValue(cxt, key, schema) +} + +function parseDiscriminator(cxt: ParseCxt): void { + const {gen, data, schema} = cxt + const {discriminator, mapping} = schema + parseToken(cxt, "{") + gen.assign(data, _`{}`) + const startPos = gen.const("pos", N.jsonPos) + const value = gen.let("value") + const tag = gen.let("tag") + tryParseItems(cxt, "}", () => { + const key = gen.let("key") + parseString({...cxt, data: key}) + parseToken(cxt, ":") + gen.if( + _`${key} === ${discriminator}`, + () => { + parseString({...cxt, data: tag}) + gen.assign(_`${data}[${key}]`, tag) + gen.break() + }, + () => parseEmpty({...cxt, data: value}) // can be discarded/skipped + ) + }) + gen.assign(N.jsonPos, startPos) + gen.if(_`${tag} === undefined`) + parsingError(cxt, str`discriminator tag not found`) + for (const tagValue in mapping) { + gen.elseIf(_`${tag} === ${tagValue}`) + parseSchemaProperties({...cxt, schema: mapping[tagValue]}, discriminator) + } + gen.else() + parsingError(cxt, str`discriminator value not in schema`) + gen.endIf() +} + +function parseProperties(cxt: ParseCxt): void { + const {gen, data} = cxt + parseToken(cxt, "{") + gen.assign(data, _`{}`) + parseSchemaProperties(cxt) +} + +function parseSchemaProperties(cxt: ParseCxt, discriminator?: string): void { + const {gen, schema, data} = cxt + const {properties, optionalProperties, additionalProperties} = schema + parseItems(cxt, "}", () => { + const key = gen.let("key") + parseString({...cxt, data: key}) + parseToken(cxt, ":") + gen.if(false) + parseDefinedProperty(cxt, key, properties) + parseDefinedProperty(cxt, key, optionalProperties) + if (discriminator) { + gen.elseIf(_`${key} === ${discriminator}`) + const tag = gen.let("tag") + parseString({...cxt, data: tag}) // can be discarded, it is already assigned + } + gen.else() + if (additionalProperties) { + parseEmpty({...cxt, data: _`${data}[${key}]`}) + } else { + parsingError(cxt, str`property ${key} not allowed`) + } + gen.endIf() + }) + if (properties) { + const hasProp = hasPropFunc(gen) + const allProps: Code = and( + ...Object.keys(properties).map((p): Code => _`${hasProp}.call(${data}, ${p})`) + ) + gen.if(not(allProps), () => parsingError(cxt, str`missing required properties`)) + } +} + +function parseDefinedProperty(cxt: ParseCxt, key: Name, schemas: SchemaObjectMap = {}): void { + const {gen} = cxt + for (const prop in schemas) { + gen.elseIf(_`${key} === ${prop}`) + parsePropertyValue(cxt, key, schemas[prop] as SchemaObject) + } +} + +function parsePropertyValue(cxt: ParseCxt, key: Name, schema: SchemaObject): void { + parseCode({...cxt, schema, data: _`${cxt.data}[${key}]`}) +} + +function parseType(cxt: ParseCxt): void { + const {gen, schema, data, self} = cxt + switch (schema.type) { + case "boolean": + parseBoolean(cxt) + break + case "string": + parseString(cxt) + break + case "timestamp": { + parseString(cxt) + const vts = useFunc(gen, validTimestamp) + const {allowDate, parseDate} = self.opts + const notValid = allowDate ? _`!${vts}(${data}, true)` : _`!${vts}(${data})` + const fail: Code = parseDate + ? or(notValid, _`(${data} = new Date(${data}), false)`, _`isNaN(${data}.valueOf())`) + : notValid + gen.if(fail, () => parsingError(cxt, str`invalid timestamp`)) + break + } + case "float32": + case "float64": + parseNumber(cxt) + break + default: { + const t = schema.type as IntType + if (!self.opts.int32range && (t === "int32" || t === "uint32")) { + parseNumber(cxt, 16) // 2 ** 53 - max safe integer + if (t === "uint32") { + gen.if(_`${data} < 0`, () => parsingError(cxt, str`integer out of range`)) + } + } else { + const [min, max, maxDigits] = intRange[t] + parseNumber(cxt, maxDigits) + gen.if(_`${data} < ${min} || ${data} > ${max}`, () => + parsingError(cxt, str`integer out of range`) + ) + } + } + } +} + +function parseString(cxt: ParseCxt): void { + parseToken(cxt, '"') + parseWith(cxt, parseJsonString) +} + +function parseEnum(cxt: ParseCxt): void { + const {gen, data, schema} = cxt + const enumSch = schema.enum + parseToken(cxt, '"') + // TODO loopEnum + gen.if(false) + for (const value of enumSch) { + const valueStr = JSON.stringify(value).slice(1) // remove starting quote + gen.elseIf(_`${jsonSlice(valueStr.length)} === ${valueStr}`) + gen.assign(data, str`${value}`) + gen.add(N.jsonPos, valueStr.length) + } + gen.else() + jsonSyntaxError(cxt) + gen.endIf() +} + +function parseNumber(cxt: ParseCxt, maxDigits?: number): void { + const {gen} = cxt + skipWhitespace(cxt) + gen.if( + _`"-0123456789".indexOf(${jsonSlice(1)}) < 0`, + () => jsonSyntaxError(cxt), + () => parseWith(cxt, parseJsonNumber, maxDigits) + ) +} + +function parseBooleanToken(bool: boolean, fail: GenParse): GenParse { + return (cxt) => { + const {gen, data} = cxt + tryParseToken( + cxt, + `${bool}`, + () => fail(cxt), + () => gen.assign(data, bool) + ) + } +} + +function parseRef(cxt: ParseCxt): void { + const {gen, self, definitions, schema, schemaEnv} = cxt + const {ref} = schema + const refSchema = definitions[ref] + if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`) + if (!hasRef(refSchema)) return parseCode({...cxt, schema: refSchema}) + const {root} = schemaEnv + const sch = compileParser.call(self, new SchemaEnv({schema: refSchema, root}), definitions) + partialParse(cxt, getParser(gen, sch), true) +} + +function getParser(gen: CodeGen, sch: SchemaEnv): Code { + return sch.parse + ? gen.scopeValue("parse", {ref: sch.parse}) + : _`${gen.scopeValue("wrapper", {ref: sch})}.parse` +} + +function parseEmpty(cxt: ParseCxt): void { + parseWith(cxt, parseJson) +} + +function parseWith(cxt: ParseCxt, parseFunc: {code: string}, args?: SafeExpr): void { + partialParse(cxt, useFunc(cxt.gen, parseFunc), args) +} + +function partialParse(cxt: ParseCxt, parseFunc: Name, args?: SafeExpr): void { + const {gen, data} = cxt + gen.assign(data, _`${parseFunc}(${N.json}, ${N.jsonPos}${args ? _`, ${args}` : nil})`) + gen.assign(N.jsonPos, _`${parseFunc}.position`) + gen.if(_`${data} === undefined`, () => parsingError(cxt, _`${parseFunc}.message`)) +} + +function parseToken(cxt: ParseCxt, tok: string): void { + tryParseToken(cxt, tok, jsonSyntaxError) +} + +function tryParseToken(cxt: ParseCxt, tok: string, fail: GenParse, success?: GenParse): void { + const {gen} = cxt + const n = tok.length + skipWhitespace(cxt) + gen.if( + _`${jsonSlice(n)} === ${tok}`, + () => { + gen.add(N.jsonPos, n) + success?.(cxt) + }, + () => fail(cxt) + ) +} + +function skipWhitespace({gen, char: c}: ParseCxt): void { + gen.code( + _`while((${c}=${N.json}[${N.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${N.jsonPos}++;` + ) +} + +function jsonSlice(len: number | Name): Code { + return len === 1 + ? _`${N.json}[${N.jsonPos}]` + : _`${N.json}.slice(${N.jsonPos}, ${N.jsonPos}+${len})` +} + +function jsonSyntaxError(cxt: ParseCxt): void { + parsingError(cxt, _`"unexpected token " + ${N.json}[${N.jsonPos}]`) +} + +function parsingError({gen, parseName}: ParseCxt, msg: Code): void { + gen.assign(_`${parseName}.message`, msg) + gen.assign(_`${parseName}.position`, N.jsonPos) + gen.return(undef) +} diff --git a/node_modules/ajv/lib/compile/jtd/serialize.ts b/node_modules/ajv/lib/compile/jtd/serialize.ts new file mode 100644 index 0000000000000000000000000000000000000000..42a47cffc1d2e1461212f9feeee08fbde02c0c2a --- /dev/null +++ b/node_modules/ajv/lib/compile/jtd/serialize.ts @@ -0,0 +1,277 @@ +import type Ajv from "../../core" +import type {SchemaObject} from "../../types" +import {jtdForms, JTDForm, SchemaObjectMap} from "./types" +import {SchemaEnv, getCompilingSchema} from ".." +import {_, str, and, getProperty, CodeGen, Code, Name} from "../codegen" +import MissingRefError from "../ref_error" +import N from "../names" +import {isOwnProperty} from "../../vocabularies/code" +import {hasRef} from "../../vocabularies/jtd/ref" +import {useFunc} from "../util" +import quote from "../../runtime/quote" + +const genSerialize: {[F in JTDForm]: (cxt: SerializeCxt) => void} = { + elements: serializeElements, + values: serializeValues, + discriminator: serializeDiscriminator, + properties: serializeProperties, + optionalProperties: serializeProperties, + enum: serializeString, + type: serializeType, + ref: serializeRef, +} + +interface SerializeCxt { + readonly gen: CodeGen + readonly self: Ajv // current Ajv instance + readonly schemaEnv: SchemaEnv + readonly definitions: SchemaObjectMap + schema: SchemaObject + data: Code +} + +export default function compileSerializer( + this: Ajv, + sch: SchemaEnv, + definitions: SchemaObjectMap +): SchemaEnv { + const _sch = getCompilingSchema.call(this, sch) + if (_sch) return _sch + const {es5, lines} = this.opts.code + const {ownProperties} = this.opts + const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) + const serializeName = gen.scopeName("serialize") + const cxt: SerializeCxt = { + self: this, + gen, + schema: sch.schema as SchemaObject, + schemaEnv: sch, + definitions, + data: N.data, + } + + let sourceCode: string | undefined + try { + this._compilations.add(sch) + sch.serializeName = serializeName + gen.func(serializeName, N.data, false, () => { + gen.let(N.json, str``) + serializeCode(cxt) + gen.return(N.json) + }) + gen.optimize(this.opts.code.optimize) + const serializeFuncCode = gen.toString() + sourceCode = `${gen.scopeRefs(N.scope)}return ${serializeFuncCode}` + const makeSerialize = new Function(`${N.scope}`, sourceCode) + const serialize: (data: unknown) => string = makeSerialize(this.scope.get()) + this.scope.value(serializeName, {ref: serialize}) + sch.serialize = serialize + } catch (e) { + if (sourceCode) this.logger.error("Error compiling serializer, function code:", sourceCode) + delete sch.serialize + delete sch.serializeName + throw e + } finally { + this._compilations.delete(sch) + } + return sch +} + +function serializeCode(cxt: SerializeCxt): void { + let form: JTDForm | undefined + for (const key of jtdForms) { + if (key in cxt.schema) { + form = key + break + } + } + serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty) +} + +function serializeNullable(cxt: SerializeCxt, serializeForm: (_cxt: SerializeCxt) => void): void { + const {gen, schema, data} = cxt + if (!schema.nullable) return serializeForm(cxt) + gen.if( + _`${data} === undefined || ${data} === null`, + () => gen.add(N.json, _`"null"`), + () => serializeForm(cxt) + ) +} + +function serializeElements(cxt: SerializeCxt): void { + const {gen, schema, data} = cxt + gen.add(N.json, str`[`) + const first = gen.let("first", true) + gen.forOf("el", data, (el) => { + addComma(cxt, first) + serializeCode({...cxt, schema: schema.elements, data: el}) + }) + gen.add(N.json, str`]`) +} + +function serializeValues(cxt: SerializeCxt): void { + const {gen, schema, data} = cxt + gen.add(N.json, str`{`) + const first = gen.let("first", true) + gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first)) + gen.add(N.json, str`}`) +} + +function serializeKeyValue(cxt: SerializeCxt, key: Name, schema: SchemaObject, first?: Name): void { + const {gen, data} = cxt + addComma(cxt, first) + serializeString({...cxt, data: key}) + gen.add(N.json, str`:`) + const value = gen.const("value", _`${data}${getProperty(key)}`) + serializeCode({...cxt, schema, data: value}) +} + +function serializeDiscriminator(cxt: SerializeCxt): void { + const {gen, schema, data} = cxt + const {discriminator} = schema + gen.add(N.json, str`{${JSON.stringify(discriminator)}:`) + const tag = gen.const("tag", _`${data}${getProperty(discriminator)}`) + serializeString({...cxt, data: tag}) + gen.if(false) + for (const tagValue in schema.mapping) { + gen.elseIf(_`${tag} === ${tagValue}`) + const sch = schema.mapping[tagValue] + serializeSchemaProperties({...cxt, schema: sch}, discriminator) + } + gen.endIf() + gen.add(N.json, str`}`) +} + +function serializeProperties(cxt: SerializeCxt): void { + const {gen} = cxt + gen.add(N.json, str`{`) + serializeSchemaProperties(cxt) + gen.add(N.json, str`}`) +} + +function serializeSchemaProperties(cxt: SerializeCxt, discriminator?: string): void { + const {gen, schema, data} = cxt + const {properties, optionalProperties} = schema + const props = keys(properties) + const optProps = keys(optionalProperties) + const allProps = allProperties(props.concat(optProps)) + let first = !discriminator + let firstProp: Name | undefined + + for (const key of props) { + if (first) first = false + else gen.add(N.json, str`,`) + serializeProperty(key, properties[key], keyValue(key)) + } + if (first) firstProp = gen.let("first", true) + for (const key of optProps) { + const value = keyValue(key) + gen.if(and(_`${value} !== undefined`, isOwnProperty(gen, data, key)), () => { + addComma(cxt, firstProp) + serializeProperty(key, optionalProperties[key], value) + }) + } + if (schema.additionalProperties) { + gen.forIn("key", data, (key) => + gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp)) + ) + } + + function keys(ps?: SchemaObjectMap): string[] { + return ps ? Object.keys(ps) : [] + } + + function allProperties(ps: string[]): string[] { + if (discriminator) ps.push(discriminator) + if (new Set(ps).size !== ps.length) { + throw new Error("JTD: properties/optionalProperties/disciminator overlap") + } + return ps + } + + function keyValue(key: string): Name { + return gen.const("value", _`${data}${getProperty(key)}`) + } + + function serializeProperty(key: string, propSchema: SchemaObject, value: Name): void { + gen.add(N.json, str`${JSON.stringify(key)}:`) + serializeCode({...cxt, schema: propSchema, data: value}) + } + + function isAdditional(key: Name, ps: string[]): Code | true { + return ps.length ? and(...ps.map((p) => _`${key} !== ${p}`)) : true + } +} + +function serializeType(cxt: SerializeCxt): void { + const {gen, schema, data} = cxt + switch (schema.type) { + case "boolean": + gen.add(N.json, _`${data} ? "true" : "false"`) + break + case "string": + serializeString(cxt) + break + case "timestamp": + gen.if( + _`${data} instanceof Date`, + () => gen.add(N.json, _`'"' + ${data}.toISOString() + '"'`), + () => serializeString(cxt) + ) + break + default: + serializeNumber(cxt) + } +} + +function serializeString({gen, data}: SerializeCxt): void { + gen.add(N.json, _`${useFunc(gen, quote)}(${data})`) +} + +function serializeNumber({gen, data, self}: SerializeCxt): void { + const condition = _`${data} === Infinity || ${data} === -Infinity || ${data} !== ${data}` + + if (self.opts.specialNumbers === undefined || self.opts.specialNumbers === "fast") { + gen.add(N.json, _`"" + ${data}`) + } else { + // specialNumbers === "null" + gen.if( + condition, + () => gen.add(N.json, _`null`), + () => gen.add(N.json, _`"" + ${data}`) + ) + } +} + +function serializeRef(cxt: SerializeCxt): void { + const {gen, self, data, definitions, schema, schemaEnv} = cxt + const {ref} = schema + const refSchema = definitions[ref] + if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`) + if (!hasRef(refSchema)) return serializeCode({...cxt, schema: refSchema}) + const {root} = schemaEnv + const sch = compileSerializer.call(self, new SchemaEnv({schema: refSchema, root}), definitions) + gen.add(N.json, _`${getSerialize(gen, sch)}(${data})`) +} + +function getSerialize(gen: CodeGen, sch: SchemaEnv): Code { + return sch.serialize + ? gen.scopeValue("serialize", {ref: sch.serialize}) + : _`${gen.scopeValue("wrapper", {ref: sch})}.serialize` +} + +function serializeEmpty({gen, data}: SerializeCxt): void { + gen.add(N.json, _`JSON.stringify(${data})`) +} + +function addComma({gen}: SerializeCxt, first?: Name): void { + if (first) { + gen.if( + first, + () => gen.assign(first, false), + () => gen.add(N.json, str`,`) + ) + } else { + gen.add(N.json, str`,`) + } +} diff --git a/node_modules/ajv/lib/compile/jtd/types.ts b/node_modules/ajv/lib/compile/jtd/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..1258050fdf426a085097c3858c513b95447ded94 --- /dev/null +++ b/node_modules/ajv/lib/compile/jtd/types.ts @@ -0,0 +1,16 @@ +import type {SchemaObject} from "../../types" + +export type SchemaObjectMap = {[Ref in string]?: SchemaObject} + +export const jtdForms = [ + "elements", + "values", + "discriminator", + "properties", + "optionalProperties", + "enum", + "type", + "ref", +] as const + +export type JTDForm = (typeof jtdForms)[number] diff --git a/node_modules/ajv/lib/compile/names.ts b/node_modules/ajv/lib/compile/names.ts new file mode 100644 index 0000000000000000000000000000000000000000..b4b242e175f08c9705f80e0daaec11ab6662e06a --- /dev/null +++ b/node_modules/ajv/lib/compile/names.ts @@ -0,0 +1,27 @@ +import {Name} from "./codegen" + +const names = { + // validation function arguments + data: new Name("data"), // data passed to validation function + // args passed from referencing schema + valCxt: new Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below + instancePath: new Name("instancePath"), + parentData: new Name("parentData"), + parentDataProperty: new Name("parentDataProperty"), + rootData: new Name("rootData"), // root data - same as the data passed to the first/top validation function + dynamicAnchors: new Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef + // function scoped variables + vErrors: new Name("vErrors"), // null or array of validation errors + errors: new Name("errors"), // counter of validation errors + this: new Name("this"), + // "globals" + self: new Name("self"), + scope: new Name("scope"), + // JTD serialize/parse name for JSON string and position + json: new Name("json"), + jsonPos: new Name("jsonPos"), + jsonLen: new Name("jsonLen"), + jsonPart: new Name("jsonPart"), +} + +export default names diff --git a/node_modules/ajv/lib/compile/ref_error.ts b/node_modules/ajv/lib/compile/ref_error.ts new file mode 100644 index 0000000000000000000000000000000000000000..386bf04995827ca2e6653fee7d4095049a753955 --- /dev/null +++ b/node_modules/ajv/lib/compile/ref_error.ts @@ -0,0 +1,13 @@ +import {resolveUrl, normalizeId, getFullPath} from "./resolve" +import type {UriResolver} from "../types" + +export default class MissingRefError extends Error { + readonly missingRef: string + readonly missingSchema: string + + constructor(resolver: UriResolver, baseId: string, ref: string, msg?: string) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`) + this.missingRef = resolveUrl(resolver, baseId, ref) + this.missingSchema = normalizeId(getFullPath(resolver, this.missingRef)) + } +} diff --git a/node_modules/ajv/lib/compile/resolve.ts b/node_modules/ajv/lib/compile/resolve.ts new file mode 100644 index 0000000000000000000000000000000000000000..b8c4aca394a7a3f46f7977c2e66a7ab570213e80 --- /dev/null +++ b/node_modules/ajv/lib/compile/resolve.ts @@ -0,0 +1,149 @@ +import type {AnySchema, AnySchemaObject, UriResolver} from "../types" +import type Ajv from "../ajv" +import type {URIComponent} from "fast-uri" +import {eachItem} from "./util" +import * as equal from "fast-deep-equal" +import * as traverse from "json-schema-traverse" + +// the hash of local references inside the schema (created by getSchemaRefs), used for inline resolution +export type LocalRefs = {[Ref in string]?: AnySchemaObject} + +// TODO refactor to use keyword definitions +const SIMPLE_INLINED = new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const", +]) + +export function inlineRef(schema: AnySchema, limit: boolean | number = true): boolean { + if (typeof schema == "boolean") return true + if (limit === true) return !hasRef(schema) + if (!limit) return false + return countKeys(schema) <= limit +} + +const REF_KEYWORDS = new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor", +]) + +function hasRef(schema: AnySchemaObject): boolean { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) return true + const sch = schema[key] + if (Array.isArray(sch) && sch.some(hasRef)) return true + if (typeof sch == "object" && hasRef(sch)) return true + } + return false +} + +function countKeys(schema: AnySchemaObject): number { + let count = 0 + for (const key in schema) { + if (key === "$ref") return Infinity + count++ + if (SIMPLE_INLINED.has(key)) continue + if (typeof schema[key] == "object") { + eachItem(schema[key], (sch) => (count += countKeys(sch))) + } + if (count === Infinity) return Infinity + } + return count +} + +export function getFullPath(resolver: UriResolver, id = "", normalize?: boolean): string { + if (normalize !== false) id = normalizeId(id) + const p = resolver.parse(id) + return _getFullPath(resolver, p) +} + +export function _getFullPath(resolver: UriResolver, p: URIComponent): string { + const serialized = resolver.serialize(p) + return serialized.split("#")[0] + "#" +} + +const TRAILING_SLASH_HASH = /#\/?$/ +export function normalizeId(id: string | undefined): string { + return id ? id.replace(TRAILING_SLASH_HASH, "") : "" +} + +export function resolveUrl(resolver: UriResolver, baseId: string, id: string): string { + id = normalizeId(id) + return resolver.resolve(baseId, id) +} + +const ANCHOR = /^[a-z_][-a-z0-9._]*$/i + +export function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs { + if (typeof schema == "boolean") return {} + const {schemaId, uriResolver} = this.opts + const schId = normalizeId(schema[schemaId] || baseId) + const baseIds: {[JsonPtr in string]?: string} = {"": schId} + const pathPrefix = getFullPath(uriResolver, schId, false) + const localRefs: LocalRefs = {} + const schemaRefs: Set = new Set() + + traverse(schema, {allKeys: true}, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === undefined) return + const fullPath = pathPrefix + jsonPtr + let innerBaseId = baseIds[parentJsonPtr] + if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]) + addAnchor.call(this, sch.$anchor) + addAnchor.call(this, sch.$dynamicAnchor) + baseIds[jsonPtr] = innerBaseId + + function addRef(this: Ajv, ref: string): string { + // eslint-disable-next-line @typescript-eslint/unbound-method + const _resolve = this.opts.uriResolver.resolve + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref) + if (schemaRefs.has(ref)) throw ambiguos(ref) + schemaRefs.add(ref) + let schOrRef = this.refs[ref] + if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef] + if (typeof schOrRef == "object") { + checkAmbiguosRef(sch, schOrRef.schema, ref) + } else if (ref !== normalizeId(fullPath)) { + if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref) + localRefs[ref] = sch + } else { + this.refs[ref] = fullPath + } + } + return ref + } + + function addAnchor(this: Ajv, anchor: unknown): void { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`) + addRef.call(this, `#${anchor}`) + } + } + }) + + return localRefs + + function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void { + if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref) + } + + function ambiguos(ref: string): Error { + return new Error(`reference "${ref}" resolves to more than one schema`) + } +} diff --git a/node_modules/ajv/lib/compile/rules.ts b/node_modules/ajv/lib/compile/rules.ts new file mode 100644 index 0000000000000000000000000000000000000000..7dbf7ab9e08317ff4e893317d07962bb6df43327 --- /dev/null +++ b/node_modules/ajv/lib/compile/rules.ts @@ -0,0 +1,50 @@ +import type {AddedKeywordDefinition} from "../types" + +const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"] as const + +export type JSONType = (typeof _jsonTypes)[number] + +const jsonTypes: Set = new Set(_jsonTypes) + +export function isJSONType(x: unknown): x is JSONType { + return typeof x == "string" && jsonTypes.has(x) +} + +type ValidationTypes = { + [K in JSONType]: boolean | RuleGroup | undefined +} + +export interface ValidationRules { + rules: RuleGroup[] + post: RuleGroup + all: {[Key in string]?: boolean | Rule} // rules that have to be validated + keywords: {[Key in string]?: boolean} // all known keywords (superset of "all") + types: ValidationTypes +} + +export interface RuleGroup { + type?: JSONType + rules: Rule[] +} + +// This interface wraps KeywordDefinition because definition can have multiple keywords +export interface Rule { + keyword: string + definition: AddedKeywordDefinition +} + +export function getRules(): ValidationRules { + const groups: Record<"number" | "string" | "array" | "object", RuleGroup> = { + number: {type: "number", rules: []}, + string: {type: "string", rules: []}, + array: {type: "array", rules: []}, + object: {type: "object", rules: []}, + } + return { + types: {...groups, integer: true, boolean: true, null: true}, + rules: [{rules: []}, groups.number, groups.string, groups.array, groups.object], + post: {rules: []}, + all: {}, + keywords: {}, + } +} diff --git a/node_modules/ajv/lib/compile/util.ts b/node_modules/ajv/lib/compile/util.ts new file mode 100644 index 0000000000000000000000000000000000000000..cefae51c2bfcc01fed2b40bcbe3425c9d1c53d18 --- /dev/null +++ b/node_modules/ajv/lib/compile/util.ts @@ -0,0 +1,213 @@ +import type {AnySchema, EvaluatedProperties, EvaluatedItems} from "../types" +import type {SchemaCxt, SchemaObjCxt} from "." +import {_, getProperty, Code, Name, CodeGen} from "./codegen" +import {_Code} from "./codegen/code" +import type {Rule, ValidationRules} from "./rules" + +// TODO refactor to use Set +export function toHash(arr: T[]): {[K in T]?: true} { + const hash: {[K in T]?: true} = {} + for (const item of arr) hash[item] = true + return hash +} + +export function alwaysValidSchema(it: SchemaCxt, schema: AnySchema): boolean | void { + if (typeof schema == "boolean") return schema + if (Object.keys(schema).length === 0) return true + checkUnknownRules(it, schema) + return !schemaHasRules(schema, it.self.RULES.all) +} + +export function checkUnknownRules(it: SchemaCxt, schema: AnySchema = it.schema): void { + const {opts, self} = it + if (!opts.strictSchema) return + if (typeof schema === "boolean") return + const rules = self.RULES.keywords + for (const key in schema) { + if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`) + } +} + +export function schemaHasRules( + schema: AnySchema, + rules: {[Key in string]?: boolean | Rule} +): boolean { + if (typeof schema == "boolean") return !schema + for (const key in schema) if (rules[key]) return true + return false +} + +export function schemaHasRulesButRef(schema: AnySchema, RULES: ValidationRules): boolean { + if (typeof schema == "boolean") return !schema + for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true + return false +} + +export function schemaRefOrVal( + {topSchemaRef, schemaPath}: SchemaObjCxt, + schema: unknown, + keyword: string, + $data?: string | false +): Code | number | boolean { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") return schema + if (typeof schema == "string") return _`${schema}` + } + return _`${topSchemaRef}${schemaPath}${getProperty(keyword)}` +} + +export function unescapeFragment(str: string): string { + return unescapeJsonPointer(decodeURIComponent(str)) +} + +export function escapeFragment(str: string | number): string { + return encodeURIComponent(escapeJsonPointer(str)) +} + +export function escapeJsonPointer(str: string | number): string { + if (typeof str == "number") return `${str}` + return str.replace(/~/g, "~0").replace(/\//g, "~1") +} + +export function unescapeJsonPointer(str: string): string { + return str.replace(/~1/g, "/").replace(/~0/g, "~") +} + +export function eachItem(xs: T | T[], f: (x: T) => void): void { + if (Array.isArray(xs)) { + for (const x of xs) f(x) + } else { + f(xs) + } +} + +type SomeEvaluated = EvaluatedProperties | EvaluatedItems + +type MergeEvaluatedFunc = ( + gen: CodeGen, + from: Name | T, + to: Name | Exclude | undefined, + toName?: typeof Name +) => Name | T + +interface MakeMergeFuncArgs { + mergeNames: (gen: CodeGen, from: Name, to: Name) => void + mergeToName: (gen: CodeGen, from: T, to: Name) => void + mergeValues: (from: T, to: Exclude) => T + resultToName: (gen: CodeGen, res?: T) => Name +} + +function makeMergeEvaluated({ + mergeNames, + mergeToName, + mergeValues, + resultToName, +}: MakeMergeFuncArgs): MergeEvaluatedFunc { + return (gen, from, to, toName) => { + const res = + to === undefined + ? from + : to instanceof Name + ? (from instanceof Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) + : from instanceof Name + ? (mergeToName(gen, to, from), from) + : mergeValues(from, to) + return toName === Name && !(res instanceof Name) ? resultToName(gen, res) : res + } +} + +interface MergeEvaluated { + props: MergeEvaluatedFunc + items: MergeEvaluatedFunc +} + +export const mergeEvaluated: MergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => + gen.if(_`${to} !== true && ${from} !== undefined`, () => { + gen.if( + _`${from} === true`, + () => gen.assign(to, true), + () => gen.assign(to, _`${to} || {}`).code(_`Object.assign(${to}, ${from})`) + ) + }), + mergeToName: (gen, from, to) => + gen.if(_`${to} !== true`, () => { + if (from === true) { + gen.assign(to, true) + } else { + gen.assign(to, _`${to} || {}`) + setEvaluated(gen, to, from) + } + }), + mergeValues: (from, to) => (from === true ? true : {...from, ...to}), + resultToName: evaluatedPropsToName, + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => + gen.if(_`${to} !== true && ${from} !== undefined`, () => + gen.assign(to, _`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`) + ), + mergeToName: (gen, from, to) => + gen.if(_`${to} !== true`, () => + gen.assign(to, from === true ? true : _`${to} > ${from} ? ${to} : ${from}`) + ), + mergeValues: (from, to) => (from === true ? true : Math.max(from, to)), + resultToName: (gen, items) => gen.var("items", items), + }), +} + +export function evaluatedPropsToName(gen: CodeGen, ps?: EvaluatedProperties): Name { + if (ps === true) return gen.var("props", true) + const props = gen.var("props", _`{}`) + if (ps !== undefined) setEvaluated(gen, props, ps) + return props +} + +export function setEvaluated(gen: CodeGen, props: Name, ps: {[K in string]?: true}): void { + Object.keys(ps).forEach((p) => gen.assign(_`${props}${getProperty(p)}`, true)) +} + +const snippets: {[S in string]?: _Code} = {} + +export function useFunc(gen: CodeGen, f: {code: string}): Name { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new _Code(f.code)), + }) +} + +export enum Type { + Num, + Str, +} + +export function getErrorPath( + dataProp: Name | string | number, + dataPropType?: Type, + jsPropertySyntax?: boolean +): Code | string { + // let path + if (dataProp instanceof Name) { + const isNumber = dataPropType === Type.Num + return jsPropertySyntax + ? isNumber + ? _`"[" + ${dataProp} + "]"` + : _`"['" + ${dataProp} + "']"` + : isNumber + ? _`"/" + ${dataProp}` + : _`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")` // TODO maybe use global escapePointer + } + return jsPropertySyntax ? getProperty(dataProp).toString() : "/" + escapeJsonPointer(dataProp) +} + +export function checkStrictMode( + it: SchemaCxt, + msg: string, + mode: boolean | "log" = it.opts.strictSchema +): void { + if (!mode) return + msg = `strict mode: ${msg}` + if (mode === true) throw new Error(msg) + it.self.logger.warn(msg) +} diff --git a/node_modules/ajv/lib/compile/validate/applicability.ts b/node_modules/ajv/lib/compile/validate/applicability.ts new file mode 100644 index 0000000000000000000000000000000000000000..478b704ac571d7b34deb19ef84aa0e2dd08973e3 --- /dev/null +++ b/node_modules/ajv/lib/compile/validate/applicability.ts @@ -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) + ) +} diff --git a/node_modules/ajv/lib/compile/validate/boolSchema.ts b/node_modules/ajv/lib/compile/validate/boolSchema.ts new file mode 100644 index 0000000000000000000000000000000000000000..156355016d62249d16c6dc19a89c28b5ff6972c7 --- /dev/null +++ b/node_modules/ajv/lib/compile/validate/boolSchema.ts @@ -0,0 +1,47 @@ +import type {KeywordErrorDefinition, KeywordErrorCxt} from "../../types" +import type {SchemaCxt} from ".." +import {reportError} from "../errors" +import {_, Name} from "../codegen" +import N from "../names" + +const boolError: KeywordErrorDefinition = { + message: "boolean schema is false", +} + +export function topBoolOrEmptySchema(it: SchemaCxt): void { + const {gen, schema, validateName} = it + if (schema === false) { + falseSchemaError(it, false) + } else if (typeof schema == "object" && schema.$async === true) { + gen.return(N.data) + } else { + gen.assign(_`${validateName}.errors`, null) + gen.return(true) + } +} + +export function boolOrEmptySchema(it: SchemaCxt, valid: Name): void { + const {gen, schema} = it + if (schema === false) { + gen.var(valid, false) // TODO var + falseSchemaError(it) + } else { + gen.var(valid, true) // TODO var + } +} + +function falseSchemaError(it: SchemaCxt, overrideAllErrors?: boolean): void { + const {gen, data} = it + // TODO maybe some other interface should be used for non-keyword validation errors... + const cxt: KeywordErrorCxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it, + } + reportError(cxt, boolError, undefined, overrideAllErrors) +} diff --git a/node_modules/ajv/lib/compile/validate/dataType.ts b/node_modules/ajv/lib/compile/validate/dataType.ts new file mode 100644 index 0000000000000000000000000000000000000000..d8142b3e1f55194a06de0ab489ee01e00136df25 --- /dev/null +++ b/node_modules/ajv/lib/compile/validate/dataType.ts @@ -0,0 +1,230 @@ +import type { + KeywordErrorDefinition, + KeywordErrorCxt, + ErrorObject, + AnySchemaObject, +} from "../../types" +import type {SchemaObjCxt} from ".." +import {isJSONType, JSONType} from "../rules" +import {schemaHasRulesForType} from "./applicability" +import {reportError} from "../errors" +import {_, nil, and, not, operators, Code, Name} from "../codegen" +import {toHash, schemaRefOrVal} from "../util" + +export enum DataType { + Correct, + Wrong, +} + +export function getSchemaTypes(schema: AnySchemaObject): JSONType[] { + const types = getJSONTypes(schema.type) + const hasNull = types.includes("null") + if (hasNull) { + if (schema.nullable === false) throw new Error("type: null contradicts nullable: false") + } else { + if (!types.length && schema.nullable !== undefined) { + throw new Error('"nullable" cannot be used without "type"') + } + if (schema.nullable === true) types.push("null") + } + return types +} + +// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents +export function getJSONTypes(ts: unknown | unknown[]): JSONType[] { + const types: unknown[] = Array.isArray(ts) ? ts : ts ? [ts] : [] + if (types.every(isJSONType)) return types + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")) +} + +export function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean { + const {gen, data, opts} = it + const coerceTo = coerceToTypes(types, opts.coerceTypes) + const checkTypes = + types.length > 0 && + !(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0])) + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong) + gen.if(wrongType, () => { + if (coerceTo.length) coerceData(it, types, coerceTo) + else reportTypeError(it) + }) + } + return checkTypes +} + +const COERCIBLE: Set = new Set(["string", "number", "integer", "boolean", "null"]) +function coerceToTypes(types: JSONType[], coerceTypes?: boolean | "array"): JSONType[] { + return coerceTypes + ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array")) + : [] +} + +function coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void { + const {gen, data, opts} = it + const dataType = gen.let("dataType", _`typeof ${data}`) + const coerced = gen.let("coerced", _`undefined`) + if (opts.coerceTypes === "array") { + gen.if(_`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => + gen + .assign(data, _`${data}[0]`) + .assign(dataType, _`typeof ${data}`) + .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)) + ) + } + gen.if(_`${coerced} !== undefined`) + for (const t of coerceTo) { + if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) { + coerceSpecificType(t) + } + } + gen.else() + reportTypeError(it) + gen.endIf() + + gen.if(_`${coerced} !== undefined`, () => { + gen.assign(data, coerced) + assignParentData(it, coerced) + }) + + function coerceSpecificType(t: string): void { + switch (t) { + case "string": + gen + .elseIf(_`${dataType} == "number" || ${dataType} == "boolean"`) + .assign(coerced, _`"" + ${data}`) + .elseIf(_`${data} === null`) + .assign(coerced, _`""`) + return + case "number": + gen + .elseIf( + _`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})` + ) + .assign(coerced, _`+${data}`) + return + case "integer": + gen + .elseIf( + _`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))` + ) + .assign(coerced, _`+${data}`) + return + case "boolean": + gen + .elseIf(_`${data} === "false" || ${data} === 0 || ${data} === null`) + .assign(coerced, false) + .elseIf(_`${data} === "true" || ${data} === 1`) + .assign(coerced, true) + return + case "null": + gen.elseIf(_`${data} === "" || ${data} === 0 || ${data} === false`) + gen.assign(coerced, null) + return + + case "array": + gen + .elseIf( + _`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null` + ) + .assign(coerced, _`[${data}]`) + } + } +} + +function assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void { + // TODO use gen.property + gen.if(_`${parentData} !== undefined`, () => + gen.assign(_`${parentData}[${parentDataProperty}]`, expr) + ) +} + +export function checkDataType( + dataType: JSONType, + data: Name, + strictNums?: boolean | "log", + correct = DataType.Correct +): Code { + const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ + let cond: Code + switch (dataType) { + case "null": + return _`${data} ${EQ} null` + case "array": + cond = _`Array.isArray(${data})` + break + case "object": + cond = _`${data} && typeof ${data} == "object" && !Array.isArray(${data})` + break + case "integer": + cond = numCond(_`!(${data} % 1) && !isNaN(${data})`) + break + case "number": + cond = numCond() + break + default: + return _`typeof ${data} ${EQ} ${dataType}` + } + return correct === DataType.Correct ? cond : not(cond) + + function numCond(_cond: Code = nil): Code { + return and(_`typeof ${data} == "number"`, _cond, strictNums ? _`isFinite(${data})` : nil) + } +} + +export function checkDataTypes( + dataTypes: JSONType[], + data: Name, + strictNums?: boolean | "log", + correct?: DataType +): Code { + if (dataTypes.length === 1) { + return checkDataType(dataTypes[0], data, strictNums, correct) + } + let cond: Code + const types = toHash(dataTypes) + if (types.array && types.object) { + const notObj = _`typeof ${data} != "object"` + cond = types.null ? notObj : _`!${data} || ${notObj}` + delete types.null + delete types.array + delete types.object + } else { + cond = nil + } + if (types.number) delete types.integer + for (const t in types) cond = and(cond, checkDataType(t as JSONType, data, strictNums, correct)) + return cond +} + +export type TypeError = ErrorObject<"type", {type: string}> + +const typeError: KeywordErrorDefinition = { + message: ({schema}) => `must be ${schema}`, + params: ({schema, schemaValue}) => + typeof schema == "string" ? _`{type: ${schema}}` : _`{type: ${schemaValue}}`, +} + +export function reportTypeError(it: SchemaObjCxt): void { + const cxt = getTypeErrorContext(it) + reportError(cxt, typeError) +} + +function getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt { + const {gen, data, schema} = it + const schemaCode = schemaRefOrVal(it, schema, "type") + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it, + } +} diff --git a/node_modules/ajv/lib/compile/validate/defaults.ts b/node_modules/ajv/lib/compile/validate/defaults.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ad3d4df8291bdfd7aec74833bec4b0b4c91f36f --- /dev/null +++ b/node_modules/ajv/lib/compile/validate/defaults.ts @@ -0,0 +1,32 @@ +import type {SchemaObjCxt} from ".." +import {_, getProperty, stringify} from "../codegen" +import {checkStrictMode} from "../util" + +export function assignDefaults(it: SchemaObjCxt, ty?: string): void { + const {properties, items} = it.schema + if (ty === "object" && properties) { + for (const key in properties) { + assignDefault(it, key, properties[key].default) + } + } else if (ty === "array" && Array.isArray(items)) { + items.forEach((sch, i: number) => assignDefault(it, i, sch.default)) + } +} + +function assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void { + const {gen, compositeRule, data, opts} = it + if (defaultValue === undefined) return + const childData = _`${data}${getProperty(prop)}` + if (compositeRule) { + checkStrictMode(it, `default is ignored for: ${childData}`) + return + } + + let condition = _`${childData} === undefined` + if (opts.useDefaults === "empty") { + condition = _`${condition} || ${childData} === null || ${childData} === ""` + } + // `${childData} === undefined` + + // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "") + gen.if(condition, _`${childData} = ${stringify(defaultValue)}`) +} diff --git a/node_modules/ajv/lib/compile/validate/index.ts b/node_modules/ajv/lib/compile/validate/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..15ecabd85169e3f19b56b7547982643383068552 --- /dev/null +++ b/node_modules/ajv/lib/compile/validate/index.ts @@ -0,0 +1,582 @@ +import type { + AddedKeywordDefinition, + AnySchema, + AnySchemaObject, + KeywordErrorCxt, + KeywordCxtParams, +} from "../../types" +import type {SchemaCxt, SchemaObjCxt} from ".." +import type {InstanceOptions} from "../../core" +import {boolOrEmptySchema, topBoolOrEmptySchema} from "./boolSchema" +import {coerceAndCheckDataType, getSchemaTypes} from "./dataType" +import {shouldUseGroup, shouldUseRule} from "./applicability" +import {checkDataType, checkDataTypes, reportTypeError, DataType} from "./dataType" +import {assignDefaults} from "./defaults" +import {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from "./keyword" +import {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from "./subschema" +import {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from "../codegen" +import N from "../names" +import {resolveUrl} from "../resolve" +import { + schemaRefOrVal, + schemaHasRulesButRef, + checkUnknownRules, + checkStrictMode, + unescapeJsonPointer, + mergeEvaluated, +} from "../util" +import type {JSONType, Rule, RuleGroup} from "../rules" +import { + ErrorPaths, + reportError, + reportExtraError, + resetErrorsCount, + keyword$DataError, +} from "../errors" + +// schema compilation - generates validation function, subschemaCode (below) is used for subschemas +export function validateFunctionCode(it: SchemaCxt): void { + if (isSchemaObj(it)) { + checkKeywords(it) + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it) + return + } + } + validateFunction(it, () => topBoolOrEmptySchema(it)) +} + +function validateFunction( + {gen, validateName, schema, schemaEnv, opts}: SchemaCxt, + body: Block +): void { + if (opts.code.es5) { + gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => { + gen.code(_`"use strict"; ${funcSourceUrl(schema, opts)}`) + destructureValCxtES5(gen, opts) + gen.code(body) + }) + } else { + gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => + gen.code(funcSourceUrl(schema, opts)).code(body) + ) + } +} + +function destructureValCxt(opts: InstanceOptions): Code { + return _`{${N.instancePath}="", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${ + N.data + }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}` +} + +function destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void { + gen.if( + N.valCxt, + () => { + gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`) + gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`) + gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`) + gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`) + if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`) + }, + () => { + gen.var(N.instancePath, _`""`) + gen.var(N.parentData, _`undefined`) + gen.var(N.parentDataProperty, _`undefined`) + gen.var(N.rootData, N.data) + if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`) + } + ) +} + +function topSchemaObjCode(it: SchemaObjCxt): void { + const {schema, opts, gen} = it + validateFunction(it, () => { + if (opts.$comment && schema.$comment) commentKeyword(it) + checkNoDefault(it) + gen.let(N.vErrors, null) + gen.let(N.errors, 0) + if (opts.unevaluated) resetEvaluated(it) + typeAndKeywords(it) + returnResults(it) + }) + return +} + +function resetEvaluated(it: SchemaObjCxt): void { + // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated + const {gen, validateName} = it + it.evaluated = gen.const("evaluated", _`${validateName}.evaluated`) + gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`)) + gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`)) +} + +function funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code { + const schId = typeof schema == "object" && schema[opts.schemaId] + return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil +} + +// schema compilation - this function is used recursively to generate code for sub-schemas +function subschemaCode(it: SchemaCxt, valid: Name): void { + if (isSchemaObj(it)) { + checkKeywords(it) + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid) + return + } + } + boolOrEmptySchema(it, valid) +} + +function schemaCxtHasRules({schema, self}: SchemaCxt): boolean { + if (typeof schema == "boolean") return !schema + for (const key in schema) if (self.RULES.all[key]) return true + return false +} + +function isSchemaObj(it: SchemaCxt): it is SchemaObjCxt { + return typeof it.schema != "boolean" +} + +function subSchemaObjCode(it: SchemaObjCxt, valid: Name): void { + const {schema, gen, opts} = it + if (opts.$comment && schema.$comment) commentKeyword(it) + updateContext(it) + checkAsyncSchema(it) + const errsCount = gen.const("_errs", N.errors) + typeAndKeywords(it, errsCount) + // TODO var + gen.var(valid, _`${errsCount} === ${N.errors}`) +} + +function checkKeywords(it: SchemaObjCxt): void { + checkUnknownRules(it) + checkRefsAndKeywords(it) +} + +function typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void { + if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount) + const types = getSchemaTypes(it.schema) + const checkedTypes = coerceAndCheckDataType(it, types) + schemaKeywords(it, types, !checkedTypes, errsCount) +} + +function checkRefsAndKeywords(it: SchemaObjCxt): void { + const {schema, errSchemaPath, opts, self} = it + if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) { + self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`) + } +} + +function checkNoDefault(it: SchemaObjCxt): void { + const {schema, opts} = it + if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) { + checkStrictMode(it, "default is ignored in the schema root") + } +} + +function updateContext(it: SchemaObjCxt): void { + const schId = it.schema[it.opts.schemaId] + if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId) +} + +function checkAsyncSchema(it: SchemaObjCxt): void { + if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema") +} + +function commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void { + const msg = schema.$comment + if (opts.$comment === true) { + gen.code(_`${N.self}.logger.log(${msg})`) + } else if (typeof opts.$comment == "function") { + const schemaPath = str`${errSchemaPath}/$comment` + const rootName = gen.scopeValue("root", {ref: schemaEnv.root}) + gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`) + } +} + +function returnResults(it: SchemaCxt): void { + const {gen, schemaEnv, validateName, ValidationError, opts} = it + if (schemaEnv.$async) { + // TODO assign unevaluated + gen.if( + _`${N.errors} === 0`, + () => gen.return(N.data), + () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`) + ) + } else { + gen.assign(_`${validateName}.errors`, N.vErrors) + if (opts.unevaluated) assignEvaluated(it) + gen.return(_`${N.errors} === 0`) + } +} + +function assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void { + if (props instanceof Name) gen.assign(_`${evaluated}.props`, props) + if (items instanceof Name) gen.assign(_`${evaluated}.items`, items) +} + +function schemaKeywords( + it: SchemaObjCxt, + types: JSONType[], + typeErrors: boolean, + errsCount?: Name +): void { + const {gen, schema, data, allErrors, opts, self} = it + const {RULES} = self + if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", (RULES.all.$ref as Rule).definition)) // TODO typecast + return + } + if (!opts.jtd) checkStrictTypes(it, types) + gen.block(() => { + for (const group of RULES.rules) groupKeywords(group) + groupKeywords(RULES.post) + }) + + function groupKeywords(group: RuleGroup): void { + if (!shouldUseGroup(schema, group)) return + if (group.type) { + gen.if(checkDataType(group.type, data, opts.strictNumbers)) + iterateKeywords(it, group) + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else() + reportTypeError(it) + } + gen.endIf() + } else { + iterateKeywords(it, group) + } + // TODO make it "ok" call? + if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`) + } +} + +function iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void { + const { + gen, + schema, + opts: {useDefaults}, + } = it + if (useDefaults) assignDefaults(it, group.type) + gen.block(() => { + for (const rule of group.rules) { + if (shouldUseRule(schema, rule)) { + keywordCode(it, rule.keyword, rule.definition, group.type) + } + } + }) +} + +function checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void { + if (it.schemaEnv.meta || !it.opts.strictTypes) return + checkContextTypes(it, types) + if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types) + checkKeywordTypes(it, it.dataTypes) +} + +function checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void { + if (!types.length) return + if (!it.dataTypes.length) { + it.dataTypes = types + return + } + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) { + strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`) + } + }) + narrowSchemaTypes(it, types) +} + +function checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { + strictTypesError(it, "use allowUnionTypes to allow union type keyword") + } +} + +function checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void { + const rules = it.self.RULES.all + for (const keyword in rules) { + const rule = rules[keyword] + if (typeof rule == "object" && shouldUseRule(it.schema, rule)) { + const {type} = rule.definition + if (type.length && !type.some((t) => hasApplicableType(ts, t))) { + strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`) + } + } + } +} + +function hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean { + return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer")) +} + +function includesType(ts: JSONType[], t: JSONType): boolean { + return ts.includes(t) || (t === "integer" && ts.includes("number")) +} + +function narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void { + const ts: JSONType[] = [] + for (const t of it.dataTypes) { + if (includesType(withTypes, t)) ts.push(t) + else if (withTypes.includes("integer") && t === "number") ts.push("integer") + } + it.dataTypes = ts +} + +function strictTypesError(it: SchemaObjCxt, msg: string): void { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath + msg += ` at "${schemaPath}" (strictTypes)` + checkStrictMode(it, msg, it.opts.strictTypes) +} + +export class KeywordCxt implements KeywordErrorCxt { + readonly gen: CodeGen + readonly allErrors?: boolean + readonly keyword: string + readonly data: Name // Name referencing the current level of the data instance + readonly $data?: string | false + schema: any // keyword value in the schema + readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value + readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) + readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema + readonly parentSchema: AnySchemaObject + readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, + // requires option trackErrors in keyword definition + params: KeywordCxtParams // object to pass parameters to error messages from keyword code + readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) + readonly def: AddedKeywordDefinition + + constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { + validateKeywordUsage(it, def, keyword) + this.gen = it.gen + this.allErrors = it.allErrors + this.keyword = keyword + this.data = it.data + this.schema = it.schema[keyword] + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data + this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) + this.schemaType = def.schemaType + this.parentSchema = it.schema + this.params = {} + this.it = it + this.def = def + + if (this.$data) { + this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) + } else { + this.schemaCode = this.schemaValue + if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { + throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) + } + } + + if ("code" in def ? def.trackErrors : def.errors !== false) { + this.errsCount = it.gen.const("_errs", N.errors) + } + } + + result(condition: Code, successAction?: () => void, failAction?: () => void): void { + this.failResult(not(condition), successAction, failAction) + } + + failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { + this.gen.if(condition) + if (failAction) failAction() + else this.error() + if (successAction) { + this.gen.else() + successAction() + if (this.allErrors) this.gen.endIf() + } else { + if (this.allErrors) this.gen.endIf() + else this.gen.else() + } + } + + pass(condition: Code, failAction?: () => void): void { + this.failResult(not(condition), undefined, failAction) + } + + fail(condition?: Code): void { + if (condition === undefined) { + this.error() + if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize + return + } + this.gen.if(condition) + this.error() + if (this.allErrors) this.gen.endIf() + else this.gen.else() + } + + fail$data(condition: Code): void { + if (!this.$data) return this.fail(condition) + const {schemaCode} = this + this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) + } + + error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { + if (errorParams) { + this.setParams(errorParams) + this._error(append, errorPaths) + this.setParams({}) + return + } + this._error(append, errorPaths) + } + + private _error(append?: boolean, errorPaths?: ErrorPaths): void { + ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) + } + + $dataError(): void { + reportError(this, this.def.$dataError || keyword$DataError) + } + + reset(): void { + if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') + resetErrorsCount(this.gen, this.errsCount) + } + + ok(cond: Code | boolean): void { + if (!this.allErrors) this.gen.if(cond) + } + + setParams(obj: KeywordCxtParams, assign?: true): void { + if (assign) Object.assign(this.params, obj) + else this.params = obj + } + + block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { + this.gen.block(() => { + this.check$data(valid, $dataValid) + codeBlock() + }) + } + + check$data(valid: Name = nil, $dataValid: Code = nil): void { + if (!this.$data) return + const {gen, schemaCode, schemaType, def} = this + gen.if(or(_`${schemaCode} === undefined`, $dataValid)) + if (valid !== nil) gen.assign(valid, true) + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()) + this.$dataError() + if (valid !== nil) gen.assign(valid, false) + } + gen.else() + } + + invalid$data(): Code { + const {gen, schemaCode, schemaType, def, it} = this + return or(wrong$DataType(), invalid$DataSchema()) + + function wrong$DataType(): Code { + if (schemaType.length) { + /* istanbul ignore if */ + if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") + const st = Array.isArray(schemaType) ? schemaType : [schemaType] + return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` + } + return nil + } + + function invalid$DataSchema(): Code { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone + return _`!${validateSchemaRef}(${schemaCode})` + } + return nil + } + } + + subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { + const subschema = getSubschema(this.it, appl) + extendSubschemaData(subschema, this.it, appl) + extendSubschemaMode(subschema, appl) + const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} + subschemaCode(nextContext, valid) + return nextContext + } + + mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { + const {it, gen} = this + if (!it.opts.unevaluated) return + if (it.props !== true && schemaCxt.props !== undefined) { + it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) + } + if (it.items !== true && schemaCxt.items !== undefined) { + it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) + } + } + + mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { + const {it, gen} = this + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) + return true + } + } +} + +function keywordCode( + it: SchemaObjCxt, + keyword: string, + def: AddedKeywordDefinition, + ruleType?: JSONType +): void { + const cxt = new KeywordCxt(it, def, keyword) + if ("code" in def) { + def.code(cxt, ruleType) + } else if (cxt.$data && def.validate) { + funcKeywordCode(cxt, def) + } else if ("macro" in def) { + macroKeywordCode(cxt, def) + } else if (def.compile || def.validate) { + funcKeywordCode(cxt, def) + } +} + +const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/ +const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/ +export function getData( + $data: string, + {dataLevel, dataNames, dataPathArr}: SchemaCxt +): Code | number { + let jsonPointer + let data: Code + if ($data === "") return N.rootData + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`) + jsonPointer = $data + data = N.rootData + } else { + const matches = RELATIVE_JSON_POINTER.exec($data) + if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`) + const up: number = +matches[1] + jsonPointer = matches[2] + if (jsonPointer === "#") { + if (up >= dataLevel) throw new Error(errorMsg("property/index", up)) + return dataPathArr[dataLevel - up] + } + if (up > dataLevel) throw new Error(errorMsg("data", up)) + data = dataNames[dataLevel - up] + if (!jsonPointer) return data + } + + let expr = data + const segments = jsonPointer.split("/") + for (const segment of segments) { + if (segment) { + data = _`${data}${getProperty(unescapeJsonPointer(segment))}` + expr = _`${expr} && ${data}` + } + } + return expr + + function errorMsg(pointerType: string, up: number): string { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}` + } +} diff --git a/node_modules/ajv/lib/compile/validate/keyword.ts b/node_modules/ajv/lib/compile/validate/keyword.ts new file mode 100644 index 0000000000000000000000000000000000000000..f854aa71083ca28c01f8064fdca177a847e6f308 --- /dev/null +++ b/node_modules/ajv/lib/compile/validate/keyword.ts @@ -0,0 +1,171 @@ +import type {KeywordCxt} from "." +import type { + AnySchema, + SchemaValidateFunction, + AnyValidateFunction, + AddedKeywordDefinition, + MacroKeywordDefinition, + FuncKeywordDefinition, +} from "../../types" +import type {SchemaObjCxt} from ".." +import {_, nil, not, stringify, Code, Name, CodeGen} from "../codegen" +import N from "../names" +import type {JSONType} from "../rules" +import {callValidateCode} from "../../vocabularies/code" +import {extendErrors} from "../errors" + +type KeywordCompilationResult = AnySchema | SchemaValidateFunction | AnyValidateFunction + +export function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void { + const {gen, keyword, schema, parentSchema, it} = cxt + const macroSchema = def.macro.call(it.self, schema, parentSchema, it) + const schemaRef = useKeyword(gen, keyword, macroSchema) + if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true) + + const valid = gen.name("valid") + cxt.subschema( + { + schema: macroSchema, + schemaPath: nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true, + }, + valid + ) + cxt.pass(valid, () => cxt.error(true)) +} + +export function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void { + const {gen, keyword, schema, parentSchema, $data, it} = cxt + checkAsyncKeyword(it, def) + const validate = + !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate + const validateRef = useKeyword(gen, keyword, validate) + const valid = gen.let("valid") + cxt.block$data(valid, validateKeyword) + cxt.ok(def.valid ?? valid) + + function validateKeyword(): void { + if (def.errors === false) { + assignValid() + if (def.modifying) modifyData(cxt) + reportErrs(() => cxt.error()) + } else { + const ruleErrs = def.async ? validateAsync() : validateSync() + if (def.modifying) modifyData(cxt) + reportErrs(() => addErrs(cxt, ruleErrs)) + } + } + + function validateAsync(): Name { + const ruleErrs = gen.let("ruleErrs", null) + gen.try( + () => assignValid(_`await `), + (e) => + gen.assign(valid, false).if( + _`${e} instanceof ${it.ValidationError as Name}`, + () => gen.assign(ruleErrs, _`${e}.errors`), + () => gen.throw(e) + ) + ) + return ruleErrs + } + + function validateSync(): Code { + const validateErrs = _`${validateRef}.errors` + gen.assign(validateErrs, null) + assignValid(nil) + return validateErrs + } + + function assignValid(_await: Code = def.async ? _`await ` : nil): void { + const passCxt = it.opts.passContext ? N.this : N.self + const passSchema = !(("compile" in def && !$data) || def.schema === false) + gen.assign( + valid, + _`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`, + def.modifying + ) + } + + function reportErrs(errors: () => void): void { + gen.if(not(def.valid ?? valid), errors) + } +} + +function modifyData(cxt: KeywordCxt): void { + const {gen, data, it} = cxt + gen.if(it.parentData, () => gen.assign(data, _`${it.parentData}[${it.parentDataProperty}]`)) +} + +function addErrs(cxt: KeywordCxt, errs: Code): void { + const {gen} = cxt + gen.if( + _`Array.isArray(${errs})`, + () => { + gen + .assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) + .assign(N.errors, _`${N.vErrors}.length`) + extendErrors(cxt) + }, + () => cxt.error() + ) +} + +function checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void { + if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema") +} + +function useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name { + if (result === undefined) throw new Error(`keyword "${keyword}" failed to compile`) + return gen.scopeValue( + "keyword", + typeof result == "function" ? {ref: result} : {ref: result, code: stringify(result)} + ) +} + +export function validSchemaType( + schema: unknown, + schemaType: JSONType[], + allowUndefined = false +): boolean { + // TODO add tests + return ( + !schemaType.length || + schemaType.some((st) => + st === "array" + ? Array.isArray(schema) + : st === "object" + ? schema && typeof schema == "object" && !Array.isArray(schema) + : typeof schema == st || (allowUndefined && typeof schema == "undefined") + ) + ) +} + +export function validateKeywordUsage( + {schema, opts, self, errSchemaPath}: SchemaObjCxt, + def: AddedKeywordDefinition, + keyword: string +): void { + /* istanbul ignore if */ + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { + throw new Error("ajv implementation error") + } + + const deps = def.dependencies + if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { + throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`) + } + + if (def.validateSchema) { + const valid = def.validateSchema(schema[keyword]) + if (!valid) { + const msg = + `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + + self.errorsText(def.validateSchema.errors) + if (opts.validateSchema === "log") self.logger.error(msg) + else throw new Error(msg) + } + } +} diff --git a/node_modules/ajv/lib/compile/validate/subschema.ts b/node_modules/ajv/lib/compile/validate/subschema.ts new file mode 100644 index 0000000000000000000000000000000000000000..9072ed7743decf23950a40033cb2c2f6ec1845e4 --- /dev/null +++ b/node_modules/ajv/lib/compile/validate/subschema.ts @@ -0,0 +1,135 @@ +import type {AnySchema} from "../../types" +import type {SchemaObjCxt} from ".." +import {_, str, getProperty, Code, Name} from "../codegen" +import {escapeFragment, getErrorPath, Type} from "../util" +import type {JSONType} from "../rules" + +export interface SubschemaContext { + // TODO use Optional? align with SchemCxt property types + schema: AnySchema + schemaPath: Code + errSchemaPath: string + topSchemaRef?: Code + errorPath?: Code + dataLevel?: number + dataTypes?: JSONType[] + data?: Name + parentData?: Name + parentDataProperty?: Code | number + dataNames?: Name[] + dataPathArr?: (Code | number)[] + propertyName?: Name + jtdDiscriminator?: string + jtdMetadata?: boolean + compositeRule?: true + createErrors?: boolean + allErrors?: boolean +} + +export type SubschemaArgs = Partial<{ + keyword: string + schemaProp: string | number + schema: AnySchema + schemaPath: Code + errSchemaPath: string + topSchemaRef: Code + data: Name | Code + dataProp: Code | string | number + dataTypes: JSONType[] + definedProperties: Set + propertyName: Name + dataPropType: Type + jtdDiscriminator: string + jtdMetadata: boolean + compositeRule: true + createErrors: boolean + allErrors: boolean +}> + +export function getSubschema( + it: SchemaObjCxt, + {keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs +): SubschemaContext { + if (keyword !== undefined && schema !== undefined) { + throw new Error('both "keyword" and "schema" passed, only one allowed') + } + + if (keyword !== undefined) { + const sch = it.schema[keyword] + return schemaProp === undefined + ? { + schema: sch, + schemaPath: _`${it.schemaPath}${getProperty(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + } + : { + schema: sch[schemaProp], + schemaPath: _`${it.schemaPath}${getProperty(keyword)}${getProperty(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${escapeFragment(schemaProp)}`, + } + } + + if (schema !== undefined) { + if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) { + throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"') + } + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath, + } + } + + throw new Error('either "keyword" or "schema" must be passed') +} + +export function extendSubschemaData( + subschema: SubschemaContext, + it: SchemaObjCxt, + {dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs +): void { + if (data !== undefined && dataProp !== undefined) { + throw new Error('both "data" and "dataProp" passed, only one allowed') + } + + const {gen} = it + + if (dataProp !== undefined) { + const {errorPath, dataPathArr, opts} = it + const nextData = gen.let("data", _`${it.data}${getProperty(dataProp)}`, true) + dataContextProps(nextData) + subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}` + subschema.parentDataProperty = _`${dataProp}` + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty] + } + + if (data !== undefined) { + const nextData = data instanceof Name ? data : gen.let("data", data, true) // replaceable if used once? + dataContextProps(nextData) + if (propertyName !== undefined) subschema.propertyName = propertyName + // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr + } + + if (dataTypes) subschema.dataTypes = dataTypes + + function dataContextProps(_nextData: Name): void { + subschema.data = _nextData + subschema.dataLevel = it.dataLevel + 1 + subschema.dataTypes = [] + it.definedProperties = new Set() + subschema.parentData = it.data + subschema.dataNames = [...it.dataNames, _nextData] + } +} + +export function extendSubschemaMode( + subschema: SubschemaContext, + {jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs +): void { + if (compositeRule !== undefined) subschema.compositeRule = compositeRule + if (createErrors !== undefined) subschema.createErrors = createErrors + if (allErrors !== undefined) subschema.allErrors = allErrors + subschema.jtdDiscriminator = jtdDiscriminator // not inherited + subschema.jtdMetadata = jtdMetadata // not inherited +} diff --git a/node_modules/ajv/lib/core.ts b/node_modules/ajv/lib/core.ts new file mode 100644 index 0000000000000000000000000000000000000000..81a2d33ceecf62a055722373bd26384cbb1a4ebb --- /dev/null +++ b/node_modules/ajv/lib/core.ts @@ -0,0 +1,892 @@ +export { + Format, + FormatDefinition, + AsyncFormatDefinition, + KeywordDefinition, + KeywordErrorDefinition, + CodeKeywordDefinition, + MacroKeywordDefinition, + FuncKeywordDefinition, + Vocabulary, + Schema, + SchemaObject, + AnySchemaObject, + AsyncSchema, + AnySchema, + ValidateFunction, + AsyncValidateFunction, + AnyValidateFunction, + ErrorObject, + ErrorNoParams, +} from "./types" + +export {SchemaCxt, SchemaObjCxt} from "./compile" +export interface Plugin { + (ajv: Ajv, options?: Opts): Ajv + [prop: string]: any +} + +export {KeywordCxt} from "./compile/validate" +export {DefinedError} from "./vocabularies/errors" +export {JSONType} from "./compile/rules" +export {JSONSchemaType} from "./types/json-schema" +export {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema" +export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen" + +import type { + Schema, + AnySchema, + AnySchemaObject, + SchemaObject, + AsyncSchema, + Vocabulary, + KeywordDefinition, + AddedKeywordDefinition, + AnyValidateFunction, + ValidateFunction, + AsyncValidateFunction, + ErrorObject, + Format, + AddedFormat, + RegExpEngine, + UriResolver, +} from "./types" +import type {JSONSchemaType} from "./types/json-schema" +import type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema" +import ValidationError from "./runtime/validation_error" +import MissingRefError from "./compile/ref_error" +import {getRules, ValidationRules, Rule, RuleGroup, JSONType} from "./compile/rules" +import {SchemaEnv, compileSchema, resolveSchema} from "./compile" +import {Code, ValueScope} from "./compile/codegen" +import {normalizeId, getSchemaRefs} from "./compile/resolve" +import {getJSONTypes} from "./compile/validate/dataType" +import {eachItem} from "./compile/util" +import * as $dataRefSchema from "./refs/data.json" + +import DefaultUriResolver from "./runtime/uri" + +const defaultRegExp: RegExpEngine = (str, flags) => new RegExp(str, flags) +defaultRegExp.code = "new RegExp" + +const META_IGNORE_OPTIONS: (keyof Options)[] = ["removeAdditional", "useDefaults", "coerceTypes"] +const EXT_SCOPE_NAMES = new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error", +]) + +export type Options = CurrentOptions & DeprecatedOptions + +export interface CurrentOptions { + // strict mode options (NEW) + strict?: boolean | "log" + strictSchema?: boolean | "log" + strictNumbers?: boolean | "log" + strictTypes?: boolean | "log" + strictTuples?: boolean | "log" + strictRequired?: boolean | "log" + allowMatchingProperties?: boolean // disables a strict mode restriction + allowUnionTypes?: boolean + validateFormats?: boolean + // validation and reporting options: + $data?: boolean + allErrors?: boolean + verbose?: boolean + discriminator?: boolean + unicodeRegExp?: boolean + timestamp?: "string" | "date" // JTD only + parseDate?: boolean // JTD only + allowDate?: boolean // JTD only + specialNumbers?: "fast" | "null" // JTD only + $comment?: + | true + | ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown) + formats?: {[Name in string]?: Format} + keywords?: Vocabulary + schemas?: AnySchema[] | {[Key in string]?: AnySchema} + logger?: Logger | false + loadSchema?: (uri: string) => Promise + // options to modify validated data: + removeAdditional?: boolean | "all" | "failing" + useDefaults?: boolean | "empty" + coerceTypes?: boolean | "array" + // advanced options: + next?: boolean // NEW + unevaluated?: boolean // NEW + dynamicRef?: boolean // NEW + schemaId?: "id" | "$id" + jtd?: boolean // NEW + meta?: SchemaObject | boolean + defaultMeta?: string | AnySchemaObject + validateSchema?: boolean | "log" + addUsedSchema?: boolean + inlineRefs?: boolean | number + passContext?: boolean + loopRequired?: number + loopEnum?: number // NEW + ownProperties?: boolean + multipleOfPrecision?: number + int32range?: boolean // JTD only + messages?: boolean + code?: CodeOptions // NEW + uriResolver?: UriResolver +} + +export interface CodeOptions { + es5?: boolean + esm?: boolean + lines?: boolean + optimize?: boolean | number + formats?: Code // code to require (or construct) map of available formats - for standalone code + source?: boolean + process?: (code: string, schema?: SchemaEnv) => string + regExp?: RegExpEngine +} + +interface InstanceCodeOptions extends CodeOptions { + regExp: RegExpEngine + optimize: number +} + +interface DeprecatedOptions { + /** @deprecated */ + ignoreKeywordsWithRef?: boolean + /** @deprecated */ + jsPropertySyntax?: boolean // added instead of jsonPointers + /** @deprecated */ + unicode?: boolean +} + +interface RemovedOptions { + format?: boolean + errorDataPath?: "object" | "property" + nullable?: boolean // "nullable" keyword is supported by default + jsonPointers?: boolean + extendRefs?: true | "ignore" | "fail" + missingRefs?: true | "ignore" | "fail" + processCode?: (code: string, schema?: SchemaEnv) => string + sourceCode?: boolean + strictDefaults?: boolean + strictKeywords?: boolean + uniqueItems?: boolean + unknownFormats?: true | string[] | "ignore" + cache?: any + serialize?: (schema: AnySchema) => unknown + ajvErrors?: boolean +} + +type OptionsInfo = { + [K in keyof T]-?: string | undefined +} + +const removedOptions: OptionsInfo = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: '"nullable" keyword is supported by default.', + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: '"uniqueItems" keyword is always validated.', + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now.", +} + +const deprecatedOptions: OptionsInfo = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: '"minLength"/"maxLength" account for unicode characters by default.', +} + +type RequiredInstanceOptions = { + [K in + | "strictSchema" + | "strictNumbers" + | "strictTypes" + | "strictTuples" + | "strictRequired" + | "inlineRefs" + | "loopRequired" + | "loopEnum" + | "meta" + | "messages" + | "schemaId" + | "addUsedSchema" + | "validateSchema" + | "validateFormats" + | "int32range" + | "unicodeRegExp" + | "uriResolver"]: NonNullable +} & {code: InstanceCodeOptions} + +export type InstanceOptions = Options & RequiredInstanceOptions + +const MAX_EXPRESSION = 200 + +// eslint-disable-next-line complexity +function requiredOptions(o: Options): RequiredInstanceOptions { + const s = o.strict + const _optz = o.code?.optimize + const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0 + const regExp = o.code?.regExp ?? defaultRegExp + const uriResolver = o.uriResolver ?? DefaultUriResolver + return { + strictSchema: o.strictSchema ?? s ?? true, + strictNumbers: o.strictNumbers ?? s ?? true, + strictTypes: o.strictTypes ?? s ?? "log", + strictTuples: o.strictTuples ?? s ?? "log", + strictRequired: o.strictRequired ?? s ?? false, + code: o.code ? {...o.code, optimize, regExp} : {optimize, regExp}, + loopRequired: o.loopRequired ?? MAX_EXPRESSION, + loopEnum: o.loopEnum ?? MAX_EXPRESSION, + meta: o.meta ?? true, + messages: o.messages ?? true, + inlineRefs: o.inlineRefs ?? true, + schemaId: o.schemaId ?? "$id", + addUsedSchema: o.addUsedSchema ?? true, + validateSchema: o.validateSchema ?? true, + validateFormats: o.validateFormats ?? true, + unicodeRegExp: o.unicodeRegExp ?? true, + int32range: o.int32range ?? true, + uriResolver: uriResolver, + } +} + +export interface Logger { + log(...args: unknown[]): unknown + warn(...args: unknown[]): unknown + error(...args: unknown[]): unknown +} + +export default class Ajv { + opts: InstanceOptions + errors?: ErrorObject[] | null // errors from the last validation + logger: Logger + // shared external scope values for compiled functions + readonly scope: ValueScope + readonly schemas: {[Key in string]?: SchemaEnv} = {} + readonly refs: {[Ref in string]?: SchemaEnv | string} = {} + readonly formats: {[Name in string]?: AddedFormat} = Object.create(null) + readonly RULES: ValidationRules + readonly _compilations: Set = new Set() + private readonly _loading: {[Ref in string]?: Promise} = {} + private readonly _cache: Map = new Map() + private readonly _metaOpts: InstanceOptions + + static ValidationError = ValidationError + static MissingRefError = MissingRefError + + constructor(opts: Options = {}) { + opts = this.opts = {...opts, ...requiredOptions(opts)} + const {es5, lines} = this.opts.code + + this.scope = new ValueScope({scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines}) + this.logger = getLogger(opts.logger) + const formatOpt = opts.validateFormats + opts.validateFormats = false + + this.RULES = getRules() + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED") + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn") + this._metaOpts = getMetaSchemaOptions.call(this) + + if (opts.formats) addInitialFormats.call(this) + this._addVocabularies() + this._addDefaultMetaSchema() + if (opts.keywords) addInitialKeywords.call(this, opts.keywords) + if (typeof opts.meta == "object") this.addMetaSchema(opts.meta) + addInitialSchemas.call(this) + opts.validateFormats = formatOpt + } + + _addVocabularies(): void { + this.addKeyword("$async") + } + + _addDefaultMetaSchema(): void { + const {$data, meta, schemaId} = this.opts + let _dataRefSchema: SchemaObject = $dataRefSchema + if (schemaId === "id") { + _dataRefSchema = {...$dataRefSchema} + _dataRefSchema.id = _dataRefSchema.$id + delete _dataRefSchema.$id + } + if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false) + } + + defaultMeta(): string | AnySchemaObject | undefined { + const {meta, schemaId} = this.opts + return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined) + } + + // Validate data using schema + // AnySchema will be compiled and cached using schema itself as a key for Map + validate(schema: Schema | string, data: unknown): boolean + validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise + validate(schema: Schema | JSONSchemaType | string, data: unknown): data is T + // Separated for type inference to work + // eslint-disable-next-line @typescript-eslint/unified-signatures + validate(schema: JTDSchemaType, data: unknown): data is T + // This overload is only intended for typescript inference, the first + // argument prevents manual type annotation from matching this overload + // eslint-disable-next-line @typescript-eslint/no-unused-vars + validate( + schema: T, + data: unknown + ): data is JTDDataType + // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents + validate(schema: AsyncSchema, data: unknown | T): Promise + validate(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise + validate( + schemaKeyRef: AnySchema | string, // key, ref or schema object + // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents + data: unknown | T // to be validated + ): boolean | Promise { + let v: AnyValidateFunction | undefined + if (typeof schemaKeyRef == "string") { + v = this.getSchema(schemaKeyRef) + if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`) + } else { + v = this.compile(schemaKeyRef) + } + + const valid = v(data) + if (!("$async" in v)) this.errors = v.errors + return valid + } + + // Create validation function for passed schema + // _meta: true if schema is a meta-schema. Used internally to compile meta schemas of user-defined keywords. + compile(schema: Schema | JSONSchemaType, _meta?: boolean): ValidateFunction + // Separated for type inference to work + // eslint-disable-next-line @typescript-eslint/unified-signatures + compile(schema: JTDSchemaType, _meta?: boolean): ValidateFunction + // This overload is only intended for typescript inference, the first + // argument prevents manual type annotation from matching this overload + // eslint-disable-next-line @typescript-eslint/no-unused-vars + compile( + schema: T, + _meta?: boolean + ): ValidateFunction> + compile(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction + compile(schema: AnySchema, _meta?: boolean): AnyValidateFunction + compile(schema: AnySchema, _meta?: boolean): AnyValidateFunction { + const sch = this._addSchema(schema, _meta) + return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction + } + + // Creates validating function for passed schema with asynchronous loading of missing schemas. + // `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema. + // TODO allow passing schema URI + // meta - optional true to compile meta-schema + compileAsync( + schema: SchemaObject | JSONSchemaType, + _meta?: boolean + ): Promise> + // Separated for type inference to work + // eslint-disable-next-line @typescript-eslint/unified-signatures + compileAsync(schema: JTDSchemaType, _meta?: boolean): Promise> + compileAsync(schema: AsyncSchema, meta?: boolean): Promise> + // eslint-disable-next-line @typescript-eslint/unified-signatures + compileAsync( + schema: AnySchemaObject, + meta?: boolean + ): Promise> + compileAsync( + schema: AnySchemaObject, + meta?: boolean + ): Promise> { + if (typeof this.opts.loadSchema != "function") { + throw new Error("options.loadSchema should be a function") + } + const {loadSchema} = this.opts + return runCompileAsync.call(this, schema, meta) + + async function runCompileAsync( + this: Ajv, + _schema: AnySchemaObject, + _meta?: boolean + ): Promise { + await loadMetaSchema.call(this, _schema.$schema) + const sch = this._addSchema(_schema, _meta) + return sch.validate || _compileAsync.call(this, sch) + } + + async function loadMetaSchema(this: Ajv, $ref?: string): Promise { + if ($ref && !this.getSchema($ref)) { + await runCompileAsync.call(this, {$ref}, true) + } + } + + async function _compileAsync(this: Ajv, sch: SchemaEnv): Promise { + try { + return this._compileSchemaEnv(sch) + } catch (e) { + if (!(e instanceof MissingRefError)) throw e + checkLoaded.call(this, e) + await loadMissingSchema.call(this, e.missingSchema) + return _compileAsync.call(this, sch) + } + } + + function checkLoaded(this: Ajv, {missingSchema: ref, missingRef}: MissingRefError): void { + if (this.refs[ref]) { + throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`) + } + } + + async function loadMissingSchema(this: Ajv, ref: string): Promise { + const _schema = await _loadSchema.call(this, ref) + if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema) + if (!this.refs[ref]) this.addSchema(_schema, ref, meta) + } + + async function _loadSchema(this: Ajv, ref: string): Promise { + const p = this._loading[ref] + if (p) return p + try { + return await (this._loading[ref] = loadSchema(ref)) + } finally { + delete this._loading[ref] + } + } + } + + // Adds schema to the instance + addSchema( + schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored + key?: string, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + _meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead. + ): Ajv { + if (Array.isArray(schema)) { + for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema) + return this + } + let id: string | undefined + if (typeof schema === "object") { + const {schemaId} = this.opts + id = schema[schemaId] + if (id !== undefined && typeof id != "string") { + throw new Error(`schema ${schemaId} must be string`) + } + } + key = normalizeId(key || id) + this._checkUnique(key) + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true) + return this + } + + // Add schema that will be used to validate other schemas + // options in META_IGNORE_OPTIONS are alway set to false + addMetaSchema( + schema: AnySchemaObject, + key?: string, // schema key + _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema + ): Ajv { + this.addSchema(schema, key, true, _validateSchema) + return this + } + + // Validate schema against its meta-schema + validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise { + if (typeof schema == "boolean") return true + let $schema: string | AnySchemaObject | undefined + $schema = schema.$schema + if ($schema !== undefined && typeof $schema != "string") { + throw new Error("$schema must be a string") + } + $schema = $schema || this.opts.defaultMeta || this.defaultMeta() + if (!$schema) { + this.logger.warn("meta-schema not available") + this.errors = null + return true + } + const valid = this.validate($schema, schema) + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText() + if (this.opts.validateSchema === "log") this.logger.error(message) + else throw new Error(message) + } + return valid + } + + // Get compiled schema by `key` or `ref`. + // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) + getSchema(keyRef: string): AnyValidateFunction | undefined { + let sch + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch + if (sch === undefined) { + const {schemaId} = this.opts + const root = new SchemaEnv({schema: {}, schemaId}) + sch = resolveSchema.call(this, root, keyRef) + if (!sch) return + this.refs[keyRef] = sch + } + return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction | undefined + } + + // Remove cached schema(s). + // If no parameter is passed all schemas but meta-schemas are removed. + // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef) + this._removeAllSchemas(this.refs, schemaKeyRef) + return this + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas) + this._removeAllSchemas(this.refs) + this._cache.clear() + return this + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef) + if (typeof sch == "object") this._cache.delete(sch.schema) + delete this.schemas[schemaKeyRef] + delete this.refs[schemaKeyRef] + return this + } + case "object": { + const cacheKey = schemaKeyRef + this._cache.delete(cacheKey) + let id = schemaKeyRef[this.opts.schemaId] + if (id) { + id = normalizeId(id) + delete this.schemas[id] + delete this.refs[id] + } + return this + } + default: + throw new Error("ajv.removeSchema: invalid parameter") + } + } + + // add "vocabulary" - a collection of keywords + addVocabulary(definitions: Vocabulary): Ajv { + for (const def of definitions) this.addKeyword(def) + return this + } + + addKeyword( + kwdOrDef: string | KeywordDefinition, + def?: KeywordDefinition // deprecated + ): Ajv { + let keyword: string | string[] + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword") + def.keyword = keyword + } + } else if (typeof kwdOrDef == "object" && def === undefined) { + def = kwdOrDef + keyword = def.keyword + if (Array.isArray(keyword) && !keyword.length) { + throw new Error("addKeywords: keyword must be string or non-empty array") + } + } else { + throw new Error("invalid addKeywords parameters") + } + + checkKeyword.call(this, keyword, def) + if (!def) { + eachItem(keyword, (kwd) => addRule.call(this, kwd)) + return this + } + keywordMetaschema.call(this, def) + const definition: AddedKeywordDefinition = { + ...def, + type: getJSONTypes(def.type), + schemaType: getJSONTypes(def.schemaType), + } + eachItem( + keyword, + definition.type.length === 0 + ? (k) => addRule.call(this, k, definition) + : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)) + ) + return this + } + + getKeyword(keyword: string): AddedKeywordDefinition | boolean { + const rule = this.RULES.all[keyword] + return typeof rule == "object" ? rule.definition : !!rule + } + + // Remove keyword + removeKeyword(keyword: string): Ajv { + // TODO return type should be Ajv + const {RULES} = this + delete RULES.keywords[keyword] + delete RULES.all[keyword] + for (const group of RULES.rules) { + const i = group.rules.findIndex((rule) => rule.keyword === keyword) + if (i >= 0) group.rules.splice(i, 1) + } + return this + } + + // Add format + addFormat(name: string, format: Format): Ajv { + if (typeof format == "string") format = new RegExp(format) + this.formats[name] = format + return this + } + + errorsText( + errors: ErrorObject[] | null | undefined = this.errors, // optional array of validation errors + {separator = ", ", dataVar = "data"}: ErrorsTextOptions = {} // optional options with properties `separator` and `dataVar` + ): string { + if (!errors || errors.length === 0) return "No errors" + return errors + .map((e) => `${dataVar}${e.instancePath} ${e.message}`) + .reduce((text, msg) => text + separator + msg) + } + + $dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject { + const rules = this.RULES.all + metaSchema = JSON.parse(JSON.stringify(metaSchema)) + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1) // first segment is an empty string + let keywords = metaSchema + for (const seg of segments) keywords = keywords[seg] as AnySchemaObject + + for (const key in rules) { + const rule = rules[key] + if (typeof rule != "object") continue + const {$data} = rule.definition + const schema = keywords[key] as AnySchemaObject | undefined + if ($data && schema) keywords[key] = schemaOrData(schema) + } + } + + return metaSchema + } + + private _removeAllSchemas(schemas: {[Ref in string]?: SchemaEnv | string}, regex?: RegExp): void { + for (const keyRef in schemas) { + const sch = schemas[keyRef] + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") { + delete schemas[keyRef] + } else if (sch && !sch.meta) { + this._cache.delete(sch.schema) + delete schemas[keyRef] + } + } + } + } + + _addSchema( + schema: AnySchema, + meta?: boolean, + baseId?: string, + validateSchema = this.opts.validateSchema, + addSchema = this.opts.addUsedSchema + ): SchemaEnv { + let id: string | undefined + const {schemaId} = this.opts + if (typeof schema == "object") { + id = schema[schemaId] + } else { + if (this.opts.jtd) throw new Error("schema must be object") + else if (typeof schema != "boolean") throw new Error("schema must be object or boolean") + } + let sch = this._cache.get(schema) + if (sch !== undefined) return sch + + baseId = normalizeId(id || baseId) + const localRefs = getSchemaRefs.call(this, schema, baseId) + sch = new SchemaEnv({schema, schemaId, meta, baseId, localRefs}) + this._cache.set(sch.schema, sch) + if (addSchema && !baseId.startsWith("#")) { + // TODO atm it is allowed to overwrite schemas without id (instead of not adding them) + if (baseId) this._checkUnique(baseId) + this.refs[baseId] = sch + } + if (validateSchema) this.validateSchema(schema, true) + return sch + } + + private _checkUnique(id: string): void { + if (this.schemas[id] || this.refs[id]) { + throw new Error(`schema with key or id "${id}" already exists`) + } + } + + private _compileSchemaEnv(sch: SchemaEnv): AnyValidateFunction { + if (sch.meta) this._compileMetaSchema(sch) + else compileSchema.call(this, sch) + + /* istanbul ignore if */ + if (!sch.validate) throw new Error("ajv implementation error") + return sch.validate + } + + private _compileMetaSchema(sch: SchemaEnv): void { + const currentOpts = this.opts + this.opts = this._metaOpts + try { + compileSchema.call(this, sch) + } finally { + this.opts = currentOpts + } + } +} + +export interface ErrorsTextOptions { + separator?: string + dataVar?: string +} + +function checkOptions( + this: Ajv, + checkOpts: OptionsInfo, + options: Options & RemovedOptions, + msg: string, + log: "warn" | "error" = "error" +): void { + for (const key in checkOpts) { + const opt = key as keyof typeof checkOpts + if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`) + } +} + +function getSchEnv(this: Ajv, keyRef: string): SchemaEnv | string | undefined { + keyRef = normalizeId(keyRef) // TODO tests fail without this line + return this.schemas[keyRef] || this.refs[keyRef] +} + +function addInitialSchemas(this: Ajv): void { + const optsSchemas = this.opts.schemas + if (!optsSchemas) return + if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas) + else for (const key in optsSchemas) this.addSchema(optsSchemas[key] as AnySchema, key) +} + +function addInitialFormats(this: Ajv): void { + for (const name in this.opts.formats) { + const format = this.opts.formats[name] + if (format) this.addFormat(name, format) + } +} + +function addInitialKeywords( + this: Ajv, + defs: Vocabulary | {[K in string]?: KeywordDefinition} +): void { + if (Array.isArray(defs)) { + this.addVocabulary(defs) + return + } + this.logger.warn("keywords option as map is deprecated, pass array") + for (const keyword in defs) { + const def = defs[keyword] as KeywordDefinition + if (!def.keyword) def.keyword = keyword + this.addKeyword(def) + } +} + +function getMetaSchemaOptions(this: Ajv): InstanceOptions { + const metaOpts = {...this.opts} + for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt] + return metaOpts +} + +const noLogs = {log() {}, warn() {}, error() {}} + +function getLogger(logger?: Partial | false): Logger { + if (logger === false) return noLogs + if (logger === undefined) return console + if (logger.log && logger.warn && logger.error) return logger as Logger + throw new Error("logger must implement log, warn and error methods") +} + +const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i + +function checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void { + const {RULES} = this + eachItem(keyword, (kwd) => { + if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`) + if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`) + }) + if (!def) return + if (def.$data && !("code" in def || "validate" in def)) { + throw new Error('$data keyword must have "code" or "validate" function') + } +} + +function addRule( + this: Ajv, + keyword: string, + definition?: AddedKeywordDefinition, + dataType?: JSONType +): void { + const post = definition?.post + if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"') + const {RULES} = this + let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType) + if (!ruleGroup) { + ruleGroup = {type: dataType, rules: []} + RULES.rules.push(ruleGroup) + } + RULES.keywords[keyword] = true + if (!definition) return + + const rule: Rule = { + keyword, + definition: { + ...definition, + type: getJSONTypes(definition.type), + schemaType: getJSONTypes(definition.schemaType), + }, + } + if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before) + else ruleGroup.rules.push(rule) + RULES.all[keyword] = rule + definition.implements?.forEach((kwd) => this.addKeyword(kwd)) +} + +function addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void { + const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before) + if (i >= 0) { + ruleGroup.rules.splice(i, 0, rule) + } else { + ruleGroup.rules.push(rule) + this.logger.warn(`rule ${before} is not defined`) + } +} + +function keywordMetaschema(this: Ajv, def: KeywordDefinition): void { + let {metaSchema} = def + if (metaSchema === undefined) return + if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema) + def.validateSchema = this.compile(metaSchema, true) +} + +const $dataRef = { + $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", +} + +function schemaOrData(schema: AnySchema): AnySchemaObject { + return {anyOf: [schema, $dataRef]} +} diff --git a/node_modules/ajv/lib/jtd.ts b/node_modules/ajv/lib/jtd.ts new file mode 100644 index 0000000000000000000000000000000000000000..a7e7bce3ba39a6339b9377cee40429daba39af72 --- /dev/null +++ b/node_modules/ajv/lib/jtd.ts @@ -0,0 +1,132 @@ +import type {AnySchemaObject, SchemaObject, JTDParser} from "./types" +import type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema" +import AjvCore, {CurrentOptions} from "./core" +import jtdVocabulary from "./vocabularies/jtd" +import jtdMetaSchema from "./refs/jtd-schema" +import compileSerializer from "./compile/jtd/serialize" +import compileParser from "./compile/jtd/parse" +import {SchemaEnv} from "./compile" + +const META_SCHEMA_ID = "JTD-meta-schema" + +type JTDOptions = CurrentOptions & { + // strict mode options not supported with JTD: + strict?: never + allowMatchingProperties?: never + allowUnionTypes?: never + validateFormats?: never + // validation and reporting options not supported with JTD: + $data?: never + verbose?: boolean + $comment?: never + formats?: never + loadSchema?: never + // options to modify validated data: + useDefaults?: never + coerceTypes?: never + // advanced options: + next?: never + unevaluated?: never + dynamicRef?: never + meta?: boolean + defaultMeta?: never + inlineRefs?: boolean + loopRequired?: never + multipleOfPrecision?: never +} + +export class Ajv extends AjvCore { + constructor(opts: JTDOptions = {}) { + super({ + ...opts, + jtd: true, + }) + } + + _addVocabularies(): void { + super._addVocabularies() + this.addVocabulary(jtdVocabulary) + } + + _addDefaultMetaSchema(): void { + super._addDefaultMetaSchema() + if (!this.opts.meta) return + this.addMetaSchema(jtdMetaSchema, META_SCHEMA_ID, false) + } + + defaultMeta(): string | AnySchemaObject | undefined { + return (this.opts.defaultMeta = + super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)) + } + + compileSerializer(schema: SchemaObject): (data: T) => string + // Separated for type inference to work + // eslint-disable-next-line @typescript-eslint/unified-signatures + compileSerializer(schema: JTDSchemaType): (data: T) => string + compileSerializer(schema: SchemaObject): (data: T) => string { + const sch = this._addSchema(schema) + return sch.serialize || this._compileSerializer(sch) + } + + compileParser(schema: SchemaObject): JTDParser + // Separated for type inference to work + // eslint-disable-next-line @typescript-eslint/unified-signatures + compileParser(schema: JTDSchemaType): JTDParser + compileParser(schema: SchemaObject): JTDParser { + const sch = this._addSchema(schema) + return (sch.parse || this._compileParser(sch)) as JTDParser + } + + private _compileSerializer(sch: SchemaEnv): (data: T) => string { + compileSerializer.call(this, sch, (sch.schema as AnySchemaObject).definitions || {}) + /* istanbul ignore if */ + if (!sch.serialize) throw new Error("ajv implementation error") + return sch.serialize + } + + private _compileParser(sch: SchemaEnv): JTDParser { + compileParser.call(this, sch, (sch.schema as AnySchemaObject).definitions || {}) + /* istanbul ignore if */ + if (!sch.parse) throw new Error("ajv implementation error") + return sch.parse + } +} + +module.exports = exports = Ajv +module.exports.Ajv = Ajv +Object.defineProperty(exports, "__esModule", {value: true}) + +export default Ajv + +export { + Format, + FormatDefinition, + AsyncFormatDefinition, + KeywordDefinition, + KeywordErrorDefinition, + CodeKeywordDefinition, + MacroKeywordDefinition, + FuncKeywordDefinition, + Vocabulary, + Schema, + SchemaObject, + AnySchemaObject, + AsyncSchema, + AnySchema, + ValidateFunction, + AsyncValidateFunction, + ErrorObject, + ErrorNoParams, + JTDParser, +} from "./types" + +export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core" +export {SchemaCxt, SchemaObjCxt} from "./compile" +export {KeywordCxt} from "./compile/validate" +export {JTDErrorObject} from "./vocabularies/jtd" +export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen" + +export {JTDSchemaType, SomeJTDSchemaType, JTDDataType} +export {JTDOptions} +export {default as ValidationError} from "./runtime/validation_error" +export {default as MissingRefError} from "./compile/ref_error" diff --git a/node_modules/ajv/lib/refs/data.json b/node_modules/ajv/lib/refs/data.json new file mode 100644 index 0000000000000000000000000000000000000000..9ffc9f5ce05484799308bc4c78fd3a8822e9af53 --- /dev/null +++ b/node_modules/ajv/lib/refs/data.json @@ -0,0 +1,13 @@ +{ + "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)", + "type": "object", + "required": ["$data"], + "properties": { + "$data": { + "type": "string", + "anyOf": [{"format": "relative-json-pointer"}, {"format": "json-pointer"}] + } + }, + "additionalProperties": false +} diff --git a/node_modules/ajv/lib/refs/json-schema-2019-09/index.ts b/node_modules/ajv/lib/refs/json-schema-2019-09/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..b6ea7195f019ef1b91c45517db08f42daa2f0673 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2019-09/index.ts @@ -0,0 +1,28 @@ +import type Ajv from "../../core" +import type {AnySchemaObject} from "../../types" +import * as metaSchema from "./schema.json" +import * as applicator from "./meta/applicator.json" +import * as content from "./meta/content.json" +import * as core from "./meta/core.json" +import * as format from "./meta/format.json" +import * as metadata from "./meta/meta-data.json" +import * as validation from "./meta/validation.json" + +const META_SUPPORT_DATA = ["/properties"] + +export default function addMetaSchema2019(this: Ajv, $data?: boolean): Ajv { + ;[ + metaSchema, + applicator, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation), + ].forEach((sch) => this.addMetaSchema(sch, undefined, false)) + return this + + function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2019-09/meta/applicator.json b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/applicator.json new file mode 100644 index 0000000000000000000000000000000000000000..c5e91cf2ac8469eccf444cf6501dba80dccb5c63 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/applicator.json @@ -0,0 +1,53 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/applicator", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/applicator": true + }, + "$recursiveAnchor": true, + + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "additionalItems": {"$recursiveRef": "#"}, + "unevaluatedItems": {"$recursiveRef": "#"}, + "items": { + "anyOf": [{"$recursiveRef": "#"}, {"$ref": "#/$defs/schemaArray"}] + }, + "contains": {"$recursiveRef": "#"}, + "additionalProperties": {"$recursiveRef": "#"}, + "unevaluatedProperties": {"$recursiveRef": "#"}, + "properties": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "propertyNames": {"format": "regex"}, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { + "$recursiveRef": "#" + } + }, + "propertyNames": {"$recursiveRef": "#"}, + "if": {"$recursiveRef": "#"}, + "then": {"$recursiveRef": "#"}, + "else": {"$recursiveRef": "#"}, + "allOf": {"$ref": "#/$defs/schemaArray"}, + "anyOf": {"$ref": "#/$defs/schemaArray"}, + "oneOf": {"$ref": "#/$defs/schemaArray"}, + "not": {"$recursiveRef": "#"} + }, + "$defs": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$recursiveRef": "#"} + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2019-09/meta/content.json b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/content.json new file mode 100644 index 0000000000000000000000000000000000000000..b8f63734343046b3d4b74bf8a59f2380dbc67fc3 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/content.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/content", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + + "title": "Content vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "contentMediaType": {"type": "string"}, + "contentEncoding": {"type": "string"}, + "contentSchema": {"$recursiveRef": "#"} + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2019-09/meta/core.json b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/core.json new file mode 100644 index 0000000000000000000000000000000000000000..f71adbff04fe9ecc6a828823ad5dfa7366f1a60f --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/core.json @@ -0,0 +1,57 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/core", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true + }, + "$recursiveAnchor": true, + + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$anchor": { + "type": "string", + "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveRef": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveAnchor": { + "type": "boolean", + "default": false + }, + "$vocabulary": { + "type": "object", + "propertyNames": { + "type": "string", + "format": "uri" + }, + "additionalProperties": { + "type": "boolean" + } + }, + "$comment": { + "type": "string" + }, + "$defs": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2019-09/meta/format.json b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/format.json new file mode 100644 index 0000000000000000000000000000000000000000..03ccfce26efeaff5a6e223be5154f238f633c16e --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/format.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/format", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/format": true + }, + "$recursiveAnchor": true, + + "title": "Format vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "format": {"type": "string"} + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2019-09/meta/meta-data.json b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/meta-data.json new file mode 100644 index 0000000000000000000000000000000000000000..0e194326fa133b077af409486ebe1e2dca83feff --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/meta-data.json @@ -0,0 +1,37 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/meta-data", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/meta-data": true + }, + "$recursiveAnchor": true, + + "title": "Meta-data vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2019-09/meta/validation.json b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/validation.json new file mode 100644 index 0000000000000000000000000000000000000000..7027a1279a014a74c170a2558100d2ca37eecac0 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2019-09/meta/validation.json @@ -0,0 +1,90 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/validation", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/validation": true + }, + "$recursiveAnchor": true, + + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/$defs/nonNegativeInteger"}, + "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": {"$ref": "#/$defs/nonNegativeInteger"}, + "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": {"$ref": "#/$defs/nonNegativeInteger"}, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"}, + "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/$defs/stringArray"}, + "dependentRequired": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/stringArray" + } + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "type": { + "anyOf": [ + {"$ref": "#/$defs/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/$defs/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2019-09/schema.json b/node_modules/ajv/lib/refs/json-schema-2019-09/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..54eb7157afed6957bd7074068d7ad99498c668f3 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2019-09/schema.json @@ -0,0 +1,39 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/schema", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true, + "https://json-schema.org/draft/2019-09/vocab/applicator": true, + "https://json-schema.org/draft/2019-09/vocab/validation": true, + "https://json-schema.org/draft/2019-09/vocab/meta-data": true, + "https://json-schema.org/draft/2019-09/vocab/format": false, + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + + "title": "Core and Validation specifications meta-schema", + "allOf": [ + {"$ref": "meta/core"}, + {"$ref": "meta/applicator"}, + {"$ref": "meta/validation"}, + {"$ref": "meta/meta-data"}, + {"$ref": "meta/format"}, + {"$ref": "meta/content"} + ], + "type": ["object", "boolean"], + "properties": { + "definitions": { + "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"", + "type": "object", + "additionalProperties": { + "anyOf": [{"$recursiveRef": "#"}, {"$ref": "meta/validation#/$defs/stringArray"}] + } + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/index.ts b/node_modules/ajv/lib/refs/json-schema-2020-12/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e850d08b5cdc8ec9f41ff69581c11844c9c60af --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/index.ts @@ -0,0 +1,30 @@ +import type Ajv from "../../core" +import type {AnySchemaObject} from "../../types" +import * as metaSchema from "./schema.json" +import * as applicator from "./meta/applicator.json" +import * as unevaluated from "./meta/unevaluated.json" +import * as content from "./meta/content.json" +import * as core from "./meta/core.json" +import * as format from "./meta/format-annotation.json" +import * as metadata from "./meta/meta-data.json" +import * as validation from "./meta/validation.json" + +const META_SUPPORT_DATA = ["/properties"] + +export default function addMetaSchema2020(this: Ajv, $data?: boolean): Ajv { + ;[ + metaSchema, + applicator, + unevaluated, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation), + ].forEach((sch) => this.addMetaSchema(sch, undefined, false)) + return this + + function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/meta/applicator.json b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/applicator.json new file mode 100644 index 0000000000000000000000000000000000000000..674c913dab00c66865d82027bdf7748e157365fa --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/applicator.json @@ -0,0 +1,48 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/applicator", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/applicator": true + }, + "$dynamicAnchor": "meta", + + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "prefixItems": {"$ref": "#/$defs/schemaArray"}, + "items": {"$dynamicRef": "#meta"}, + "contains": {"$dynamicRef": "#meta"}, + "additionalProperties": {"$dynamicRef": "#meta"}, + "properties": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "propertyNames": {"format": "regex"}, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "default": {} + }, + "propertyNames": {"$dynamicRef": "#meta"}, + "if": {"$dynamicRef": "#meta"}, + "then": {"$dynamicRef": "#meta"}, + "else": {"$dynamicRef": "#meta"}, + "allOf": {"$ref": "#/$defs/schemaArray"}, + "anyOf": {"$ref": "#/$defs/schemaArray"}, + "oneOf": {"$ref": "#/$defs/schemaArray"}, + "not": {"$dynamicRef": "#meta"} + }, + "$defs": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$dynamicRef": "#meta"} + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/meta/content.json b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/content.json new file mode 100644 index 0000000000000000000000000000000000000000..2ae23ddb5cc30cce43646dc58b86f61b1dc7fc4c --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/content.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/content", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + + "title": "Content vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "contentEncoding": {"type": "string"}, + "contentMediaType": {"type": "string"}, + "contentSchema": {"$dynamicRef": "#meta"} + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/meta/core.json b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/core.json new file mode 100644 index 0000000000000000000000000000000000000000..4c8e5cb61657ff226186dd96e5dea6e15eb102e1 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/core.json @@ -0,0 +1,51 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/core", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true + }, + "$dynamicAnchor": "meta", + + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "$ref": "#/$defs/uriReferenceString", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": {"$ref": "#/$defs/uriString"}, + "$ref": {"$ref": "#/$defs/uriReferenceString"}, + "$anchor": {"$ref": "#/$defs/anchorString"}, + "$dynamicRef": {"$ref": "#/$defs/uriReferenceString"}, + "$dynamicAnchor": {"$ref": "#/$defs/anchorString"}, + "$vocabulary": { + "type": "object", + "propertyNames": {"$ref": "#/$defs/uriString"}, + "additionalProperties": { + "type": "boolean" + } + }, + "$comment": { + "type": "string" + }, + "$defs": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"} + } + }, + "$defs": { + "anchorString": { + "type": "string", + "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" + }, + "uriString": { + "type": "string", + "format": "uri" + }, + "uriReferenceString": { + "type": "string", + "format": "uri-reference" + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/meta/format-annotation.json b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/format-annotation.json new file mode 100644 index 0000000000000000000000000000000000000000..83c26e35f0042ebada16aba9b0c42bedd46bcb24 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/format-annotation.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true + }, + "$dynamicAnchor": "meta", + + "title": "Format vocabulary meta-schema for annotation results", + "type": ["object", "boolean"], + "properties": { + "format": {"type": "string"} + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/meta/meta-data.json b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/meta-data.json new file mode 100644 index 0000000000000000000000000000000000000000..11946fb5019a3564afb38270af3d7806af39978c --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/meta-data.json @@ -0,0 +1,37 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/meta-data": true + }, + "$dynamicAnchor": "meta", + + "title": "Meta-data vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/meta/unevaluated.json b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/unevaluated.json new file mode 100644 index 0000000000000000000000000000000000000000..5e4b203b2c26905ccef5ab90c627aaa19ee708bb --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/unevaluated.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true + }, + "$dynamicAnchor": "meta", + + "title": "Unevaluated applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "unevaluatedItems": {"$dynamicRef": "#meta"}, + "unevaluatedProperties": {"$dynamicRef": "#meta"} + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/meta/validation.json b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/validation.json new file mode 100644 index 0000000000000000000000000000000000000000..e0ae13d9d2063403c60e88282701b4b8f6ccd5f5 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/meta/validation.json @@ -0,0 +1,90 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/validation", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/validation": true + }, + "$dynamicAnchor": "meta", + + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "type": { + "anyOf": [ + {"$ref": "#/$defs/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/$defs/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/$defs/nonNegativeInteger"}, + "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": {"$ref": "#/$defs/nonNegativeInteger"}, + "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": {"$ref": "#/$defs/nonNegativeInteger"}, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"}, + "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/$defs/stringArray"}, + "dependentRequired": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/stringArray" + } + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-2020-12/schema.json b/node_modules/ajv/lib/refs/json-schema-2020-12/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..1c68270fdc6e4fa807c75bb32391ce8cb530a497 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-2020-12/schema.json @@ -0,0 +1,55 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/schema", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://json-schema.org/draft/2020-12/vocab/meta-data": true, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + + "title": "Core and Validation specifications meta-schema", + "allOf": [ + {"$ref": "meta/core"}, + {"$ref": "meta/applicator"}, + {"$ref": "meta/unevaluated"}, + {"$ref": "meta/validation"}, + {"$ref": "meta/meta-data"}, + {"$ref": "meta/format-annotation"}, + {"$ref": "meta/content"} + ], + "type": ["object", "boolean"], + "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", + "properties": { + "definitions": { + "$comment": "\"definitions\" has been replaced by \"$defs\".", + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "deprecated": true, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", + "type": "object", + "additionalProperties": { + "anyOf": [{"$dynamicRef": "#meta"}, {"$ref": "meta/validation#/$defs/stringArray"}] + }, + "deprecated": true, + "default": {} + }, + "$recursiveAnchor": { + "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", + "$ref": "meta/core#/$defs/anchorString", + "deprecated": true + }, + "$recursiveRef": { + "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", + "$ref": "meta/core#/$defs/uriReferenceString", + "deprecated": true + } + } +} diff --git a/node_modules/ajv/lib/refs/json-schema-draft-06.json b/node_modules/ajv/lib/refs/json-schema-draft-06.json new file mode 100644 index 0000000000000000000000000000000000000000..5410064ba8df9315d61a34a66245311f1d18db8e --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-draft-06.json @@ -0,0 +1,137 @@ +{ + "$schema": "http://json-schema.org/draft-06/schema#", + "$id": "http://json-schema.org/draft-06/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$ref": "#"} + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}] + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": {}, + "examples": { + "type": "array", + "items": {} + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/definitions/nonNegativeInteger"}, + "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": {"$ref": "#"}, + "items": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}], + "default": {} + }, + "maxItems": {"$ref": "#/definitions/nonNegativeInteger"}, + "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": {"$ref": "#"}, + "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"}, + "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/definitions/stringArray"}, + "additionalProperties": {"$ref": "#"}, + "definitions": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}] + } + }, + "propertyNames": {"$ref": "#"}, + "const": {}, + "enum": { + "type": "array", + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + {"$ref": "#/definitions/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/definitions/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": {"type": "string"}, + "allOf": {"$ref": "#/definitions/schemaArray"}, + "anyOf": {"$ref": "#/definitions/schemaArray"}, + "oneOf": {"$ref": "#/definitions/schemaArray"}, + "not": {"$ref": "#"} + }, + "default": {} +} diff --git a/node_modules/ajv/lib/refs/json-schema-draft-07.json b/node_modules/ajv/lib/refs/json-schema-draft-07.json new file mode 100644 index 0000000000000000000000000000000000000000..6a74851043623c67cbe2e1cd206da447aff752c3 --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-draft-07.json @@ -0,0 +1,151 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "http://json-schema.org/draft-07/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$ref": "#"} + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}] + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$comment": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/definitions/nonNegativeInteger"}, + "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": {"$ref": "#"}, + "items": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}], + "default": true + }, + "maxItems": {"$ref": "#/definitions/nonNegativeInteger"}, + "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": {"$ref": "#"}, + "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"}, + "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/definitions/stringArray"}, + "additionalProperties": {"$ref": "#"}, + "definitions": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "propertyNames": {"format": "regex"}, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}] + } + }, + "propertyNames": {"$ref": "#"}, + "const": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + {"$ref": "#/definitions/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/definitions/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": {"type": "string"}, + "contentMediaType": {"type": "string"}, + "contentEncoding": {"type": "string"}, + "if": {"$ref": "#"}, + "then": {"$ref": "#"}, + "else": {"$ref": "#"}, + "allOf": {"$ref": "#/definitions/schemaArray"}, + "anyOf": {"$ref": "#/definitions/schemaArray"}, + "oneOf": {"$ref": "#/definitions/schemaArray"}, + "not": {"$ref": "#"} + }, + "default": true +} diff --git a/node_modules/ajv/lib/refs/json-schema-secure.json b/node_modules/ajv/lib/refs/json-schema-secure.json new file mode 100644 index 0000000000000000000000000000000000000000..3968abd5d97e7b2cf87db34d5eb211c090b8700f --- /dev/null +++ b/node_modules/ajv/lib/refs/json-schema-secure.json @@ -0,0 +1,88 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/json-schema-secure.json#", + "title": "Meta-schema for the security assessment of JSON Schemas", + "description": "If a JSON AnySchema fails validation against this meta-schema, it may be unsafe to validate untrusted data", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$ref": "#"} + } + }, + "dependencies": { + "patternProperties": { + "description": "prevent slow validation of large property names", + "required": ["propertyNames"], + "properties": { + "propertyNames": { + "required": ["maxLength"] + } + } + }, + "uniqueItems": { + "description": "prevent slow validation of large non-scalar arrays", + "if": { + "properties": { + "uniqueItems": {"const": true}, + "items": { + "properties": { + "type": { + "anyOf": [ + { + "enum": ["object", "array"] + }, + { + "type": "array", + "contains": {"enum": ["object", "array"]} + } + ] + } + } + } + } + }, + "then": { + "required": ["maxItems"] + } + }, + "pattern": { + "description": "prevent slow pattern matching of large strings", + "required": ["maxLength"] + }, + "format": { + "description": "prevent slow format validation of large strings", + "required": ["maxLength"] + } + }, + "properties": { + "additionalItems": {"$ref": "#"}, + "additionalProperties": {"$ref": "#"}, + "dependencies": { + "additionalProperties": { + "anyOf": [{"type": "array"}, {"$ref": "#"}] + } + }, + "items": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}] + }, + "definitions": { + "additionalProperties": {"$ref": "#"} + }, + "patternProperties": { + "additionalProperties": {"$ref": "#"} + }, + "properties": { + "additionalProperties": {"$ref": "#"} + }, + "if": {"$ref": "#"}, + "then": {"$ref": "#"}, + "else": {"$ref": "#"}, + "allOf": {"$ref": "#/definitions/schemaArray"}, + "anyOf": {"$ref": "#/definitions/schemaArray"}, + "oneOf": {"$ref": "#/definitions/schemaArray"}, + "not": {"$ref": "#"}, + "contains": {"$ref": "#"}, + "propertyNames": {"$ref": "#"} + } +} diff --git a/node_modules/ajv/lib/refs/jtd-schema.ts b/node_modules/ajv/lib/refs/jtd-schema.ts new file mode 100644 index 0000000000000000000000000000000000000000..c0198128985137b24b13e40e6f41431f37b86647 --- /dev/null +++ b/node_modules/ajv/lib/refs/jtd-schema.ts @@ -0,0 +1,130 @@ +import {SchemaObject} from "../types" + +type MetaSchema = (root: boolean) => SchemaObject + +const shared: MetaSchema = (root) => { + const sch: SchemaObject = { + nullable: {type: "boolean"}, + metadata: { + optionalProperties: { + union: {elements: {ref: "schema"}}, + }, + additionalProperties: true, + }, + } + if (root) sch.definitions = {values: {ref: "schema"}} + return sch +} + +const emptyForm: MetaSchema = (root) => ({ + optionalProperties: shared(root), +}) + +const refForm: MetaSchema = (root) => ({ + properties: { + ref: {type: "string"}, + }, + optionalProperties: shared(root), +}) + +const typeForm: MetaSchema = (root) => ({ + properties: { + type: { + enum: [ + "boolean", + "timestamp", + "string", + "float32", + "float64", + "int8", + "uint8", + "int16", + "uint16", + "int32", + "uint32", + ], + }, + }, + optionalProperties: shared(root), +}) + +const enumForm: MetaSchema = (root) => ({ + properties: { + enum: {elements: {type: "string"}}, + }, + optionalProperties: shared(root), +}) + +const elementsForm: MetaSchema = (root) => ({ + properties: { + elements: {ref: "schema"}, + }, + optionalProperties: shared(root), +}) + +const propertiesForm: MetaSchema = (root) => ({ + properties: { + properties: {values: {ref: "schema"}}, + }, + optionalProperties: { + optionalProperties: {values: {ref: "schema"}}, + additionalProperties: {type: "boolean"}, + ...shared(root), + }, +}) + +const optionalPropertiesForm: MetaSchema = (root) => ({ + properties: { + optionalProperties: {values: {ref: "schema"}}, + }, + optionalProperties: { + additionalProperties: {type: "boolean"}, + ...shared(root), + }, +}) + +const discriminatorForm: MetaSchema = (root) => ({ + properties: { + discriminator: {type: "string"}, + mapping: { + values: { + metadata: { + union: [propertiesForm(false), optionalPropertiesForm(false)], + }, + }, + }, + }, + optionalProperties: shared(root), +}) + +const valuesForm: MetaSchema = (root) => ({ + properties: { + values: {ref: "schema"}, + }, + optionalProperties: shared(root), +}) + +const schema: MetaSchema = (root) => ({ + metadata: { + union: [ + emptyForm, + refForm, + typeForm, + enumForm, + elementsForm, + propertiesForm, + optionalPropertiesForm, + discriminatorForm, + valuesForm, + ].map((s) => s(root)), + }, +}) + +const jtdMetaSchema: SchemaObject = { + definitions: { + schema: schema(false), + }, + ...schema(true), +} + +export default jtdMetaSchema diff --git a/node_modules/ajv/lib/runtime/equal.ts b/node_modules/ajv/lib/runtime/equal.ts new file mode 100644 index 0000000000000000000000000000000000000000..3cb00631a2363720e822255d0911a54439512c3c --- /dev/null +++ b/node_modules/ajv/lib/runtime/equal.ts @@ -0,0 +1,7 @@ +// https://github.com/ajv-validator/ajv/issues/889 +import * as equal from "fast-deep-equal" + +type Equal = typeof equal & {code: string} +;(equal as Equal).code = 'require("ajv/dist/runtime/equal").default' + +export default equal as Equal diff --git a/node_modules/ajv/lib/runtime/parseJson.ts b/node_modules/ajv/lib/runtime/parseJson.ts new file mode 100644 index 0000000000000000000000000000000000000000..472e5e50786f2cff1092ac1353508ac0fcebce9e --- /dev/null +++ b/node_modules/ajv/lib/runtime/parseJson.ts @@ -0,0 +1,177 @@ +const rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/ + +export function parseJson(s: string, pos: number): unknown { + let endPos: number | undefined + parseJson.message = undefined + let matches: RegExpExecArray | null + if (pos) s = s.slice(pos) + try { + parseJson.position = pos + s.length + return JSON.parse(s) + } catch (e) { + matches = rxParseJson.exec((e as Error).message) + if (!matches) { + parseJson.message = "unexpected end" + return undefined + } + endPos = +matches[1] + const c = s[endPos] + s = s.slice(0, endPos) + parseJson.position = pos + endPos + try { + return JSON.parse(s) + } catch (e1) { + parseJson.message = `unexpected token ${c}` + return undefined + } + } +} + +parseJson.message = undefined as string | undefined +parseJson.position = 0 as number +parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson' + +export function parseJsonNumber(s: string, pos: number, maxDigits?: number): number | undefined { + let numStr = "" + let c: string + parseJsonNumber.message = undefined + if (s[pos] === "-") { + numStr += "-" + pos++ + } + if (s[pos] === "0") { + numStr += "0" + pos++ + } else { + if (!parseDigits(maxDigits)) { + errorMessage() + return undefined + } + } + if (maxDigits) { + parseJsonNumber.position = pos + return +numStr + } + if (s[pos] === ".") { + numStr += "." + pos++ + if (!parseDigits()) { + errorMessage() + return undefined + } + } + if (((c = s[pos]), c === "e" || c === "E")) { + numStr += "e" + pos++ + if (((c = s[pos]), c === "+" || c === "-")) { + numStr += c + pos++ + } + if (!parseDigits()) { + errorMessage() + return undefined + } + } + parseJsonNumber.position = pos + return +numStr + + function parseDigits(maxLen?: number): boolean { + let digit = false + while (((c = s[pos]), c >= "0" && c <= "9" && (maxLen === undefined || maxLen-- > 0))) { + digit = true + numStr += c + pos++ + } + return digit + } + + function errorMessage(): void { + parseJsonNumber.position = pos + parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end" + } +} + +parseJsonNumber.message = undefined as string | undefined +parseJsonNumber.position = 0 as number +parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber' + +const escapedChars: {[X in string]?: string} = { + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t", + '"': '"', + "/": "/", + "\\": "\\", +} + +const CODE_A: number = "a".charCodeAt(0) +const CODE_0: number = "0".charCodeAt(0) + +export function parseJsonString(s: string, pos: number): string | undefined { + let str = "" + let c: string | undefined + parseJsonString.message = undefined + // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition + while (true) { + c = s[pos++] + if (c === '"') break + if (c === "\\") { + c = s[pos] + if (c in escapedChars) { + str += escapedChars[c] + pos++ + } else if (c === "u") { + pos++ + let count = 4 + let code = 0 + while (count--) { + code <<= 4 + c = s[pos] + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (c === undefined) { + errorMessage("unexpected end") + return undefined + } + c = c.toLowerCase() + if (c >= "a" && c <= "f") { + code += c.charCodeAt(0) - CODE_A + 10 + } else if (c >= "0" && c <= "9") { + code += c.charCodeAt(0) - CODE_0 + } else { + errorMessage(`unexpected token ${c}`) + return undefined + } + pos++ + } + str += String.fromCharCode(code) + } else { + errorMessage(`unexpected token ${c}`) + return undefined + } + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + } else if (c === undefined) { + errorMessage("unexpected end") + return undefined + } else { + if (c.charCodeAt(0) >= 0x20) { + str += c + } else { + errorMessage(`unexpected token ${c}`) + return undefined + } + } + } + parseJsonString.position = pos + return str + + function errorMessage(msg: string): void { + parseJsonString.position = pos + parseJsonString.message = msg + } +} + +parseJsonString.message = undefined as string | undefined +parseJsonString.position = 0 as number +parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString' diff --git a/node_modules/ajv/lib/runtime/quote.ts b/node_modules/ajv/lib/runtime/quote.ts new file mode 100644 index 0000000000000000000000000000000000000000..1160e6a23807cf7fc0f4d036ddc45bd962562275 --- /dev/null +++ b/node_modules/ajv/lib/runtime/quote.ts @@ -0,0 +1,31 @@ +const rxEscapable = + // eslint-disable-next-line no-control-regex, no-misleading-character-class + /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g + +const escaped: {[K in string]?: string} = { + "\b": "\\b", + "\t": "\\t", + "\n": "\\n", + "\f": "\\f", + "\r": "\\r", + '"': '\\"', + "\\": "\\\\", +} + +export default function quote(s: string): string { + rxEscapable.lastIndex = 0 + return ( + '"' + + (rxEscapable.test(s) + ? s.replace(rxEscapable, (a) => { + const c = escaped[a] + return typeof c === "string" + ? c + : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4) + }) + : s) + + '"' + ) +} + +quote.code = 'require("ajv/dist/runtime/quote").default' diff --git a/node_modules/ajv/lib/runtime/re2.ts b/node_modules/ajv/lib/runtime/re2.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c769bc7aefc5aa1924e2be877d39bc59670ab3f --- /dev/null +++ b/node_modules/ajv/lib/runtime/re2.ts @@ -0,0 +1,6 @@ +import * as re2 from "re2" + +type Re2 = typeof re2 & {code: string} +;(re2 as Re2).code = 'require("ajv/dist/runtime/re2").default' + +export default re2 as Re2 diff --git a/node_modules/ajv/lib/runtime/timestamp.ts b/node_modules/ajv/lib/runtime/timestamp.ts new file mode 100644 index 0000000000000000000000000000000000000000..1625f9a40f4443fde14743a6a8ecb6c1dc8fb819 --- /dev/null +++ b/node_modules/ajv/lib/runtime/timestamp.ts @@ -0,0 +1,46 @@ +const DT_SEPARATOR = /t|\s/i +const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/ +const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i +const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + +export default function validTimestamp(str: string, allowDate: boolean): boolean { + // http://tools.ietf.org/html/rfc3339#section-5.6 + const dt: string[] = str.split(DT_SEPARATOR) + return ( + (dt.length === 2 && validDate(dt[0]) && validTime(dt[1])) || + (allowDate && dt.length === 1 && validDate(dt[0])) + ) +} + +function validDate(str: string): boolean { + const matches: string[] | null = DATE.exec(str) + if (!matches) return false + const y: number = +matches[1] + const m: number = +matches[2] + const d: number = +matches[3] + return ( + m >= 1 && + m <= 12 && + d >= 1 && + (d <= DAYS[m] || + // leap year: https://tools.ietf.org/html/rfc3339#appendix-C + (m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0))) + ) +} + +function validTime(str: string): boolean { + const matches: string[] | null = TIME.exec(str) + if (!matches) return false + const hr: number = +matches[1] + const min: number = +matches[2] + const sec: number = +matches[3] + const tzH: number = +(matches[4] || 0) + const tzM: number = +(matches[5] || 0) + return ( + (hr <= 23 && min <= 59 && sec <= 59) || + // leap second + (hr - tzH === 23 && min - tzM === 59 && sec === 60) + ) +} + +validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default' diff --git a/node_modules/ajv/lib/runtime/ucs2length.ts b/node_modules/ajv/lib/runtime/ucs2length.ts new file mode 100644 index 0000000000000000000000000000000000000000..47d8292b83fde4619bdbf28b89e6720824a97164 --- /dev/null +++ b/node_modules/ajv/lib/runtime/ucs2length.ts @@ -0,0 +1,20 @@ +// https://mathiasbynens.be/notes/javascript-encoding +// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode +export default function ucs2length(str: string): number { + const len = str.length + let length = 0 + let pos = 0 + let value: number + while (pos < len) { + length++ + value = str.charCodeAt(pos++) + if (value >= 0xd800 && value <= 0xdbff && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos) + if ((value & 0xfc00) === 0xdc00) pos++ // low surrogate + } + } + return length +} + +ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default' diff --git a/node_modules/ajv/lib/runtime/uri.ts b/node_modules/ajv/lib/runtime/uri.ts new file mode 100644 index 0000000000000000000000000000000000000000..5450549cd5a3968f163460d3c0fb1aeb7ffc2b2c --- /dev/null +++ b/node_modules/ajv/lib/runtime/uri.ts @@ -0,0 +1,6 @@ +import * as uri from "fast-uri" + +type URI = typeof uri & {code: string} +;(uri as URI).code = 'require("ajv/dist/runtime/uri").default' + +export default uri as URI diff --git a/node_modules/ajv/lib/runtime/validation_error.ts b/node_modules/ajv/lib/runtime/validation_error.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d19a46a2245c667f479d7ee51d1d9558cd9ae90 --- /dev/null +++ b/node_modules/ajv/lib/runtime/validation_error.ts @@ -0,0 +1,13 @@ +import type {ErrorObject} from "../types" + +export default class ValidationError extends Error { + readonly errors: Partial[] + readonly ajv: true + readonly validation: true + + constructor(errors: Partial[]) { + super("validation failed") + this.errors = errors + this.ajv = this.validation = true + } +} diff --git a/node_modules/ajv/lib/standalone/index.ts b/node_modules/ajv/lib/standalone/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..b6129ce9e5ebab51fe4f53ffa86dbacd12878ed9 --- /dev/null +++ b/node_modules/ajv/lib/standalone/index.ts @@ -0,0 +1,100 @@ +import type AjvCore from "../core" +import type {AnyValidateFunction, SourceCode} from "../types" +import type {SchemaEnv} from "../compile" +import {UsedScopeValues, UsedValueState, ValueScopeName, varKinds} from "../compile/codegen/scope" +import {_, nil, _Code, Code, getProperty, getEsmExportName} from "../compile/codegen/code" + +function standaloneCode( + ajv: AjvCore, + refsOrFunc?: {[K in string]?: string} | AnyValidateFunction +): string { + if (!ajv.opts.code.source) { + throw new Error("moduleCode: ajv instance must have code.source option") + } + const {_n} = ajv.scope.opts + return typeof refsOrFunc == "function" + ? funcExportCode(refsOrFunc.source) + : refsOrFunc !== undefined + ? multiExportsCode(refsOrFunc, getValidate) + : multiExportsCode(ajv.schemas, (sch) => + sch.meta ? undefined : ajv.compile(sch.schema) + ) + + function getValidate(id: string): AnyValidateFunction { + const v = ajv.getSchema(id) + if (!v) throw new Error(`moduleCode: no schema with id ${id}`) + return v + } + + function funcExportCode(source?: SourceCode): string { + const usedValues: UsedScopeValues = {} + const n = source?.validateName + const vCode = validateCode(usedValues, source) + if (ajv.opts.code.esm) { + // Always do named export as `validate` rather than the variable `n` which is `validateXX` for known export value + return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}` + } + return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}` + } + + function multiExportsCode( + schemas: {[K in string]?: T}, + getValidateFunc: (schOrId: T) => AnyValidateFunction | undefined + ): string { + const usedValues: UsedScopeValues = {} + let code = _`"use strict";` + for (const name in schemas) { + const v = getValidateFunc(schemas[name] as T) + if (v) { + const vCode = validateCode(usedValues, v.source) + const exportSyntax = ajv.opts.code.esm + ? _`export const ${getEsmExportName(name)}` + : _`exports${getProperty(name)}` + code = _`${code}${_n}${exportSyntax} = ${v.source?.validateName};${_n}${vCode}` + } + } + return `${code}` + } + + function validateCode(usedValues: UsedScopeValues, s?: SourceCode): Code { + if (!s) throw new Error('moduleCode: function does not have "source" property') + if (usedState(s.validateName) === UsedValueState.Completed) return nil + setUsedState(s.validateName, UsedValueState.Started) + + const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode) + const code = new _Code(`${scopeCode}${_n}${s.validateCode}`) + return s.evaluated ? _`${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code + + function refValidateCode(n: ValueScopeName): Code | undefined { + const vRef = n.value?.ref + if (n.prefix === "validate" && typeof vRef == "function") { + const v = vRef as AnyValidateFunction + return validateCode(usedValues, v.source) + } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { + const {validate, validateName} = vRef as SchemaEnv + if (!validateName) throw new Error("ajv internal error") + const def = ajv.opts.code.es5 ? varKinds.var : varKinds.const + const wrapper = _`${def} ${n} = {validate: ${validateName}};` + if (usedState(validateName) === UsedValueState.Started) return wrapper + const vCode = validateCode(usedValues, validate?.source) + return _`${wrapper}${_n}${vCode}` + } + return undefined + } + + function usedState(name: ValueScopeName): UsedValueState | undefined { + return usedValues[name.prefix]?.get(name) + } + + function setUsedState(name: ValueScopeName, state: UsedValueState): void { + const {prefix} = name + const names = (usedValues[prefix] = usedValues[prefix] || new Map()) + names.set(name, state) + } + } +} + +module.exports = exports = standaloneCode +Object.defineProperty(exports, "__esModule", {value: true}) + +export default standaloneCode diff --git a/node_modules/ajv/lib/standalone/instance.ts b/node_modules/ajv/lib/standalone/instance.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4b2c30b58f0ebc89b4c8e1010e5976216c0042f --- /dev/null +++ b/node_modules/ajv/lib/standalone/instance.ts @@ -0,0 +1,36 @@ +import Ajv, {AnySchema, AnyValidateFunction, ErrorObject} from "../core" +import standaloneCode from "." +import * as requireFromString from "require-from-string" + +export default class AjvPack { + errors?: ErrorObject[] | null // errors from the last validation + constructor(readonly ajv: Ajv) {} + + validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise { + return Ajv.prototype.validate.call(this, schemaKeyRef, data) + } + + compile(schema: AnySchema, meta?: boolean): AnyValidateFunction { + return this.getStandalone(this.ajv.compile(schema, meta)) + } + + getSchema(keyRef: string): AnyValidateFunction | undefined { + const v = this.ajv.getSchema(keyRef) + if (!v) return undefined + return this.getStandalone(v) + } + + private getStandalone(v: AnyValidateFunction): AnyValidateFunction { + return requireFromString(standaloneCode(this.ajv, v)) as AnyValidateFunction + } + + addSchema(...args: Parameters): AjvPack { + this.ajv.addSchema.call(this.ajv, ...args) + return this + } + + addKeyword(...args: Parameters): AjvPack { + this.ajv.addKeyword.call(this.ajv, ...args) + return this + } +} diff --git a/node_modules/ajv/lib/types/index.ts b/node_modules/ajv/lib/types/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..39bc51b0b99d79b09e3e5f0e2d0d48e7bf37c069 --- /dev/null +++ b/node_modules/ajv/lib/types/index.ts @@ -0,0 +1,244 @@ +import {URIComponent} from "fast-uri" +import type {CodeGen, Code, Name, ScopeValueSets, ValueScopeName} from "../compile/codegen" +import type {SchemaEnv, SchemaCxt, SchemaObjCxt} from "../compile" +import type {JSONType} from "../compile/rules" +import type {KeywordCxt} from "../compile/validate" +import type Ajv from "../core" + +interface _SchemaObject { + id?: string + $id?: string + $schema?: string + [x: string]: any // TODO +} + +export interface SchemaObject extends _SchemaObject { + id?: string + $id?: string + $schema?: string + $async?: false + [x: string]: any // TODO +} + +export interface AsyncSchema extends _SchemaObject { + $async: true +} + +export type AnySchemaObject = SchemaObject | AsyncSchema + +export type Schema = SchemaObject | boolean + +export type AnySchema = Schema | AsyncSchema + +export type SchemaMap = {[Key in string]?: AnySchema} + +export interface SourceCode { + validateName: ValueScopeName + validateCode: string + scopeValues: ScopeValueSets + evaluated?: Code +} + +export interface DataValidationCxt { + instancePath: string + parentData: {[K in T]: any} // object or array + parentDataProperty: T // string or number + rootData: Record | any[] + dynamicAnchors: {[Ref in string]?: ValidateFunction} +} + +export interface ValidateFunction { + // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents + (this: Ajv | any, data: any, dataCxt?: DataValidationCxt): data is T + errors?: null | ErrorObject[] + evaluated?: Evaluated + schema: AnySchema + schemaEnv: SchemaEnv + source?: SourceCode +} + +export interface JTDParser { + (json: string): T | undefined + message?: string + position?: number +} + +export type EvaluatedProperties = {[K in string]?: true} | true + +export type EvaluatedItems = number | true + +export interface Evaluated { + // determined at compile time if staticProps/Items is true + props?: EvaluatedProperties + items?: EvaluatedItems + // whether props/items determined at compile time + dynamicProps: boolean + dynamicItems: boolean +} + +export interface AsyncValidateFunction extends ValidateFunction { + (...args: Parameters>): Promise + $async: true +} + +export type AnyValidateFunction = ValidateFunction | AsyncValidateFunction + +export interface ErrorObject, S = unknown> { + keyword: K + instancePath: string + schemaPath: string + params: P + // Added to validation errors of "propertyNames" keyword schema + propertyName?: string + // Excluded if option `messages` set to false. + message?: string + // These are added with the `verbose` option. + schema?: S + parentSchema?: AnySchemaObject + data?: unknown +} + +export type ErrorNoParams = ErrorObject, S> + +interface _KeywordDef { + keyword: string | string[] + type?: JSONType | JSONType[] // data types that keyword applies to + schemaType?: JSONType | JSONType[] // allowed type(s) of keyword value in the schema + allowUndefined?: boolean // used for keywords that can be invoked by other keywords, not being present in the schema + $data?: boolean // keyword supports [$data reference](../../docs/guide/combining-schemas.md#data-reference) + implements?: string[] // other schema keywords that this keyword implements + before?: string // keyword should be executed before this keyword (should be applicable to the same type) + post?: boolean // keyword should be executed after other keywords without post flag + metaSchema?: AnySchemaObject // meta-schema for keyword schema value - it is better to use schemaType where applicable + validateSchema?: AnyValidateFunction // compiled keyword metaSchema - should not be passed + dependencies?: string[] // keywords that must be present in the same schema + error?: KeywordErrorDefinition + $dataError?: KeywordErrorDefinition +} + +export interface CodeKeywordDefinition extends _KeywordDef { + code: (cxt: KeywordCxt, ruleType?: string) => void + trackErrors?: boolean +} + +export type MacroKeywordFunc = ( + schema: any, + parentSchema: AnySchemaObject, + it: SchemaCxt +) => AnySchema + +export type CompileKeywordFunc = ( + schema: any, + parentSchema: AnySchemaObject, + it: SchemaObjCxt +) => DataValidateFunction + +export interface DataValidateFunction { + (...args: Parameters): boolean | Promise + errors?: Partial[] +} + +export interface SchemaValidateFunction { + ( + schema: any, + data: any, + parentSchema?: AnySchemaObject, + dataCxt?: DataValidationCxt + ): boolean | Promise + errors?: Partial[] +} + +export interface FuncKeywordDefinition extends _KeywordDef { + validate?: SchemaValidateFunction | DataValidateFunction + compile?: CompileKeywordFunc + // schema: false makes validate not to expect schema (DataValidateFunction) + schema?: boolean // requires "validate" + modifying?: boolean + async?: boolean + valid?: boolean + errors?: boolean | "full" +} + +export interface MacroKeywordDefinition extends FuncKeywordDefinition { + macro: MacroKeywordFunc +} + +export type KeywordDefinition = + | CodeKeywordDefinition + | FuncKeywordDefinition + | MacroKeywordDefinition + +export type AddedKeywordDefinition = KeywordDefinition & { + type: JSONType[] + schemaType: JSONType[] +} + +export interface KeywordErrorDefinition { + message: string | Code | ((cxt: KeywordErrorCxt) => string | Code) + params?: Code | ((cxt: KeywordErrorCxt) => Code) +} + +export type Vocabulary = (KeywordDefinition | string)[] + +export interface KeywordErrorCxt { + gen: CodeGen + keyword: string + data: Name + $data?: string | false + schema: any // TODO + parentSchema?: AnySchemaObject + schemaCode: Code | number | boolean + schemaValue: Code | number | boolean + schemaType?: JSONType[] + errsCount?: Name + params: KeywordCxtParams + it: SchemaCxt +} + +export type KeywordCxtParams = {[P in string]?: Code | string | number} + +export type FormatValidator = (data: T) => boolean + +export type FormatCompare = (data1: T, data2: T) => number | undefined + +export type AsyncFormatValidator = (data: T) => Promise + +export interface FormatDefinition { + type?: T extends string ? "string" | undefined : "number" + validate: FormatValidator | (T extends string ? string | RegExp : never) + async?: false | undefined + compare?: FormatCompare +} + +export interface AsyncFormatDefinition { + type?: T extends string ? "string" | undefined : "number" + validate: AsyncFormatValidator + async: true + compare?: FormatCompare +} + +export type AddedFormat = + | true + | RegExp + | FormatValidator + | FormatDefinition + | FormatDefinition + | AsyncFormatDefinition + | AsyncFormatDefinition + +export type Format = AddedFormat | string + +export interface RegExpEngine { + (pattern: string, u: string): RegExpLike + code: string +} + +export interface RegExpLike { + test: (s: string) => boolean +} + +export interface UriResolver { + parse(uri: string): URIComponent + resolve(base: string, path: string): string + serialize(component: URIComponent): string +} diff --git a/node_modules/ajv/lib/types/json-schema.ts b/node_modules/ajv/lib/types/json-schema.ts new file mode 100644 index 0000000000000000000000000000000000000000..065c972e54a179b74e9dee48fdea8a1c2d45c8a1 --- /dev/null +++ b/node_modules/ajv/lib/types/json-schema.ts @@ -0,0 +1,187 @@ +/* eslint-disable @typescript-eslint/no-empty-interface */ +type StrictNullChecksWrapper = undefined extends null + ? `strictNullChecks must be true in tsconfig to use ${Name}` + : Type + +type UnionToIntersection = (U extends any ? (_: U) => void : never) extends (_: infer I) => void + ? I + : never + +export type SomeJSONSchema = UncheckedJSONSchemaType + +type UncheckedPartialSchema = Partial> + +export type PartialSchema = StrictNullChecksWrapper<"PartialSchema", UncheckedPartialSchema> + +type JSONType = IsPartial extends true + ? T | undefined + : T + +interface NumberKeywords { + minimum?: number + maximum?: number + exclusiveMinimum?: number + exclusiveMaximum?: number + multipleOf?: number + format?: string +} + +interface StringKeywords { + minLength?: number + maxLength?: number + pattern?: string + format?: string +} + +type UncheckedJSONSchemaType = ( + | // these two unions allow arbitrary unions of types + { + anyOf: readonly UncheckedJSONSchemaType[] + } + | { + oneOf: readonly UncheckedJSONSchemaType[] + } + // this union allows for { type: (primitive)[] } style schemas + | ({ + type: readonly (T extends number + ? JSONType<"number" | "integer", IsPartial> + : T extends string + ? JSONType<"string", IsPartial> + : T extends boolean + ? JSONType<"boolean", IsPartial> + : never)[] + } & UnionToIntersection< + T extends number + ? NumberKeywords + : T extends string + ? StringKeywords + : T extends boolean + ? // eslint-disable-next-line @typescript-eslint/ban-types + {} + : never + >) + // this covers "normal" types; it's last so typescript looks to it first for errors + | ((T extends number + ? { + type: JSONType<"number" | "integer", IsPartial> + } & NumberKeywords + : T extends string + ? { + type: JSONType<"string", IsPartial> + } & StringKeywords + : T extends boolean + ? { + type: JSONType<"boolean", IsPartial> + } + : T extends readonly [any, ...any[]] + ? { + // JSON AnySchema for tuple + type: JSONType<"array", IsPartial> + items: { + readonly [K in keyof T]-?: UncheckedJSONSchemaType & Nullable + } & {length: T["length"]} + minItems: T["length"] + } & ({maxItems: T["length"]} | {additionalItems: false}) + : T extends readonly any[] + ? { + type: JSONType<"array", IsPartial> + items: UncheckedJSONSchemaType + contains?: UncheckedPartialSchema + minItems?: number + maxItems?: number + minContains?: number + maxContains?: number + uniqueItems?: true + additionalItems?: never + } + : T extends Record + ? { + // JSON AnySchema for records and dictionaries + // "required" is not optional because it is often forgotten + // "properties" are optional for more concise dictionary schemas + // "patternProperties" and can be only used with interfaces that have string index + type: JSONType<"object", IsPartial> + additionalProperties?: boolean | UncheckedJSONSchemaType + unevaluatedProperties?: boolean | UncheckedJSONSchemaType + properties?: IsPartial extends true + ? Partial> + : UncheckedPropertiesSchema + patternProperties?: Record> + propertyNames?: Omit, "type"> & {type?: "string"} + dependencies?: {[K in keyof T]?: readonly (keyof T)[] | UncheckedPartialSchema} + dependentRequired?: {[K in keyof T]?: readonly (keyof T)[]} + dependentSchemas?: {[K in keyof T]?: UncheckedPartialSchema} + minProperties?: number + maxProperties?: number + } & (IsPartial extends true // "required" is not necessary if it's a non-partial type with no required keys // are listed it only asserts that optional cannot be listed. // "required" type does not guarantee that all required properties + ? {required: readonly (keyof T)[]} + : [UncheckedRequiredMembers] extends [never] + ? {required?: readonly UncheckedRequiredMembers[]} + : {required: readonly UncheckedRequiredMembers[]}) + : T extends null + ? { + type: JSONType<"null", IsPartial> + nullable: true + } + : never) & { + allOf?: readonly UncheckedPartialSchema[] + anyOf?: readonly UncheckedPartialSchema[] + oneOf?: readonly UncheckedPartialSchema[] + if?: UncheckedPartialSchema + then?: UncheckedPartialSchema + else?: UncheckedPartialSchema + not?: UncheckedPartialSchema + }) +) & { + [keyword: string]: any + $id?: string + $ref?: string + $defs?: Record> + definitions?: Record> +} + +export type JSONSchemaType = StrictNullChecksWrapper< + "JSONSchemaType", + UncheckedJSONSchemaType +> + +type Known = + | {[key: string]: Known} + | [Known, ...Known[]] + | Known[] + | number + | string + | boolean + | null + +type UncheckedPropertiesSchema = { + [K in keyof T]-?: (UncheckedJSONSchemaType & Nullable) | {$ref: string} +} + +export type PropertiesSchema = StrictNullChecksWrapper< + "PropertiesSchema", + UncheckedPropertiesSchema +> + +type UncheckedRequiredMembers = { + [K in keyof T]-?: undefined extends T[K] ? never : K +}[keyof T] + +export type RequiredMembers = StrictNullChecksWrapper< + "RequiredMembers", + UncheckedRequiredMembers +> + +type Nullable = undefined extends T + ? { + nullable: true + const?: null // any non-null value would fail `const: null`, `null` would fail any other value in const + enum?: readonly (T | null)[] // `null` must be explicitly included in "enum" for `null` to pass + default?: T | null + } + : { + nullable?: false + const?: T + enum?: readonly T[] + default?: T + } diff --git a/node_modules/ajv/lib/types/jtd-schema.ts b/node_modules/ajv/lib/types/jtd-schema.ts new file mode 100644 index 0000000000000000000000000000000000000000..61b2bde81d5f5d407971855d0a2c8125aeb53463 --- /dev/null +++ b/node_modules/ajv/lib/types/jtd-schema.ts @@ -0,0 +1,273 @@ +/** numeric strings */ +type NumberType = "float32" | "float64" | "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32" + +/** string strings */ +type StringType = "string" | "timestamp" + +/** Generic JTD Schema without inference of the represented type */ +export type SomeJTDSchemaType = ( + | // ref + {ref: string} + // primitives + | {type: NumberType | StringType | "boolean"} + // enum + | {enum: string[]} + // elements + | {elements: SomeJTDSchemaType} + // values + | {values: SomeJTDSchemaType} + // properties + | { + properties: Record + optionalProperties?: Record + additionalProperties?: boolean + } + | { + properties?: Record + optionalProperties: Record + additionalProperties?: boolean + } + // discriminator + | {discriminator: string; mapping: Record} + // empty + // NOTE see the end of + // https://github.com/typescript-eslint/typescript-eslint/issues/2063#issuecomment-675156492 + // eslint-disable-next-line @typescript-eslint/ban-types + | {} +) & { + nullable?: boolean + metadata?: Record + definitions?: Record +} + +/** required keys of an object, not undefined */ +type RequiredKeys = { + [K in keyof T]-?: undefined extends T[K] ? never : K +}[keyof T] + +/** optional or undifined-able keys of an object */ +type OptionalKeys = { + [K in keyof T]-?: undefined extends T[K] ? K : never +}[keyof T] + +/** type is true if T is a union type */ +type IsUnion_ = false extends ( + T extends unknown ? ([U] extends [T] ? false : true) : never +) + ? false + : true +type IsUnion = IsUnion_ + +/** type is true if T is identically E */ +type TypeEquality = [T] extends [E] ? ([E] extends [T] ? true : false) : false + +/** type is true if T or null is identically E or null*/ +type NullTypeEquality = TypeEquality + +/** gets only the string literals of a type or null if a type isn't a string literal */ +type EnumString = [T] extends [never] + ? null + : T extends string + ? string extends T + ? null + : T + : null + +/** true if type is a union of string literals */ +type IsEnum = null extends EnumString ? false : true + +/** true only if all types are array types (not tuples) */ +// NOTE relies on the fact that tuples don't have an index at 0.5, but arrays +// have an index at every number +type IsElements = false extends IsUnion + ? [T] extends [readonly unknown[]] + ? undefined extends T[0.5] + ? false + : true + : false + : false + +/** true if the the type is a values type */ +type IsValues = false extends IsUnion ? TypeEquality : false + +/** true if type is a properties type and Union is false, or type is a discriminator type and Union is true */ +type IsRecord = Union extends IsUnion + ? null extends EnumString + ? false + : true + : false + +/** true if type represents an empty record */ +type IsEmptyRecord = [T] extends [Record] + ? [T] extends [never] + ? false + : true + : false + +/** actual schema */ +export type JTDSchemaType = Record> = ( + | // refs - where null wasn't specified, must match exactly + (null extends EnumString + ? never + : + | ({[K in keyof D]: [T] extends [D[K]] ? {ref: K} : never}[keyof D] & {nullable?: false}) + // nulled refs - if ref is nullable and nullable is specified, then it can + // match either null or non-null definitions + | (null extends T + ? { + [K in keyof D]: [Exclude] extends [Exclude] + ? {ref: K} + : never + }[keyof D] & {nullable: true} + : never)) + // empty - empty schemas also treat nullable differently in that it's now fully ignored + | (unknown extends T ? {nullable?: boolean} : never) + // all other types // numbers - only accepts the type number + | ((true extends NullTypeEquality + ? {type: NumberType} + : // booleans - accepts the type boolean + true extends NullTypeEquality + ? {type: "boolean"} + : // strings - only accepts the type string + true extends NullTypeEquality + ? {type: StringType} + : // strings - only accepts the type Date + true extends NullTypeEquality + ? {type: "timestamp"} + : // enums - only accepts union of string literals + // TODO we can't actually check that everything in the union was specified + true extends IsEnum> + ? {enum: EnumString>[]} + : // arrays - only accepts arrays, could be array of unions to be resolved later + true extends IsElements> + ? T extends readonly (infer E)[] + ? { + elements: JTDSchemaType + } + : never + : // empty properties + true extends IsEmptyRecord> + ? + | {properties: Record; optionalProperties?: Record} + | {optionalProperties: Record} + : // values + true extends IsValues> + ? T extends Record + ? { + values: JTDSchemaType + } + : never + : // properties + true extends IsRecord, false> + ? ([RequiredKeys>] extends [never] + ? { + properties?: Record + } + : { + properties: {[K in RequiredKeys]: JTDSchemaType} + }) & + ([OptionalKeys>] extends [never] + ? { + optionalProperties?: Record + } + : { + optionalProperties: { + [K in OptionalKeys]: JTDSchemaType, D> + } + }) & { + additionalProperties?: boolean + } + : // discriminator + true extends IsRecord, true> + ? { + [K in keyof Exclude]-?: Exclude[K] extends string + ? { + discriminator: K + mapping: { + // TODO currently allows descriminator to be present in schema + [M in Exclude[K]]: JTDSchemaType< + Omit ? T : never, K>, + D + > + } + } + : never + }[keyof Exclude] + : never) & + (null extends T + ? { + nullable: true + } + : {nullable?: false})) +) & { + // extra properties + metadata?: Record + // TODO these should only be allowed at the top level + definitions?: {[K in keyof D]: JTDSchemaType} +} + +type JTDDataDef> = + | // ref + (S extends {ref: string} + ? D extends {[K in S["ref"]]: infer V} + ? JTDDataDef + : never + : // type + S extends {type: NumberType} + ? number + : S extends {type: "boolean"} + ? boolean + : S extends {type: "string"} + ? string + : S extends {type: "timestamp"} + ? string | Date + : // enum + S extends {enum: readonly (infer E)[]} + ? string extends E + ? never + : [E] extends [string] + ? E + : never + : // elements + S extends {elements: infer E} + ? JTDDataDef[] + : // properties + S extends { + properties: Record + optionalProperties?: Record + additionalProperties?: boolean + } + ? {-readonly [K in keyof S["properties"]]-?: JTDDataDef} & { + -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef< + S["optionalProperties"][K], + D + > + } & ([S["additionalProperties"]] extends [true] ? Record : unknown) + : S extends { + properties?: Record + optionalProperties: Record + additionalProperties?: boolean + } + ? {-readonly [K in keyof S["properties"]]-?: JTDDataDef} & { + -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef< + S["optionalProperties"][K], + D + > + } & ([S["additionalProperties"]] extends [true] ? Record : unknown) + : // values + S extends {values: infer V} + ? Record> + : // discriminator + S extends {discriminator: infer M; mapping: Record} + ? [M] extends [string] + ? { + [K in keyof S["mapping"]]: JTDDataDef & {[KM in M]: K} + }[keyof S["mapping"]] + : never + : // empty + unknown) + | (S extends {nullable: true} ? null : never) + +export type JTDDataType = S extends {definitions: Record} + ? JTDDataDef + : JTDDataDef> diff --git a/node_modules/ajv/lib/vocabularies/applicator/additionalItems.ts b/node_modules/ajv/lib/vocabularies/applicator/additionalItems.ts new file mode 100644 index 0000000000000000000000000000000000000000..755e5b3daf551d68ffbe3bd45884ee650094a46d --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/additionalItems.ts @@ -0,0 +1,56 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, not, Name} from "../../compile/codegen" +import {alwaysValidSchema, checkStrictMode, Type} from "../../compile/util" + +export type AdditionalItemsError = ErrorObject<"additionalItems", {limit: number}, AnySchema> + +const error: KeywordErrorDefinition = { + message: ({params: {len}}) => str`must NOT have more than ${len} items`, + params: ({params: {len}}) => _`{limit: ${len}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "additionalItems" as const, + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error, + code(cxt: KeywordCxt) { + const {parentSchema, it} = cxt + const {items} = parentSchema + if (!Array.isArray(items)) { + checkStrictMode(it, '"additionalItems" is ignored when "items" is not an array of schemas') + return + } + validateAdditionalItems(cxt, items) + }, +} + +export function validateAdditionalItems(cxt: KeywordCxt, items: AnySchema[]): void { + const {gen, schema, data, keyword, it} = cxt + it.items = true + const len = gen.const("len", _`${data}.length`) + if (schema === false) { + cxt.setParams({len: items.length}) + cxt.pass(_`${len} <= ${items.length}`) + } else if (typeof schema == "object" && !alwaysValidSchema(it, schema)) { + const valid = gen.var("valid", _`${len} <= ${items.length}`) // TODO var + gen.if(not(valid), () => validateItems(valid)) + cxt.ok(valid) + } + + function validateItems(valid: Name): void { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({keyword, dataProp: i, dataPropType: Type.Num}, valid) + if (!it.allErrors) gen.if(not(valid), () => gen.break()) + }) + } +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/additionalProperties.ts b/node_modules/ajv/lib/vocabularies/applicator/additionalProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfb511ce5100f4902f0f9c17ce7d7886e95fcabc --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/additionalProperties.ts @@ -0,0 +1,118 @@ +import type { + CodeKeywordDefinition, + AddedKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import {allSchemaProperties, usePattern, isOwnProperty} from "../code" +import {_, nil, or, not, Code, Name} from "../../compile/codegen" +import N from "../../compile/names" +import type {SubschemaArgs} from "../../compile/validate/subschema" +import {alwaysValidSchema, schemaRefOrVal, Type} from "../../compile/util" + +export type AdditionalPropertiesError = ErrorObject< + "additionalProperties", + {additionalProperty: string}, + AnySchema +> + +const error: KeywordErrorDefinition = { + message: "must NOT have additional properties", + params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`, +} + +const def: CodeKeywordDefinition & AddedKeywordDefinition = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error, + code(cxt) { + const {gen, schema, parentSchema, data, errsCount, it} = cxt + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error") + const {allErrors, opts} = it + it.props = true + if (opts.removeAdditional !== "all" && alwaysValidSchema(it, schema)) return + const props = allSchemaProperties(parentSchema.properties) + const patProps = allSchemaProperties(parentSchema.patternProperties) + checkAdditionalProperties() + cxt.ok(_`${errsCount} === ${N.errors}`) + + function checkAdditionalProperties(): void { + gen.forIn("key", data, (key: Name) => { + if (!props.length && !patProps.length) additionalPropertyCode(key) + else gen.if(isAdditional(key), () => additionalPropertyCode(key)) + }) + } + + function isAdditional(key: Name): Code { + let definedProp: Code + if (props.length > 8) { + // TODO maybe an option instead of hard-coded 8? + const propsSchema = schemaRefOrVal(it, parentSchema.properties, "properties") + definedProp = isOwnProperty(gen, propsSchema as Code, key) + } else if (props.length) { + definedProp = or(...props.map((p) => _`${key} === ${p}`)) + } else { + definedProp = nil + } + if (patProps.length) { + definedProp = or(definedProp, ...patProps.map((p) => _`${usePattern(cxt, p)}.test(${key})`)) + } + return not(definedProp) + } + + function deleteAdditional(key: Name): void { + gen.code(_`delete ${data}[${key}]`) + } + + function additionalPropertyCode(key: Name): void { + if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) { + deleteAdditional(key) + return + } + + if (schema === false) { + cxt.setParams({additionalProperty: key}) + cxt.error() + if (!allErrors) gen.break() + return + } + + if (typeof schema == "object" && !alwaysValidSchema(it, schema)) { + const valid = gen.name("valid") + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false) + gen.if(not(valid), () => { + cxt.reset() + deleteAdditional(key) + }) + } else { + applyAdditionalSchema(key, valid) + if (!allErrors) gen.if(not(valid), () => gen.break()) + } + } + } + + function applyAdditionalSchema(key: Name, valid: Name, errors?: false): void { + const subschema: SubschemaArgs = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: Type.Str, + } + if (errors === false) { + Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false, + }) + } + cxt.subschema(subschema, valid) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/allOf.ts b/node_modules/ajv/lib/vocabularies/applicator/allOf.ts new file mode 100644 index 0000000000000000000000000000000000000000..cdfa86ff431396a7cf68b937cb9baa69d4e79f29 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/allOf.ts @@ -0,0 +1,22 @@ +import type {CodeKeywordDefinition, AnySchema} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {alwaysValidSchema} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: "allOf", + schemaType: "array", + code(cxt: KeywordCxt) { + const {gen, schema, it} = cxt + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + const valid = gen.name("valid") + schema.forEach((sch: AnySchema, i: number) => { + if (alwaysValidSchema(it, sch)) return + const schCxt = cxt.subschema({keyword: "allOf", schemaProp: i}, valid) + cxt.ok(valid) + cxt.mergeEvaluated(schCxt) + }) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/anyOf.ts b/node_modules/ajv/lib/vocabularies/applicator/anyOf.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd331b5ae98a72f1a6d79aacdf2d4babd16bde35 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/anyOf.ts @@ -0,0 +1,14 @@ +import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from "../../types" +import {validateUnion} from "../code" + +export type AnyOfError = ErrorNoParams<"anyOf", AnySchema[]> + +const def: CodeKeywordDefinition = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: validateUnion, + error: {message: "must match a schema in anyOf"}, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/contains.ts b/node_modules/ajv/lib/vocabularies/applicator/contains.ts new file mode 100644 index 0000000000000000000000000000000000000000..d88675c6c2a21db9fa9e0ce497646fda1bf5d5a6 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/contains.ts @@ -0,0 +1,109 @@ +import type { + CodeKeywordDefinition, + KeywordErrorDefinition, + ErrorObject, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, Name} from "../../compile/codegen" +import {alwaysValidSchema, checkStrictMode, Type} from "../../compile/util" + +export type ContainsError = ErrorObject< + "contains", + {minContains: number; maxContains?: number}, + AnySchema +> + +const error: KeywordErrorDefinition = { + message: ({params: {min, max}}) => + max === undefined + ? str`must contain at least ${min} valid item(s)` + : str`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({params: {min, max}}) => + max === undefined ? _`{minContains: ${min}}` : _`{minContains: ${min}, maxContains: ${max}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error, + code(cxt: KeywordCxt) { + const {gen, schema, parentSchema, data, it} = cxt + let min: number + let max: number | undefined + const {minContains, maxContains} = parentSchema + if (it.opts.next) { + min = minContains === undefined ? 1 : minContains + max = maxContains + } else { + min = 1 + } + const len = gen.const("len", _`${data}.length`) + cxt.setParams({min, max}) + if (max === undefined && min === 0) { + checkStrictMode(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`) + return + } + if (max !== undefined && min > max) { + checkStrictMode(it, `"minContains" > "maxContains" is always invalid`) + cxt.fail() + return + } + if (alwaysValidSchema(it, schema)) { + let cond = _`${len} >= ${min}` + if (max !== undefined) cond = _`${cond} && ${len} <= ${max}` + cxt.pass(cond) + return + } + + it.items = true + const valid = gen.name("valid") + if (max === undefined && min === 1) { + validateItems(valid, () => gen.if(valid, () => gen.break())) + } else if (min === 0) { + gen.let(valid, true) + if (max !== undefined) gen.if(_`${data}.length > 0`, validateItemsWithCount) + } else { + gen.let(valid, false) + validateItemsWithCount() + } + cxt.result(valid, () => cxt.reset()) + + function validateItemsWithCount(): void { + const schValid = gen.name("_valid") + const count = gen.let("count", 0) + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))) + } + + function validateItems(_valid: Name, block: () => void): void { + gen.forRange("i", 0, len, (i) => { + cxt.subschema( + { + keyword: "contains", + dataProp: i, + dataPropType: Type.Num, + compositeRule: true, + }, + _valid + ) + block() + }) + } + + function checkLimits(count: Name): void { + gen.code(_`${count}++`) + if (max === undefined) { + gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true).break()) + } else { + gen.if(_`${count} > ${max}`, () => gen.assign(valid, false).break()) + if (min === 1) gen.assign(valid, true) + else gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true)) + } + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/dependencies.ts b/node_modules/ajv/lib/vocabularies/applicator/dependencies.ts new file mode 100644 index 0000000000000000000000000000000000000000..f6761128698689ce1d4699c33a3b128516157eeb --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/dependencies.ts @@ -0,0 +1,112 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + SchemaMap, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str} from "../../compile/codegen" +import {alwaysValidSchema} from "../../compile/util" +import {checkReportMissingProp, checkMissingProp, reportMissingProp, propertyInData} from "../code" + +export type PropertyDependencies = {[K in string]?: string[]} + +export interface DependenciesErrorParams { + property: string + missingProperty: string + depsCount: number + deps: string // TODO change to string[] +} + +type SchemaDependencies = SchemaMap + +export type DependenciesError = ErrorObject< + "dependencies", + DependenciesErrorParams, + {[K in string]?: string[] | AnySchema} +> + +export const error: KeywordErrorDefinition = { + message: ({params: {property, depsCount, deps}}) => { + const property_ies = depsCount === 1 ? "property" : "properties" + return str`must have ${property_ies} ${deps} when property ${property} is present` + }, + params: ({params: {property, depsCount, deps, missingProperty}}) => + _`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}`, // TODO change to reference +} + +const def: CodeKeywordDefinition = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error, + code(cxt: KeywordCxt) { + const [propDeps, schDeps] = splitDependencies(cxt) + validatePropertyDeps(cxt, propDeps) + validateSchemaDeps(cxt, schDeps) + }, +} + +function splitDependencies({schema}: KeywordCxt): [PropertyDependencies, SchemaDependencies] { + const propertyDeps: PropertyDependencies = {} + const schemaDeps: SchemaDependencies = {} + for (const key in schema) { + if (key === "__proto__") continue + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps + deps[key] = schema[key] + } + return [propertyDeps, schemaDeps] +} + +export function validatePropertyDeps( + cxt: KeywordCxt, + propertyDeps: {[K in string]?: string[]} = cxt.schema +): void { + const {gen, data, it} = cxt + if (Object.keys(propertyDeps).length === 0) return + const missing = gen.let("missing") + for (const prop in propertyDeps) { + const deps = propertyDeps[prop] as string[] + if (deps.length === 0) continue + const hasProperty = propertyInData(gen, data, prop, it.opts.ownProperties) + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", "), + }) + if (it.allErrors) { + gen.if(hasProperty, () => { + for (const depProp of deps) { + checkReportMissingProp(cxt, depProp) + } + }) + } else { + gen.if(_`${hasProperty} && (${checkMissingProp(cxt, deps, missing)})`) + reportMissingProp(cxt, missing) + gen.else() + } + } +} + +export function validateSchemaDeps(cxt: KeywordCxt, schemaDeps: SchemaMap = cxt.schema): void { + const {gen, data, keyword, it} = cxt + const valid = gen.name("valid") + for (const prop in schemaDeps) { + if (alwaysValidSchema(it, schemaDeps[prop] as AnySchema)) continue + gen.if( + propertyInData(gen, data, prop, it.opts.ownProperties), + () => { + const schCxt = cxt.subschema({keyword, schemaProp: prop}, valid) + cxt.mergeValidEvaluated(schCxt, valid) + }, + () => gen.var(valid, true) // TODO var + ) + cxt.ok(valid) + } +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/dependentSchemas.ts b/node_modules/ajv/lib/vocabularies/applicator/dependentSchemas.ts new file mode 100644 index 0000000000000000000000000000000000000000..dbd3ae45c38f2e0a4c958a83694eaf5844440e7e --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/dependentSchemas.ts @@ -0,0 +1,11 @@ +import type {CodeKeywordDefinition} from "../../types" +import {validateSchemaDeps} from "./dependencies" + +const def: CodeKeywordDefinition = { + keyword: "dependentSchemas", + type: "object", + schemaType: "object", + code: (cxt) => validateSchemaDeps(cxt), +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/if.ts b/node_modules/ajv/lib/vocabularies/applicator/if.ts new file mode 100644 index 0000000000000000000000000000000000000000..5a40d5e3ad2ca0ee8bffb0bc10c361580a15378f --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/if.ts @@ -0,0 +1,80 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {SchemaObjCxt} from "../../compile" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, not, Name} from "../../compile/codegen" +import {alwaysValidSchema, checkStrictMode} from "../../compile/util" + +export type IfKeywordError = ErrorObject<"if", {failingKeyword: string}, AnySchema> + +const error: KeywordErrorDefinition = { + message: ({params}) => str`must match "${params.ifClause}" schema`, + params: ({params}) => _`{failingKeyword: ${params.ifClause}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error, + code(cxt: KeywordCxt) { + const {gen, parentSchema, it} = cxt + if (parentSchema.then === undefined && parentSchema.else === undefined) { + checkStrictMode(it, '"if" without "then" and "else" is ignored') + } + const hasThen = hasSchema(it, "then") + const hasElse = hasSchema(it, "else") + if (!hasThen && !hasElse) return + + const valid = gen.let("valid", true) + const schValid = gen.name("_valid") + validateIf() + cxt.reset() + + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause") + cxt.setParams({ifClause}) + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)) + } else if (hasThen) { + gen.if(schValid, validateClause("then")) + } else { + gen.if(not(schValid), validateClause("else")) + } + + cxt.pass(valid, () => cxt.error(true)) + + function validateIf(): void { + const schCxt = cxt.subschema( + { + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false, + }, + schValid + ) + cxt.mergeEvaluated(schCxt) + } + + function validateClause(keyword: string, ifClause?: Name): () => void { + return () => { + const schCxt = cxt.subschema({keyword}, schValid) + gen.assign(valid, schValid) + cxt.mergeValidEvaluated(schCxt, valid) + if (ifClause) gen.assign(ifClause, _`${keyword}`) + else cxt.setParams({ifClause: keyword}) + } + } + }, +} + +function hasSchema(it: SchemaObjCxt, keyword: string): boolean { + const schema = it.schema[keyword] + return schema !== undefined && !alwaysValidSchema(it, schema) +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/index.ts b/node_modules/ajv/lib/vocabularies/applicator/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..fc527169967c8e3ae32b13ee19c9ad20dc5794cc --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/index.ts @@ -0,0 +1,53 @@ +import type {ErrorNoParams, Vocabulary} from "../../types" +import additionalItems, {AdditionalItemsError} from "./additionalItems" +import prefixItems from "./prefixItems" +import items from "./items" +import items2020, {ItemsError} from "./items2020" +import contains, {ContainsError} from "./contains" +import dependencies, {DependenciesError} from "./dependencies" +import propertyNames, {PropertyNamesError} from "./propertyNames" +import additionalProperties, {AdditionalPropertiesError} from "./additionalProperties" +import properties from "./properties" +import patternProperties from "./patternProperties" +import notKeyword, {NotKeywordError} from "./not" +import anyOf, {AnyOfError} from "./anyOf" +import oneOf, {OneOfError} from "./oneOf" +import allOf from "./allOf" +import ifKeyword, {IfKeywordError} from "./if" +import thenElse from "./thenElse" + +export default function getApplicator(draft2020 = false): Vocabulary { + const applicator = [ + // any + notKeyword, + anyOf, + oneOf, + allOf, + ifKeyword, + thenElse, + // object + propertyNames, + additionalProperties, + dependencies, + properties, + patternProperties, + ] + // array + if (draft2020) applicator.push(prefixItems, items2020) + else applicator.push(additionalItems, items) + applicator.push(contains) + return applicator +} + +export type ApplicatorKeywordError = + | ErrorNoParams<"false schema"> + | AdditionalItemsError + | ItemsError + | ContainsError + | AdditionalPropertiesError + | DependenciesError + | IfKeywordError + | AnyOfError + | OneOfError + | NotKeywordError + | PropertyNamesError diff --git a/node_modules/ajv/lib/vocabularies/applicator/items.ts b/node_modules/ajv/lib/vocabularies/applicator/items.ts new file mode 100644 index 0000000000000000000000000000000000000000..033cb3977342222bc90a44251bc9366b151cff9f --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/items.ts @@ -0,0 +1,59 @@ +import type {CodeKeywordDefinition, AnySchema, AnySchemaObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_} from "../../compile/codegen" +import {alwaysValidSchema, mergeEvaluated, checkStrictMode} from "../../compile/util" +import {validateArray} from "../code" + +const def: CodeKeywordDefinition = { + keyword: "items", + type: "array", + schemaType: ["object", "array", "boolean"], + before: "uniqueItems", + code(cxt: KeywordCxt) { + const {schema, it} = cxt + if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema) + it.items = true + if (alwaysValidSchema(it, schema)) return + cxt.ok(validateArray(cxt)) + }, +} + +export function validateTuple( + cxt: KeywordCxt, + extraItems: string, + schArr: AnySchema[] = cxt.schema +): void { + const {gen, parentSchema, data, keyword, it} = cxt + checkStrictTuple(parentSchema) + if (it.opts.unevaluated && schArr.length && it.items !== true) { + it.items = mergeEvaluated.items(gen, schArr.length, it.items) + } + const valid = gen.name("valid") + const len = gen.const("len", _`${data}.length`) + schArr.forEach((sch: AnySchema, i: number) => { + if (alwaysValidSchema(it, sch)) return + gen.if(_`${len} > ${i}`, () => + cxt.subschema( + { + keyword, + schemaProp: i, + dataProp: i, + }, + valid + ) + ) + cxt.ok(valid) + }) + + function checkStrictTuple(sch: AnySchemaObject): void { + const {opts, errSchemaPath} = it + const l = schArr.length + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false) + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"` + checkStrictMode(it, msg, opts.strictTuples) + } + } +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/items2020.ts b/node_modules/ajv/lib/vocabularies/applicator/items2020.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a99b08d59adc2ce8fc6c785a5ccc34c0960c1f9 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/items2020.ts @@ -0,0 +1,36 @@ +import type { + CodeKeywordDefinition, + KeywordErrorDefinition, + ErrorObject, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str} from "../../compile/codegen" +import {alwaysValidSchema} from "../../compile/util" +import {validateArray} from "../code" +import {validateAdditionalItems} from "./additionalItems" + +export type ItemsError = ErrorObject<"items", {limit: number}, AnySchema> + +const error: KeywordErrorDefinition = { + message: ({params: {len}}) => str`must NOT have more than ${len} items`, + params: ({params: {len}}) => _`{limit: ${len}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error, + code(cxt: KeywordCxt) { + const {schema, parentSchema, it} = cxt + const {prefixItems} = parentSchema + it.items = true + if (alwaysValidSchema(it, schema)) return + if (prefixItems) validateAdditionalItems(cxt, prefixItems) + else cxt.ok(validateArray(cxt)) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/not.ts b/node_modules/ajv/lib/vocabularies/applicator/not.ts new file mode 100644 index 0000000000000000000000000000000000000000..8691db0bf229b778f88a373110311dff1c69c1dc --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/not.ts @@ -0,0 +1,38 @@ +import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {alwaysValidSchema} from "../../compile/util" + +export type NotKeywordError = ErrorNoParams<"not", AnySchema> + +const def: CodeKeywordDefinition = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt: KeywordCxt) { + const {gen, schema, it} = cxt + if (alwaysValidSchema(it, schema)) { + cxt.fail() + return + } + + const valid = gen.name("valid") + cxt.subschema( + { + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false, + }, + valid + ) + + cxt.failResult( + valid, + () => cxt.reset(), + () => cxt.error() + ) + }, + error: {message: "must NOT be valid"}, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/oneOf.ts b/node_modules/ajv/lib/vocabularies/applicator/oneOf.ts new file mode 100644 index 0000000000000000000000000000000000000000..c25353ffd648c45dce2433c14cb27841763d5435 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/oneOf.ts @@ -0,0 +1,82 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, Name} from "../../compile/codegen" +import {alwaysValidSchema} from "../../compile/util" +import {SchemaCxt} from "../../compile" + +export type OneOfError = ErrorObject< + "oneOf", + {passingSchemas: [number, number] | null}, + AnySchema[] +> + +const error: KeywordErrorDefinition = { + message: "must match exactly one schema in oneOf", + params: ({params}) => _`{passingSchemas: ${params.passing}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error, + code(cxt: KeywordCxt) { + const {gen, schema, parentSchema, it} = cxt + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + if (it.opts.discriminator && parentSchema.discriminator) return + const schArr: AnySchema[] = schema + const valid = gen.let("valid", false) + const passing = gen.let("passing", null) + const schValid = gen.name("_valid") + cxt.setParams({passing}) + // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas + + gen.block(validateOneOf) + + cxt.result( + valid, + () => cxt.reset(), + () => cxt.error(true) + ) + + function validateOneOf(): void { + schArr.forEach((sch: AnySchema, i: number) => { + let schCxt: SchemaCxt | undefined + if (alwaysValidSchema(it, sch)) { + gen.var(schValid, true) + } else { + schCxt = cxt.subschema( + { + keyword: "oneOf", + schemaProp: i, + compositeRule: true, + }, + schValid + ) + } + + if (i > 0) { + gen + .if(_`${schValid} && ${valid}`) + .assign(valid, false) + .assign(passing, _`[${passing}, ${i}]`) + .else() + } + + gen.if(schValid, () => { + gen.assign(valid, true) + gen.assign(passing, i) + if (schCxt) cxt.mergeEvaluated(schCxt, Name) + }) + }) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/patternProperties.ts b/node_modules/ajv/lib/vocabularies/applicator/patternProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea624e230dddb3d71320eb5255a2b89bae5f20b0 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/patternProperties.ts @@ -0,0 +1,91 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {allSchemaProperties, usePattern} from "../code" +import {_, not, Name} from "../../compile/codegen" +import {alwaysValidSchema, checkStrictMode} from "../../compile/util" +import {evaluatedPropsToName, Type} from "../../compile/util" +import {AnySchema} from "../../types" + +const def: CodeKeywordDefinition = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt: KeywordCxt) { + const {gen, schema, data, parentSchema, it} = cxt + const {opts} = it + const patterns = allSchemaProperties(schema) + const alwaysValidPatterns = patterns.filter((p) => + alwaysValidSchema(it, schema[p] as AnySchema) + ) + + if ( + patterns.length === 0 || + (alwaysValidPatterns.length === patterns.length && + (!it.opts.unevaluated || it.props === true)) + ) { + return + } + + const checkProperties = + opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties + const valid = gen.name("valid") + if (it.props !== true && !(it.props instanceof Name)) { + it.props = evaluatedPropsToName(gen, it.props) + } + const {props} = it + validatePatternProperties() + + function validatePatternProperties(): void { + for (const pat of patterns) { + if (checkProperties) checkMatchingProperties(pat) + if (it.allErrors) { + validateProperties(pat) + } else { + gen.var(valid, true) // TODO var + validateProperties(pat) + gen.if(valid) + } + } + } + + function checkMatchingProperties(pat: string): void { + for (const prop in checkProperties) { + if (new RegExp(pat).test(prop)) { + checkStrictMode( + it, + `property ${prop} matches pattern ${pat} (use allowMatchingProperties)` + ) + } + } + } + + function validateProperties(pat: string): void { + gen.forIn("key", data, (key) => { + gen.if(_`${usePattern(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat) + if (!alwaysValid) { + cxt.subschema( + { + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: Type.Str, + }, + valid + ) + } + + if (it.opts.unevaluated && props !== true) { + gen.assign(_`${props}[${key}]`, true) + } else if (!alwaysValid && !it.allErrors) { + // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false) + // or if all properties were evaluated (props === true) + gen.if(not(valid), () => gen.break()) + } + }) + }) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/prefixItems.ts b/node_modules/ajv/lib/vocabularies/applicator/prefixItems.ts new file mode 100644 index 0000000000000000000000000000000000000000..008fb2db1d8dd898fa79226d118530af2628c2c8 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/prefixItems.ts @@ -0,0 +1,12 @@ +import type {CodeKeywordDefinition} from "../../types" +import {validateTuple} from "./items" + +const def: CodeKeywordDefinition = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => validateTuple(cxt, "items"), +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/properties.ts b/node_modules/ajv/lib/vocabularies/applicator/properties.ts new file mode 100644 index 0000000000000000000000000000000000000000..a55b19ce5b77d180ce94cb063946a08d22824bd1 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/properties.ts @@ -0,0 +1,57 @@ +import type {CodeKeywordDefinition} from "../../types" +import {KeywordCxt} from "../../compile/validate" +import {propertyInData, allSchemaProperties} from "../code" +import {alwaysValidSchema, toHash, mergeEvaluated} from "../../compile/util" +import apDef from "./additionalProperties" + +const def: CodeKeywordDefinition = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt: KeywordCxt) { + const {gen, schema, parentSchema, data, it} = cxt + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) { + apDef.code(new KeywordCxt(it, apDef, "additionalProperties")) + } + const allProps = allSchemaProperties(schema) + for (const prop of allProps) { + it.definedProperties.add(prop) + } + if (it.opts.unevaluated && allProps.length && it.props !== true) { + it.props = mergeEvaluated.props(gen, toHash(allProps), it.props) + } + const properties = allProps.filter((p) => !alwaysValidSchema(it, schema[p])) + if (properties.length === 0) return + const valid = gen.name("valid") + + for (const prop of properties) { + if (hasDefault(prop)) { + applyPropertySchema(prop) + } else { + gen.if(propertyInData(gen, data, prop, it.opts.ownProperties)) + applyPropertySchema(prop) + if (!it.allErrors) gen.else().var(valid, true) + gen.endIf() + } + cxt.it.definedProperties.add(prop) + cxt.ok(valid) + } + + function hasDefault(prop: string): boolean | undefined { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined + } + + function applyPropertySchema(prop: string): void { + cxt.subschema( + { + keyword: "properties", + schemaProp: prop, + dataProp: prop, + }, + valid + ) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/propertyNames.ts b/node_modules/ajv/lib/vocabularies/applicator/propertyNames.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c54d605258600f3e98d4eeb17e87256be6b9f3f --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/propertyNames.ts @@ -0,0 +1,50 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, not} from "../../compile/codegen" +import {alwaysValidSchema} from "../../compile/util" + +export type PropertyNamesError = ErrorObject<"propertyNames", {propertyName: string}, AnySchema> + +const error: KeywordErrorDefinition = { + message: "property name must be valid", + params: ({params}) => _`{propertyName: ${params.propertyName}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error, + code(cxt: KeywordCxt) { + const {gen, schema, data, it} = cxt + if (alwaysValidSchema(it, schema)) return + const valid = gen.name("valid") + + gen.forIn("key", data, (key) => { + cxt.setParams({propertyName: key}) + cxt.subschema( + { + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true, + }, + valid + ) + gen.if(not(valid), () => { + cxt.error(true) + if (!it.allErrors) gen.break() + }) + }) + + cxt.ok(valid) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/applicator/thenElse.ts b/node_modules/ajv/lib/vocabularies/applicator/thenElse.ts new file mode 100644 index 0000000000000000000000000000000000000000..5055182e89141a257630516d96a52ec2917f72b6 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/applicator/thenElse.ts @@ -0,0 +1,13 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {checkStrictMode} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({keyword, parentSchema, it}: KeywordCxt) { + if (parentSchema.if === undefined) checkStrictMode(it, `"${keyword}" without "if" is ignored`) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/code.ts b/node_modules/ajv/lib/vocabularies/code.ts new file mode 100644 index 0000000000000000000000000000000000000000..92cdd5b04ef30e0ed6f3c9025752f0acf59370eb --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/code.ts @@ -0,0 +1,168 @@ +import type {AnySchema, SchemaMap} from "../types" +import type {SchemaCxt} from "../compile" +import type {KeywordCxt} from "../compile/validate" +import {CodeGen, _, and, or, not, nil, strConcat, getProperty, Code, Name} from "../compile/codegen" +import {alwaysValidSchema, Type} from "../compile/util" +import N from "../compile/names" +import {useFunc} from "../compile/util" +export function checkReportMissingProp(cxt: KeywordCxt, prop: string): void { + const {gen, data, it} = cxt + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({missingProperty: _`${prop}`}, true) + cxt.error() + }) +} + +export function checkMissingProp( + {gen, data, it: {opts}}: KeywordCxt, + properties: string[], + missing: Name +): Code { + return or( + ...properties.map((prop) => + and(noPropertyInData(gen, data, prop, opts.ownProperties), _`${missing} = ${prop}`) + ) + ) +} + +export function reportMissingProp(cxt: KeywordCxt, missing: Name): void { + cxt.setParams({missingProperty: missing}, true) + cxt.error() +} + +export function hasPropFunc(gen: CodeGen): Name { + return gen.scopeValue("func", { + // eslint-disable-next-line @typescript-eslint/unbound-method + ref: Object.prototype.hasOwnProperty, + code: _`Object.prototype.hasOwnProperty`, + }) +} + +export function isOwnProperty(gen: CodeGen, data: Name, property: Name | string): Code { + return _`${hasPropFunc(gen)}.call(${data}, ${property})` +} + +export function propertyInData( + gen: CodeGen, + data: Name, + property: Name | string, + ownProperties?: boolean +): Code { + const cond = _`${data}${getProperty(property)} !== undefined` + return ownProperties ? _`${cond} && ${isOwnProperty(gen, data, property)}` : cond +} + +export function noPropertyInData( + gen: CodeGen, + data: Name, + property: Name | string, + ownProperties?: boolean +): Code { + const cond = _`${data}${getProperty(property)} === undefined` + return ownProperties ? or(cond, not(isOwnProperty(gen, data, property))) : cond +} + +export function allSchemaProperties(schemaMap?: SchemaMap): string[] { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [] +} + +export function schemaProperties(it: SchemaCxt, schemaMap: SchemaMap): string[] { + return allSchemaProperties(schemaMap).filter( + (p) => !alwaysValidSchema(it, schemaMap[p] as AnySchema) + ) +} + +export function callValidateCode( + {schemaCode, data, it: {gen, topSchemaRef, schemaPath, errorPath}, it}: KeywordCxt, + func: Code, + context: Code, + passSchema?: boolean +): Code { + const dataAndSchema = passSchema ? _`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data + const valCxt: [Name, Code | number][] = [ + [N.instancePath, strConcat(N.instancePath, errorPath)], + [N.parentData, it.parentData], + [N.parentDataProperty, it.parentDataProperty], + [N.rootData, N.rootData], + ] + if (it.opts.dynamicRef) valCxt.push([N.dynamicAnchors, N.dynamicAnchors]) + const args = _`${dataAndSchema}, ${gen.object(...valCxt)}` + return context !== nil ? _`${func}.call(${context}, ${args})` : _`${func}(${args})` +} + +const newRegExp = _`new RegExp` + +export function usePattern({gen, it: {opts}}: KeywordCxt, pattern: string): Name { + const u = opts.unicodeRegExp ? "u" : "" + const {regExp} = opts.code + const rx = regExp(pattern, u) + + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: _`${regExp.code === "new RegExp" ? newRegExp : useFunc(gen, regExp)}(${pattern}, ${u})`, + }) +} + +export function validateArray(cxt: KeywordCxt): Name { + const {gen, data, keyword, it} = cxt + const valid = gen.name("valid") + if (it.allErrors) { + const validArr = gen.let("valid", true) + validateItems(() => gen.assign(validArr, false)) + return validArr + } + gen.var(valid, true) + validateItems(() => gen.break()) + return valid + + function validateItems(notValid: () => void): void { + const len = gen.const("len", _`${data}.length`) + gen.forRange("i", 0, len, (i) => { + cxt.subschema( + { + keyword, + dataProp: i, + dataPropType: Type.Num, + }, + valid + ) + gen.if(not(valid), notValid) + }) + } +} + +export function validateUnion(cxt: KeywordCxt): void { + const {gen, schema, keyword, it} = cxt + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + const alwaysValid = schema.some((sch: AnySchema) => alwaysValidSchema(it, sch)) + if (alwaysValid && !it.opts.unevaluated) return + + const valid = gen.let("valid", false) + const schValid = gen.name("_valid") + + gen.block(() => + schema.forEach((_sch: AnySchema, i: number) => { + const schCxt = cxt.subschema( + { + keyword, + schemaProp: i, + compositeRule: true, + }, + schValid + ) + gen.assign(valid, _`${valid} || ${schValid}`) + const merged = cxt.mergeValidEvaluated(schCxt, schValid) + // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true) + // or if all properties and items were evaluated (it.props === true && it.items === true) + if (!merged) gen.if(not(valid)) + }) + ) + + cxt.result( + valid, + () => cxt.reset(), + () => cxt.error(true) + ) +} diff --git a/node_modules/ajv/lib/vocabularies/core/id.ts b/node_modules/ajv/lib/vocabularies/core/id.ts new file mode 100644 index 0000000000000000000000000000000000000000..aa36c4bb20f45046bb46fc998ca39fa2d9589811 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/core/id.ts @@ -0,0 +1,10 @@ +import type {CodeKeywordDefinition} from "../../types" + +const def: CodeKeywordDefinition = { + keyword: "id", + code() { + throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID') + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/core/index.ts b/node_modules/ajv/lib/vocabularies/core/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e63e2895d08710745fe5785bbdb1aaf155e05407 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/core/index.ts @@ -0,0 +1,16 @@ +import type {Vocabulary} from "../../types" +import idKeyword from "./id" +import refKeyword from "./ref" + +const core: Vocabulary = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + {keyword: "$comment"}, + "definitions", + idKeyword, + refKeyword, +] + +export default core diff --git a/node_modules/ajv/lib/vocabularies/core/ref.ts b/node_modules/ajv/lib/vocabularies/core/ref.ts new file mode 100644 index 0000000000000000000000000000000000000000..5d59fbcb2a99564106fdcafe244f693bc88e3ea2 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/core/ref.ts @@ -0,0 +1,129 @@ +import type {CodeKeywordDefinition, AnySchema} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import MissingRefError from "../../compile/ref_error" +import {callValidateCode} from "../code" +import {_, nil, stringify, Code, Name} from "../../compile/codegen" +import N from "../../compile/names" +import {SchemaEnv, resolveRef} from "../../compile" +import {mergeEvaluated} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: "$ref", + schemaType: "string", + code(cxt: KeywordCxt): void { + const {gen, schema: $ref, it} = cxt + const {baseId, schemaEnv: env, validateName, opts, self} = it + const {root} = env + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef() + const schOrEnv = resolveRef.call(self, root, baseId, $ref) + if (schOrEnv === undefined) throw new MissingRefError(it.opts.uriResolver, baseId, $ref) + if (schOrEnv instanceof SchemaEnv) return callValidate(schOrEnv) + return inlineRefSchema(schOrEnv) + + function callRootRef(): void { + if (env === root) return callRef(cxt, validateName, env, env.$async) + const rootName = gen.scopeValue("root", {ref: root}) + return callRef(cxt, _`${rootName}.validate`, root, root.$async) + } + + function callValidate(sch: SchemaEnv): void { + const v = getValidate(cxt, sch) + callRef(cxt, v, sch, sch.$async) + } + + function inlineRefSchema(sch: AnySchema): void { + const schName = gen.scopeValue( + "schema", + opts.code.source === true ? {ref: sch, code: stringify(sch)} : {ref: sch} + ) + const valid = gen.name("valid") + const schCxt = cxt.subschema( + { + schema: sch, + dataTypes: [], + schemaPath: nil, + topSchemaRef: schName, + errSchemaPath: $ref, + }, + valid + ) + cxt.mergeEvaluated(schCxt) + cxt.ok(valid) + } + }, +} + +export function getValidate(cxt: KeywordCxt, sch: SchemaEnv): Code { + const {gen} = cxt + return sch.validate + ? gen.scopeValue("validate", {ref: sch.validate}) + : _`${gen.scopeValue("wrapper", {ref: sch})}.validate` +} + +export function callRef(cxt: KeywordCxt, v: Code, sch?: SchemaEnv, $async?: boolean): void { + const {gen, it} = cxt + const {allErrors, schemaEnv: env, opts} = it + const passCxt = opts.passContext ? N.this : nil + if ($async) callAsyncRef() + else callSyncRef() + + function callAsyncRef(): void { + if (!env.$async) throw new Error("async schema referenced by sync schema") + const valid = gen.let("valid") + gen.try( + () => { + gen.code(_`await ${callValidateCode(cxt, v, passCxt)}`) + addEvaluatedFrom(v) // TODO will not work with async, it has to be returned with the result + if (!allErrors) gen.assign(valid, true) + }, + (e) => { + gen.if(_`!(${e} instanceof ${it.ValidationError as Name})`, () => gen.throw(e)) + addErrorsFrom(e) + if (!allErrors) gen.assign(valid, false) + } + ) + cxt.ok(valid) + } + + function callSyncRef(): void { + cxt.result( + callValidateCode(cxt, v, passCxt), + () => addEvaluatedFrom(v), + () => addErrorsFrom(v) + ) + } + + function addErrorsFrom(source: Code): void { + const errs = _`${source}.errors` + gen.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) // TODO tagged + gen.assign(N.errors, _`${N.vErrors}.length`) + } + + function addEvaluatedFrom(source: Code): void { + if (!it.opts.unevaluated) return + const schEvaluated = sch?.validate?.evaluated + // TODO refactor + if (it.props !== true) { + if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== undefined) { + it.props = mergeEvaluated.props(gen, schEvaluated.props, it.props) + } + } else { + const props = gen.var("props", _`${source}.evaluated.props`) + it.props = mergeEvaluated.props(gen, props, it.props, Name) + } + } + if (it.items !== true) { + if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== undefined) { + it.items = mergeEvaluated.items(gen, schEvaluated.items, it.items) + } + } else { + const items = gen.var("items", _`${source}.evaluated.items`) + it.items = mergeEvaluated.items(gen, items, it.items, Name) + } + } + } +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/discriminator/index.ts b/node_modules/ajv/lib/vocabularies/discriminator/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..19ae6049f3464d2dd7518de70a9f10842aa88d66 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/discriminator/index.ts @@ -0,0 +1,113 @@ +import type {CodeKeywordDefinition, AnySchemaObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, getProperty, Name} from "../../compile/codegen" +import {DiscrError, DiscrErrorObj} from "../discriminator/types" +import {resolveRef, SchemaEnv} from "../../compile" +import MissingRefError from "../../compile/ref_error" +import {schemaHasRulesButRef} from "../../compile/util" + +export type DiscriminatorError = DiscrErrorObj | DiscrErrorObj + +const error: KeywordErrorDefinition = { + message: ({params: {discrError, tagName}}) => + discrError === DiscrError.Tag + ? `tag "${tagName}" must be string` + : `value of tag "${tagName}" must be in oneOf`, + params: ({params: {discrError, tag, tagName}}) => + _`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error, + code(cxt: KeywordCxt) { + const {gen, data, schema, parentSchema, it} = cxt + const {oneOf} = parentSchema + if (!it.opts.discriminator) { + throw new Error("discriminator: requires discriminator option") + } + const tagName = schema.propertyName + if (typeof tagName != "string") throw new Error("discriminator: requires propertyName") + if (schema.mapping) throw new Error("discriminator: mapping is not supported") + if (!oneOf) throw new Error("discriminator: requires oneOf keyword") + const valid = gen.let("valid", false) + const tag = gen.const("tag", _`${data}${getProperty(tagName)}`) + gen.if( + _`typeof ${tag} == "string"`, + () => validateMapping(), + () => cxt.error(false, {discrError: DiscrError.Tag, tag, tagName}) + ) + cxt.ok(valid) + + function validateMapping(): void { + const mapping = getMapping() + gen.if(false) + for (const tagValue in mapping) { + gen.elseIf(_`${tag} === ${tagValue}`) + gen.assign(valid, applyTagSchema(mapping[tagValue])) + } + gen.else() + cxt.error(false, {discrError: DiscrError.Mapping, tag, tagName}) + gen.endIf() + } + + function applyTagSchema(schemaProp?: number): Name { + const _valid = gen.name("valid") + const schCxt = cxt.subschema({keyword: "oneOf", schemaProp}, _valid) + cxt.mergeEvaluated(schCxt, Name) + return _valid + } + + function getMapping(): {[T in string]?: number} { + const oneOfMapping: {[T in string]?: number} = {} + const topRequired = hasRequired(parentSchema) + let tagRequired = true + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i] + if (sch?.$ref && !schemaHasRulesButRef(sch, it.self.RULES)) { + const ref = sch.$ref + sch = resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref) + if (sch instanceof SchemaEnv) sch = sch.schema + if (sch === undefined) throw new MissingRefError(it.opts.uriResolver, it.baseId, ref) + } + const propSch = sch?.properties?.[tagName] + if (typeof propSch != "object") { + throw new Error( + `discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"` + ) + } + tagRequired = tagRequired && (topRequired || hasRequired(sch)) + addMappings(propSch, i) + } + if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`) + return oneOfMapping + + function hasRequired({required}: AnySchemaObject): boolean { + return Array.isArray(required) && required.includes(tagName) + } + + function addMappings(sch: AnySchemaObject, i: number): void { + if (sch.const) { + addMapping(sch.const, i) + } else if (sch.enum) { + for (const tagValue of sch.enum) { + addMapping(tagValue, i) + } + } else { + throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`) + } + } + + function addMapping(tagValue: unknown, i: number): void { + if (typeof tagValue != "string" || tagValue in oneOfMapping) { + throw new Error(`discriminator: "${tagName}" values must be unique strings`) + } + oneOfMapping[tagValue] = i + } + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/discriminator/types.ts b/node_modules/ajv/lib/vocabularies/discriminator/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..bee5a278508e4926b85cf397fb601a7a3c2a78cb --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/discriminator/types.ts @@ -0,0 +1,12 @@ +import type {ErrorObject} from "../../types" + +export enum DiscrError { + Tag = "tag", + Mapping = "mapping", +} + +export type DiscrErrorObj = ErrorObject< + "discriminator", + {error: E; tag: string; tagValue: unknown}, + string +> diff --git a/node_modules/ajv/lib/vocabularies/draft2020.ts b/node_modules/ajv/lib/vocabularies/draft2020.ts new file mode 100644 index 0000000000000000000000000000000000000000..47fbf0ee6d75112abf222611ca514973833c8b53 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/draft2020.ts @@ -0,0 +1,23 @@ +import type {Vocabulary} from "../types" +import coreVocabulary from "./core" +import validationVocabulary from "./validation" +import getApplicatorVocabulary from "./applicator" +import dynamicVocabulary from "./dynamic" +import nextVocabulary from "./next" +import unevaluatedVocabulary from "./unevaluated" +import formatVocabulary from "./format" +import {metadataVocabulary, contentVocabulary} from "./metadata" + +const draft2020Vocabularies: Vocabulary[] = [ + dynamicVocabulary, + coreVocabulary, + validationVocabulary, + getApplicatorVocabulary(true), + formatVocabulary, + metadataVocabulary, + contentVocabulary, + nextVocabulary, + unevaluatedVocabulary, +] + +export default draft2020Vocabularies diff --git a/node_modules/ajv/lib/vocabularies/draft7.ts b/node_modules/ajv/lib/vocabularies/draft7.ts new file mode 100644 index 0000000000000000000000000000000000000000..226a644aa428d808c22dfd6808392fada925ae5e --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/draft7.ts @@ -0,0 +1,17 @@ +import type {Vocabulary} from "../types" +import coreVocabulary from "./core" +import validationVocabulary from "./validation" +import getApplicatorVocabulary from "./applicator" +import formatVocabulary from "./format" +import {metadataVocabulary, contentVocabulary} from "./metadata" + +const draft7Vocabularies: Vocabulary[] = [ + coreVocabulary, + validationVocabulary, + getApplicatorVocabulary(), + formatVocabulary, + metadataVocabulary, + contentVocabulary, +] + +export default draft7Vocabularies diff --git a/node_modules/ajv/lib/vocabularies/dynamic/dynamicAnchor.ts b/node_modules/ajv/lib/vocabularies/dynamic/dynamicAnchor.ts new file mode 100644 index 0000000000000000000000000000000000000000..ca1adb912af0347a3bb8e18ca50cf51405f2ba1f --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/dynamic/dynamicAnchor.ts @@ -0,0 +1,31 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, getProperty, Code} from "../../compile/codegen" +import N from "../../compile/names" +import {SchemaEnv, compileSchema} from "../../compile" +import {getValidate} from "../core/ref" + +const def: CodeKeywordDefinition = { + keyword: "$dynamicAnchor", + schemaType: "string", + code: (cxt) => dynamicAnchor(cxt, cxt.schema), +} + +export function dynamicAnchor(cxt: KeywordCxt, anchor: string): void { + const {gen, it} = cxt + it.schemaEnv.root.dynamicAnchors[anchor] = true + const v = _`${N.dynamicAnchors}${getProperty(anchor)}` + const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt) + gen.if(_`!${v}`, () => gen.assign(v, validate)) +} + +function _getValidate(cxt: KeywordCxt): Code { + const {schemaEnv, schema, self} = cxt.it + const {root, baseId, localRefs, meta} = schemaEnv.root + const {schemaId} = self.opts + const sch = new SchemaEnv({schema, schemaId, root, baseId, localRefs, meta}) + compileSchema.call(self, sch) + return getValidate(cxt, sch) +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/dynamic/dynamicRef.ts b/node_modules/ajv/lib/vocabularies/dynamic/dynamicRef.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a573f33024b4fc5045f17f0c251a3d6c75a22a7 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/dynamic/dynamicRef.ts @@ -0,0 +1,51 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, getProperty, Code, Name} from "../../compile/codegen" +import N from "../../compile/names" +import {callRef} from "../core/ref" + +const def: CodeKeywordDefinition = { + keyword: "$dynamicRef", + schemaType: "string", + code: (cxt) => dynamicRef(cxt, cxt.schema), +} + +export function dynamicRef(cxt: KeywordCxt, ref: string): void { + const {gen, keyword, it} = cxt + if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`) + const anchor = ref.slice(1) + if (it.allErrors) { + _dynamicRef() + } else { + const valid = gen.let("valid", false) + _dynamicRef(valid) + cxt.ok(valid) + } + + function _dynamicRef(valid?: Name): void { + // TODO the assumption here is that `recursiveRef: #` always points to the root + // of the schema object, which is not correct, because there may be $id that + // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor. + // Because of that 2 tests in recursiveRef.json fail. + // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ "$ref": "#" }`). + // (This problem is not tested in JSON-Schema-Test-Suite) + if (it.schemaEnv.root.dynamicAnchors[anchor]) { + const v = gen.let("_v", _`${N.dynamicAnchors}${getProperty(anchor)}`) + gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)) + } else { + _callRef(it.validateName, valid)() + } + } + + function _callRef(validate: Code, valid?: Name): () => void { + return valid + ? () => + gen.block(() => { + callRef(cxt, validate) + gen.let(valid, true) + }) + : () => callRef(cxt, validate) + } +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/dynamic/index.ts b/node_modules/ajv/lib/vocabularies/dynamic/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d521db6638b890151a7a901991f91793553dab0 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/dynamic/index.ts @@ -0,0 +1,9 @@ +import type {Vocabulary} from "../../types" +import dynamicAnchor from "./dynamicAnchor" +import dynamicRef from "./dynamicRef" +import recursiveAnchor from "./recursiveAnchor" +import recursiveRef from "./recursiveRef" + +const dynamic: Vocabulary = [dynamicAnchor, dynamicRef, recursiveAnchor, recursiveRef] + +export default dynamic diff --git a/node_modules/ajv/lib/vocabularies/dynamic/recursiveAnchor.ts b/node_modules/ajv/lib/vocabularies/dynamic/recursiveAnchor.ts new file mode 100644 index 0000000000000000000000000000000000000000..25f3db96bf07a2c60fc3eb860ea93ee6337e0137 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/dynamic/recursiveAnchor.ts @@ -0,0 +1,14 @@ +import type {CodeKeywordDefinition} from "../../types" +import {dynamicAnchor} from "./dynamicAnchor" +import {checkStrictMode} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: "$recursiveAnchor", + schemaType: "boolean", + code(cxt) { + if (cxt.schema) dynamicAnchor(cxt, "") + else checkStrictMode(cxt.it, "$recursiveAnchor: false is ignored") + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/dynamic/recursiveRef.ts b/node_modules/ajv/lib/vocabularies/dynamic/recursiveRef.ts new file mode 100644 index 0000000000000000000000000000000000000000..c84af0f05785affe11983f39f605a53502358c67 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/dynamic/recursiveRef.ts @@ -0,0 +1,10 @@ +import type {CodeKeywordDefinition} from "../../types" +import {dynamicRef} from "./dynamicRef" + +const def: CodeKeywordDefinition = { + keyword: "$recursiveRef", + schemaType: "string", + code: (cxt) => dynamicRef(cxt, cxt.schema), +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/errors.ts b/node_modules/ajv/lib/vocabularies/errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..c9ca3f02f040298cd2b2faff35740eaae6ea098e --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/errors.ts @@ -0,0 +1,18 @@ +import type {TypeError} from "../compile/validate/dataType" +import type {ApplicatorKeywordError} from "./applicator" +import type {ValidationKeywordError} from "./validation" +import type {FormatError} from "./format/format" +import type {UnevaluatedPropertiesError} from "./unevaluated/unevaluatedProperties" +import type {UnevaluatedItemsError} from "./unevaluated/unevaluatedItems" +import type {DependentRequiredError} from "./validation/dependentRequired" +import type {DiscriminatorError} from "./discriminator" + +export type DefinedError = + | TypeError + | ApplicatorKeywordError + | ValidationKeywordError + | FormatError + | UnevaluatedPropertiesError + | UnevaluatedItemsError + | DependentRequiredError + | DiscriminatorError diff --git a/node_modules/ajv/lib/vocabularies/format/format.ts b/node_modules/ajv/lib/vocabularies/format/format.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b1c13e764375dbb4dff021426a377f8103ab54f --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/format/format.ts @@ -0,0 +1,120 @@ +import type { + AddedFormat, + FormatValidator, + AsyncFormatValidator, + CodeKeywordDefinition, + KeywordErrorDefinition, + ErrorObject, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, nil, or, Code, getProperty, regexpCode} from "../../compile/codegen" + +type FormatValidate = + | FormatValidator + | FormatValidator + | AsyncFormatValidator + | AsyncFormatValidator + | RegExp + | string + | true + +export type FormatError = ErrorObject<"format", {format: string}, string | {$data: string}> + +const error: KeywordErrorDefinition = { + message: ({schemaCode}) => str`must match format "${schemaCode}"`, + params: ({schemaCode}) => _`{format: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error, + code(cxt: KeywordCxt, ruleType?: string) { + const {gen, data, $data, schema, schemaCode, it} = cxt + const {opts, errSchemaPath, schemaEnv, self} = it + if (!opts.validateFormats) return + + if ($data) validate$DataFormat() + else validateFormat() + + function validate$DataFormat(): void { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats, + }) + const fDef = gen.const("fDef", _`${fmts}[${schemaCode}]`) + const fType = gen.let("fType") + const format = gen.let("format") + // TODO simplify + gen.if( + _`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, + () => gen.assign(fType, _`${fDef}.type || "string"`).assign(format, _`${fDef}.validate`), + () => gen.assign(fType, _`"string"`).assign(format, fDef) + ) + cxt.fail$data(or(unknownFmt(), invalidFmt())) + + function unknownFmt(): Code { + if (opts.strictSchema === false) return nil + return _`${schemaCode} && !${format}` + } + + function invalidFmt(): Code { + const callFormat = schemaEnv.$async + ? _`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` + : _`${format}(${data})` + const validData = _`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))` + return _`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}` + } + } + + function validateFormat(): void { + const formatDef: AddedFormat | undefined = self.formats[schema] + if (!formatDef) { + unknownFormat() + return + } + if (formatDef === true) return + const [fmtType, format, fmtRef] = getFormat(formatDef) + if (fmtType === ruleType) cxt.pass(validCondition()) + + function unknownFormat(): void { + if (opts.strictSchema === false) { + self.logger.warn(unknownMsg()) + return + } + throw new Error(unknownMsg()) + + function unknownMsg(): string { + return `unknown format "${schema as string}" ignored in schema at path "${errSchemaPath}"` + } + } + + function getFormat(fmtDef: AddedFormat): [string, FormatValidate, Code] { + const code = + fmtDef instanceof RegExp + ? regexpCode(fmtDef) + : opts.code.formats + ? _`${opts.code.formats}${getProperty(schema)}` + : undefined + const fmt = gen.scopeValue("formats", {key: schema, ref: fmtDef, code}) + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { + return [fmtDef.type || "string", fmtDef.validate, _`${fmt}.validate`] + } + + return ["string", fmtDef, fmt] + } + + function validCondition(): Code { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) throw new Error("async format in sync schema") + return _`await ${fmtRef}(${data})` + } + return typeof format == "function" ? _`${fmtRef}(${data})` : _`${fmtRef}.test(${data})` + } + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/format/index.ts b/node_modules/ajv/lib/vocabularies/format/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..bca2f5b3d817051e07bd768888ed7142e63c4c97 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/format/index.ts @@ -0,0 +1,6 @@ +import type {Vocabulary} from "../../types" +import formatKeyword from "./format" + +const format: Vocabulary = [formatKeyword] + +export default format diff --git a/node_modules/ajv/lib/vocabularies/jtd/discriminator.ts b/node_modules/ajv/lib/vocabularies/jtd/discriminator.ts new file mode 100644 index 0000000000000000000000000000000000000000..f487c97f84332592ca90b09d5c046a87afd57f9b --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/discriminator.ts @@ -0,0 +1,89 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, not, getProperty, Name} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullableObject} from "./nullable" +import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error" +import {DiscrError, DiscrErrorObj} from "../discriminator/types" + +export type JTDDiscriminatorError = + | _JTDTypeError<"discriminator", "object", string> + | DiscrErrorObj + | DiscrErrorObj + +const error: KeywordErrorDefinition = { + message: (cxt) => { + const {schema, params} = cxt + return params.discrError + ? params.discrError === DiscrError.Tag + ? `tag "${schema}" must be string` + : `value of tag "${schema}" must be in mapping` + : typeErrorMessage(cxt, "object") + }, + params: (cxt) => { + const {schema, params} = cxt + return params.discrError + ? _`{error: ${params.discrError}, tag: ${schema}, tagValue: ${params.tag}}` + : typeErrorParams(cxt, "object") + }, +} + +const def: CodeKeywordDefinition = { + keyword: "discriminator", + schemaType: "string", + implements: ["mapping"], + error, + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema, parentSchema} = cxt + const [valid, cond] = checkNullableObject(cxt, data) + + gen.if(cond) + validateDiscriminator() + gen.elseIf(not(valid)) + cxt.error() + gen.endIf() + cxt.ok(valid) + + function validateDiscriminator(): void { + const tag = gen.const("tag", _`${data}${getProperty(schema)}`) + gen.if(_`${tag} === undefined`) + cxt.error(false, {discrError: DiscrError.Tag, tag}) + gen.elseIf(_`typeof ${tag} == "string"`) + validateMapping(tag) + gen.else() + cxt.error(false, {discrError: DiscrError.Tag, tag}, {instancePath: schema}) + gen.endIf() + } + + function validateMapping(tag: Name): void { + gen.if(false) + for (const tagValue in parentSchema.mapping) { + gen.elseIf(_`${tag} === ${tagValue}`) + gen.assign(valid, applyTagSchema(tagValue)) + } + gen.else() + cxt.error( + false, + {discrError: DiscrError.Mapping, tag}, + {instancePath: schema, schemaPath: "mapping", parentSchema: true} + ) + gen.endIf() + } + + function applyTagSchema(schemaProp: string): Name { + const _valid = gen.name("valid") + cxt.subschema( + { + keyword: "mapping", + schemaProp, + jtdDiscriminator: schema, + }, + _valid + ) + return _valid + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/elements.ts b/node_modules/ajv/lib/vocabularies/jtd/elements.ts new file mode 100644 index 0000000000000000000000000000000000000000..983af7c0276ed83cf92e5071a2a8a63ef2d522e4 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/elements.ts @@ -0,0 +1,32 @@ +import type {CodeKeywordDefinition, SchemaObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {alwaysValidSchema} from "../../compile/util" +import {validateArray} from "../code" +import {_, not} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullable} from "./nullable" +import {typeError, _JTDTypeError} from "./error" + +export type JTDElementsError = _JTDTypeError<"elements", "array", SchemaObject> + +const def: CodeKeywordDefinition = { + keyword: "elements", + schemaType: "object", + error: typeError("array"), + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema, it} = cxt + if (alwaysValidSchema(it, schema)) return + const [valid] = checkNullable(cxt) + gen.if(not(valid), () => + gen.if( + _`Array.isArray(${data})`, + () => gen.assign(valid, validateArray(cxt)), + () => cxt.error() + ) + ) + cxt.ok(valid) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/enum.ts b/node_modules/ajv/lib/vocabularies/jtd/enum.ts new file mode 100644 index 0000000000000000000000000000000000000000..75464ff8e13f581679d2b33662f34ac79a23e912 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/enum.ts @@ -0,0 +1,45 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition, ErrorObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, or, and, Code} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullable} from "./nullable" + +export type JTDEnumError = ErrorObject<"enum", {allowedValues: string[]}, string[]> + +const error: KeywordErrorDefinition = { + message: "must be equal to one of the allowed values", + params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "enum", + schemaType: "array", + error, + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema, schemaValue, parentSchema, it} = cxt + if (schema.length === 0) throw new Error("enum must have non-empty array") + if (schema.length !== new Set(schema).size) throw new Error("enum items must be unique") + let valid: Code + const isString = _`typeof ${data} == "string"` + if (schema.length >= it.opts.loopEnum) { + let cond: Code + ;[valid, cond] = checkNullable(cxt, isString) + gen.if(cond, loopEnum) + } else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + valid = and(isString, or(...schema.map((value: string) => _`${data} === ${value}`))) + if (parentSchema.nullable) valid = or(_`${data} === null`, valid) + } + cxt.pass(valid) + + function loopEnum(): void { + gen.forOf("v", schemaValue as Code, (v) => + gen.if(_`${valid} = ${data} === ${v}`, () => gen.break()) + ) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/error.ts b/node_modules/ajv/lib/vocabularies/jtd/error.ts new file mode 100644 index 0000000000000000000000000000000000000000..5069322588ebc486795ec075e49777888bbd8cdf --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/error.ts @@ -0,0 +1,23 @@ +import type {KeywordErrorDefinition, KeywordErrorCxt, ErrorObject} from "../../types" +import {_, Code} from "../../compile/codegen" + +export type _JTDTypeError = ErrorObject< + K, + {type: T; nullable: boolean}, + S +> + +export function typeError(t: string): KeywordErrorDefinition { + return { + message: (cxt) => typeErrorMessage(cxt, t), + params: (cxt) => typeErrorParams(cxt, t), + } +} + +export function typeErrorMessage({parentSchema}: KeywordErrorCxt, t: string): string { + return parentSchema?.nullable ? `must be ${t} or null` : `must be ${t}` +} + +export function typeErrorParams({parentSchema}: KeywordErrorCxt, t: string): Code { + return _`{type: ${t}, nullable: ${!!parentSchema?.nullable}}` +} diff --git a/node_modules/ajv/lib/vocabularies/jtd/index.ts b/node_modules/ajv/lib/vocabularies/jtd/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7baebc30788d80498e59328809b6b6a312d3315 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/index.ts @@ -0,0 +1,37 @@ +import type {Vocabulary} from "../../types" +import refKeyword from "./ref" +import typeKeyword, {JTDTypeError} from "./type" +import enumKeyword, {JTDEnumError} from "./enum" +import elements, {JTDElementsError} from "./elements" +import properties, {JTDPropertiesError} from "./properties" +import optionalProperties from "./optionalProperties" +import discriminator, {JTDDiscriminatorError} from "./discriminator" +import values, {JTDValuesError} from "./values" +import union from "./union" +import metadata from "./metadata" + +const jtdVocabulary: Vocabulary = [ + "definitions", + refKeyword, + typeKeyword, + enumKeyword, + elements, + properties, + optionalProperties, + discriminator, + values, + union, + metadata, + {keyword: "additionalProperties", schemaType: "boolean"}, + {keyword: "nullable", schemaType: "boolean"}, +] + +export default jtdVocabulary + +export type JTDErrorObject = + | JTDTypeError + | JTDEnumError + | JTDElementsError + | JTDPropertiesError + | JTDDiscriminatorError + | JTDValuesError diff --git a/node_modules/ajv/lib/vocabularies/jtd/metadata.ts b/node_modules/ajv/lib/vocabularies/jtd/metadata.ts new file mode 100644 index 0000000000000000000000000000000000000000..19eeb8c7d5b8f6ed1ab794cc0368f67d4be8bb8a --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/metadata.ts @@ -0,0 +1,24 @@ +import {KeywordCxt} from "../../ajv" +import type {CodeKeywordDefinition} from "../../types" +import {alwaysValidSchema} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: "metadata", + schemaType: "object", + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, schema, it} = cxt + if (alwaysValidSchema(it, schema)) return + const valid = gen.name("valid") + cxt.subschema({keyword: "metadata", jtdMetadata: true}, valid) + cxt.ok(valid) + }, +} + +export function checkMetadata({it, keyword}: KeywordCxt, metadata?: boolean): void { + if (it.jtdMetadata !== metadata) { + throw new Error(`JTD: "${keyword}" cannot be used in this schema location`) + } +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/nullable.ts b/node_modules/ajv/lib/vocabularies/jtd/nullable.ts new file mode 100644 index 0000000000000000000000000000000000000000..c74b05da72dbd4694ac215d5e5616e9050db283c --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/nullable.ts @@ -0,0 +1,21 @@ +import type {KeywordCxt} from "../../compile/validate" +import {_, not, nil, Code, Name} from "../../compile/codegen" + +export function checkNullable( + {gen, data, parentSchema}: KeywordCxt, + cond: Code = nil +): [Name, Code] { + const valid = gen.name("valid") + if (parentSchema.nullable) { + gen.let(valid, _`${data} === null`) + cond = not(valid) + } else { + gen.let(valid, false) + } + return [valid, cond] +} + +export function checkNullableObject(cxt: KeywordCxt, cond: Code): [Name, Code] { + const [valid, cond_] = checkNullable(cxt, cond) + return [valid, _`${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`] +} diff --git a/node_modules/ajv/lib/vocabularies/jtd/optionalProperties.ts b/node_modules/ajv/lib/vocabularies/jtd/optionalProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e91c8d91874407585b29641f22457822079fd66 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/optionalProperties.ts @@ -0,0 +1,15 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {validateProperties, error} from "./properties" + +const def: CodeKeywordDefinition = { + keyword: "optionalProperties", + schemaType: "object", + error, + code(cxt: KeywordCxt) { + if (cxt.parentSchema.properties) return + validateProperties(cxt) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/properties.ts b/node_modules/ajv/lib/vocabularies/jtd/properties.ts new file mode 100644 index 0000000000000000000000000000000000000000..9dd24c5cd62d46a913d644636fc9eacbb7f8a4fe --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/properties.ts @@ -0,0 +1,184 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + SchemaObject, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {propertyInData, allSchemaProperties, isOwnProperty} from "../code" +import {alwaysValidSchema, schemaRefOrVal} from "../../compile/util" +import {_, and, not, Code, Name} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullableObject} from "./nullable" +import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error" + +enum PropError { + Additional = "additional", + Missing = "missing", +} + +type PropKeyword = "properties" | "optionalProperties" + +type PropSchema = {[P in string]?: SchemaObject} + +export type JTDPropertiesError = + | _JTDTypeError + | ErrorObject + | ErrorObject + +export const error: KeywordErrorDefinition = { + message: (cxt) => { + const {params} = cxt + return params.propError + ? params.propError === PropError.Additional + ? "must NOT have additional properties" + : `must have property '${params.missingProperty}'` + : typeErrorMessage(cxt, "object") + }, + params: (cxt) => { + const {params} = cxt + return params.propError + ? params.propError === PropError.Additional + ? _`{error: ${params.propError}, additionalProperty: ${params.additionalProperty}}` + : _`{error: ${params.propError}, missingProperty: ${params.missingProperty}}` + : typeErrorParams(cxt, "object") + }, +} + +const def: CodeKeywordDefinition = { + keyword: "properties", + schemaType: "object", + error, + code: validateProperties, +} + +// const error: KeywordErrorDefinition = { +// message: "should NOT have additional properties", +// params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`, +// } + +export function validateProperties(cxt: KeywordCxt): void { + checkMetadata(cxt) + const {gen, data, parentSchema, it} = cxt + const {additionalProperties, nullable} = parentSchema + if (it.jtdDiscriminator && nullable) throw new Error("JTD: nullable inside discriminator mapping") + if (commonProperties()) { + throw new Error("JTD: properties and optionalProperties have common members") + } + const [allProps, properties] = schemaProperties("properties") + const [allOptProps, optProperties] = schemaProperties("optionalProperties") + if (properties.length === 0 && optProperties.length === 0 && additionalProperties) { + return + } + + const [valid, cond] = + it.jtdDiscriminator === undefined + ? checkNullableObject(cxt, data) + : [gen.let("valid", false), true] + gen.if(cond, () => + gen.assign(valid, true).block(() => { + validateProps(properties, "properties", true) + validateProps(optProperties, "optionalProperties") + if (!additionalProperties) validateAdditional() + }) + ) + cxt.pass(valid) + + function commonProperties(): boolean { + const props = parentSchema.properties as Record | undefined + const optProps = parentSchema.optionalProperties as Record | undefined + if (!(props && optProps)) return false + for (const p in props) { + if (Object.prototype.hasOwnProperty.call(optProps, p)) return true + } + return false + } + + function schemaProperties(keyword: string): [string[], string[]] { + const schema = parentSchema[keyword] + const allPs = schema ? allSchemaProperties(schema) : [] + if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) { + throw new Error(`JTD: discriminator tag used in ${keyword}`) + } + const ps = allPs.filter((p) => !alwaysValidSchema(it, schema[p])) + return [allPs, ps] + } + + function validateProps(props: string[], keyword: string, required?: boolean): void { + const _valid = gen.var("valid") + for (const prop of props) { + gen.if( + propertyInData(gen, data, prop, it.opts.ownProperties), + () => applyPropertySchema(prop, keyword, _valid), + () => missingProperty(prop) + ) + cxt.ok(_valid) + } + + function missingProperty(prop: string): void { + if (required) { + gen.assign(_valid, false) + cxt.error(false, {propError: PropError.Missing, missingProperty: prop}, {schemaPath: prop}) + } else { + gen.assign(_valid, true) + } + } + } + + function applyPropertySchema(prop: string, keyword: string, _valid: Name): void { + cxt.subschema( + { + keyword, + schemaProp: prop, + dataProp: prop, + }, + _valid + ) + } + + function validateAdditional(): void { + gen.forIn("key", data, (key: Name) => { + const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator) + const addOptProp = isAdditional(key, allOptProps, "optionalProperties") + const extra = + addProp === true ? addOptProp : addOptProp === true ? addProp : and(addProp, addOptProp) + gen.if(extra, () => { + if (it.opts.removeAdditional) { + gen.code(_`delete ${data}[${key}]`) + } else { + cxt.error( + false, + {propError: PropError.Additional, additionalProperty: key}, + {instancePath: key, parentSchema: true} + ) + if (!it.opts.allErrors) gen.break() + } + }) + }) + } + + function isAdditional( + key: Name, + props: string[], + keyword: string, + jtdDiscriminator?: string + ): Code | true { + let additional: Code | boolean + if (props.length > 8) { + // TODO maybe an option instead of hard-coded 8? + const propsSchema = schemaRefOrVal(it, parentSchema[keyword], keyword) + additional = not(isOwnProperty(gen, propsSchema as Code, key)) + if (jtdDiscriminator !== undefined) { + additional = and(additional, _`${key} !== ${jtdDiscriminator}`) + } + } else if (props.length || jtdDiscriminator !== undefined) { + const ps = jtdDiscriminator === undefined ? props : [jtdDiscriminator].concat(props) + additional = and(...ps.map((p) => _`${key} !== ${p}`)) + } else { + additional = true + } + return additional + } +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/ref.ts b/node_modules/ajv/lib/vocabularies/jtd/ref.ts new file mode 100644 index 0000000000000000000000000000000000000000..97646ee1b68885bf004ce2e629421abac07a991d --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/ref.ts @@ -0,0 +1,76 @@ +import type {CodeKeywordDefinition, AnySchemaObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {compileSchema, SchemaEnv} from "../../compile" +import {_, not, nil, stringify} from "../../compile/codegen" +import MissingRefError from "../../compile/ref_error" +import N from "../../compile/names" +import {getValidate, callRef} from "../core/ref" +import {checkMetadata} from "./metadata" + +const def: CodeKeywordDefinition = { + keyword: "ref", + schemaType: "string", + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema: ref, parentSchema, it} = cxt + const { + schemaEnv: {root}, + } = it + const valid = gen.name("valid") + if (parentSchema.nullable) { + gen.var(valid, _`${data} === null`) + gen.if(not(valid), validateJtdRef) + } else { + gen.var(valid, false) + validateJtdRef() + } + cxt.ok(valid) + + function validateJtdRef(): void { + const refSchema = (root.schema as AnySchemaObject).definitions?.[ref] + if (!refSchema) { + throw new MissingRefError(it.opts.uriResolver, "", ref, `No definition ${ref}`) + } + if (hasRef(refSchema) || !it.opts.inlineRefs) callValidate(refSchema) + else inlineRefSchema(refSchema) + } + + function callValidate(schema: AnySchemaObject): void { + const sch = compileSchema.call( + it.self, + new SchemaEnv({schema, root, schemaPath: `/definitions/${ref}`}) + ) + const v = getValidate(cxt, sch) + const errsCount = gen.const("_errs", N.errors) + callRef(cxt, v, sch, sch.$async) + gen.assign(valid, _`${errsCount} === ${N.errors}`) + } + + function inlineRefSchema(schema: AnySchemaObject): void { + const schName = gen.scopeValue( + "schema", + it.opts.code.source === true ? {ref: schema, code: stringify(schema)} : {ref: schema} + ) + cxt.subschema( + { + schema, + dataTypes: [], + schemaPath: nil, + topSchemaRef: schName, + errSchemaPath: `/definitions/${ref}`, + }, + valid + ) + } + }, +} + +export function hasRef(schema: AnySchemaObject): boolean { + for (const key in schema) { + let sch: AnySchemaObject + if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch))) return true + } + return false +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/type.ts b/node_modules/ajv/lib/vocabularies/jtd/type.ts new file mode 100644 index 0000000000000000000000000000000000000000..17274300b70b11b72977a965a4410f21a8f0f19c --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/type.ts @@ -0,0 +1,75 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, nil, or, Code} from "../../compile/codegen" +import validTimestamp from "../../runtime/timestamp" +import {useFunc} from "../../compile/util" +import {checkMetadata} from "./metadata" +import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error" + +export type JTDTypeError = _JTDTypeError<"type", JTDType, JTDType> + +export type IntType = "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32" + +export const intRange: {[T in IntType]: [number, number, number]} = { + int8: [-128, 127, 3], + uint8: [0, 255, 3], + int16: [-32768, 32767, 5], + uint16: [0, 65535, 5], + int32: [-2147483648, 2147483647, 10], + uint32: [0, 4294967295, 10], +} + +export type JTDType = "boolean" | "string" | "timestamp" | "float32" | "float64" | IntType + +const error: KeywordErrorDefinition = { + message: (cxt) => typeErrorMessage(cxt, cxt.schema), + params: (cxt) => typeErrorParams(cxt, cxt.schema), +} + +function timestampCode(cxt: KeywordCxt): Code { + const {gen, data, it} = cxt + const {timestamp, allowDate} = it.opts + if (timestamp === "date") return _`${data} instanceof Date ` + const vts = useFunc(gen, validTimestamp) + const allowDateArg = allowDate ? _`, true` : nil + const validString = _`typeof ${data} == "string" && ${vts}(${data}${allowDateArg})` + return timestamp === "string" ? validString : or(_`${data} instanceof Date`, validString) +} + +const def: CodeKeywordDefinition = { + keyword: "type", + schemaType: "string", + error, + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {data, schema, parentSchema, it} = cxt + let cond: Code + switch (schema) { + case "boolean": + case "string": + cond = _`typeof ${data} == ${schema}` + break + case "timestamp": { + cond = timestampCode(cxt) + break + } + case "float32": + case "float64": + cond = _`typeof ${data} == "number"` + break + default: { + const sch = schema as IntType + cond = _`typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)` + if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) { + if (sch === "uint32") cond = _`${cond} && ${data} >= 0` + } else { + const [min, max] = intRange[sch] + cond = _`${cond} && ${data} >= ${min} && ${data} <= ${max}` + } + } + } + cxt.pass(parentSchema.nullable ? or(_`${data} === null`, cond) : cond) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/union.ts b/node_modules/ajv/lib/vocabularies/jtd/union.ts new file mode 100644 index 0000000000000000000000000000000000000000..588f07ab4a96bb88512579ce0cc683eaa5925eb2 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/union.ts @@ -0,0 +1,12 @@ +import type {CodeKeywordDefinition} from "../../types" +import {validateUnion} from "../code" + +const def: CodeKeywordDefinition = { + keyword: "union", + schemaType: "array", + trackErrors: true, + code: validateUnion, + error: {message: "must match a schema in union"}, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/jtd/values.ts b/node_modules/ajv/lib/vocabularies/jtd/values.ts new file mode 100644 index 0000000000000000000000000000000000000000..e64945077647a81d99a6460ae6e86b5394c250c4 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/jtd/values.ts @@ -0,0 +1,58 @@ +import type {CodeKeywordDefinition, SchemaObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {alwaysValidSchema, Type} from "../../compile/util" +import {not, or, Name} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullableObject} from "./nullable" +import {typeError, _JTDTypeError} from "./error" + +export type JTDValuesError = _JTDTypeError<"values", "object", SchemaObject> + +const def: CodeKeywordDefinition = { + keyword: "values", + schemaType: "object", + error: typeError("object"), + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema, it} = cxt + const [valid, cond] = checkNullableObject(cxt, data) + if (alwaysValidSchema(it, schema)) { + gen.if(not(or(cond, valid)), () => cxt.error()) + } else { + gen.if(cond) + gen.assign(valid, validateMap()) + gen.elseIf(not(valid)) + cxt.error() + gen.endIf() + } + cxt.ok(valid) + + function validateMap(): Name | boolean { + const _valid = gen.name("valid") + if (it.allErrors) { + const validMap = gen.let("valid", true) + validateValues(() => gen.assign(validMap, false)) + return validMap + } + gen.var(_valid, true) + validateValues(() => gen.break()) + return _valid + + function validateValues(notValid: () => void): void { + gen.forIn("key", data, (key) => { + cxt.subschema( + { + keyword: "values", + dataProp: key, + dataPropType: Type.Str, + }, + _valid + ) + gen.if(not(_valid), notValid) + }) + } + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/metadata.ts b/node_modules/ajv/lib/vocabularies/metadata.ts new file mode 100644 index 0000000000000000000000000000000000000000..b9d5af85fe921f9cd553e61da6a09234213f0e5b --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/metadata.ts @@ -0,0 +1,17 @@ +import type {Vocabulary} from "../types" + +export const metadataVocabulary: Vocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples", +] + +export const contentVocabulary: Vocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema", +] diff --git a/node_modules/ajv/lib/vocabularies/next.ts b/node_modules/ajv/lib/vocabularies/next.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e987ad21241259ff0453a45534d0822fa3b7e58 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/next.ts @@ -0,0 +1,8 @@ +import type {Vocabulary} from "../types" +import dependentRequired from "./validation/dependentRequired" +import dependentSchemas from "./applicator/dependentSchemas" +import limitContains from "./validation/limitContains" + +const next: Vocabulary = [dependentRequired, dependentSchemas, limitContains] + +export default next diff --git a/node_modules/ajv/lib/vocabularies/unevaluated/index.ts b/node_modules/ajv/lib/vocabularies/unevaluated/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7f0815dbb00cfccd96f8910bea06182f9e19993 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/unevaluated/index.ts @@ -0,0 +1,7 @@ +import type {Vocabulary} from "../../types" +import unevaluatedProperties from "./unevaluatedProperties" +import unevaluatedItems from "./unevaluatedItems" + +const unevaluated: Vocabulary = [unevaluatedProperties, unevaluatedItems] + +export default unevaluated diff --git a/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedItems.ts b/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedItems.ts new file mode 100644 index 0000000000000000000000000000000000000000..50bf0e7c17873ad2f435a92105745d4aa8ed9d26 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedItems.ts @@ -0,0 +1,47 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, not, Name} from "../../compile/codegen" +import {alwaysValidSchema, Type} from "../../compile/util" + +export type UnevaluatedItemsError = ErrorObject<"unevaluatedItems", {limit: number}, AnySchema> + +const error: KeywordErrorDefinition = { + message: ({params: {len}}) => str`must NOT have more than ${len} items`, + params: ({params: {len}}) => _`{limit: ${len}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "unevaluatedItems", + type: "array", + schemaType: ["boolean", "object"], + error, + code(cxt: KeywordCxt) { + const {gen, schema, data, it} = cxt + const items = it.items || 0 + if (items === true) return + const len = gen.const("len", _`${data}.length`) + if (schema === false) { + cxt.setParams({len: items}) + cxt.fail(_`${len} > ${items}`) + } else if (typeof schema == "object" && !alwaysValidSchema(it, schema)) { + const valid = gen.var("valid", _`${len} <= ${items}`) + gen.if(not(valid), () => validateItems(valid, items)) + cxt.ok(valid) + } + it.items = true + + function validateItems(valid: Name, from: Name | number): void { + gen.forRange("i", from, len, (i) => { + cxt.subschema({keyword: "unevaluatedItems", dataProp: i, dataPropType: Type.Num}, valid) + if (!it.allErrors) gen.if(not(valid), () => gen.break()) + }) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedProperties.ts b/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e6868fa326dab80317a39e135a4b4deb1d0f2f4 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedProperties.ts @@ -0,0 +1,85 @@ +import type { + CodeKeywordDefinition, + KeywordErrorDefinition, + ErrorObject, + AnySchema, +} from "../../types" +import {_, not, and, Name, Code} from "../../compile/codegen" +import {alwaysValidSchema, Type} from "../../compile/util" +import N from "../../compile/names" + +export type UnevaluatedPropertiesError = ErrorObject< + "unevaluatedProperties", + {unevaluatedProperty: string}, + AnySchema +> + +const error: KeywordErrorDefinition = { + message: "must NOT have unevaluated properties", + params: ({params}) => _`{unevaluatedProperty: ${params.unevaluatedProperty}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "unevaluatedProperties", + type: "object", + schemaType: ["boolean", "object"], + trackErrors: true, + error, + code(cxt) { + const {gen, schema, data, errsCount, it} = cxt + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error") + const {allErrors, props} = it + if (props instanceof Name) { + gen.if(_`${props} !== true`, () => + gen.forIn("key", data, (key: Name) => + gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)) + ) + ) + } else if (props !== true) { + gen.forIn("key", data, (key: Name) => + props === undefined + ? unevaluatedPropCode(key) + : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key)) + ) + } + it.props = true + cxt.ok(_`${errsCount} === ${N.errors}`) + + function unevaluatedPropCode(key: Name): void { + if (schema === false) { + cxt.setParams({unevaluatedProperty: key}) + cxt.error() + if (!allErrors) gen.break() + return + } + + if (!alwaysValidSchema(it, schema)) { + const valid = gen.name("valid") + cxt.subschema( + { + keyword: "unevaluatedProperties", + dataProp: key, + dataPropType: Type.Str, + }, + valid + ) + if (!allErrors) gen.if(not(valid), () => gen.break()) + } + } + + function unevaluatedDynamic(evaluatedProps: Name, key: Name): Code { + return _`!${evaluatedProps} || !${evaluatedProps}[${key}]` + } + + function unevaluatedStatic(evaluatedProps: {[K in string]?: true}, key: Name): Code { + const ps: Code[] = [] + for (const p in evaluatedProps) { + if (evaluatedProps[p] === true) ps.push(_`${key} !== ${p}`) + } + return and(...ps) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/const.ts b/node_modules/ajv/lib/vocabularies/validation/const.ts new file mode 100644 index 0000000000000000000000000000000000000000..a3b94a5dcd3d0ad993a83088694b9375089f735d --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/const.ts @@ -0,0 +1,28 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_} from "../../compile/codegen" +import {useFunc} from "../../compile/util" +import equal from "../../runtime/equal" + +export type ConstError = ErrorObject<"const", {allowedValue: any}> + +const error: KeywordErrorDefinition = { + message: "must be equal to constant", + params: ({schemaCode}) => _`{allowedValue: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "const", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, data, $data, schemaCode, schema} = cxt + if ($data || (schema && typeof schema == "object")) { + cxt.fail$data(_`!${useFunc(gen, equal)}(${data}, ${schemaCode})`) + } else { + cxt.fail(_`${schema} !== ${data}`) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/dependentRequired.ts b/node_modules/ajv/lib/vocabularies/validation/dependentRequired.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c616cfa9ac79fabdd5e4d2ff19840adec61f813 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/dependentRequired.ts @@ -0,0 +1,23 @@ +import type {CodeKeywordDefinition, ErrorObject} from "../../types" +import { + validatePropertyDeps, + error, + DependenciesErrorParams, + PropertyDependencies, +} from "../applicator/dependencies" + +export type DependentRequiredError = ErrorObject< + "dependentRequired", + DependenciesErrorParams, + PropertyDependencies +> + +const def: CodeKeywordDefinition = { + keyword: "dependentRequired", + type: "object", + schemaType: "object", + error, + code: (cxt) => validatePropertyDeps(cxt), +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/enum.ts b/node_modules/ajv/lib/vocabularies/validation/enum.ts new file mode 100644 index 0000000000000000000000000000000000000000..76377fb02e6a9e8843ba08b2e858a19a067b787b --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/enum.ts @@ -0,0 +1,54 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, or, Name, Code} from "../../compile/codegen" +import {useFunc} from "../../compile/util" +import equal from "../../runtime/equal" + +export type EnumError = ErrorObject<"enum", {allowedValues: any[]}, any[] | {$data: string}> + +const error: KeywordErrorDefinition = { + message: "must be equal to one of the allowed values", + params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "enum", + schemaType: "array", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, data, $data, schema, schemaCode, it} = cxt + if (!$data && schema.length === 0) throw new Error("enum must have non-empty array") + const useLoop = schema.length >= it.opts.loopEnum + let eql: Name | undefined + const getEql = (): Name => (eql ??= useFunc(gen, equal)) + + let valid: Code + if (useLoop || $data) { + valid = gen.let("valid") + cxt.block$data(valid, loopEnum) + } else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + const vSchema = gen.const("vSchema", schemaCode) + valid = or(...schema.map((_x: unknown, i: number) => equalCode(vSchema, i))) + } + cxt.pass(valid) + + function loopEnum(): void { + gen.assign(valid, false) + gen.forOf("v", schemaCode as Code, (v) => + gen.if(_`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()) + ) + } + + function equalCode(vSchema: Name, i: number): Code { + const sch = schema[i] + return typeof sch === "object" && sch !== null + ? _`${getEql()}(${data}, ${vSchema}[${i}])` + : _`${data} === ${sch}` + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/index.ts b/node_modules/ajv/lib/vocabularies/validation/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..3531b19628b7dfb2526a81cd38d6c93ee1a54dbe --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/index.ts @@ -0,0 +1,49 @@ +import type {ErrorObject, Vocabulary} from "../../types" +import limitNumber, {LimitNumberError} from "./limitNumber" +import multipleOf, {MultipleOfError} from "./multipleOf" +import limitLength from "./limitLength" +import pattern, {PatternError} from "./pattern" +import limitProperties from "./limitProperties" +import required, {RequiredError} from "./required" +import limitItems from "./limitItems" +import uniqueItems, {UniqueItemsError} from "./uniqueItems" +import constKeyword, {ConstError} from "./const" +import enumKeyword, {EnumError} from "./enum" + +const validation: Vocabulary = [ + // number + limitNumber, + multipleOf, + // string + limitLength, + pattern, + // object + limitProperties, + required, + // array + limitItems, + uniqueItems, + // any + {keyword: "type", schemaType: ["string", "array"]}, + {keyword: "nullable", schemaType: "boolean"}, + constKeyword, + enumKeyword, +] + +export default validation + +type LimitError = ErrorObject< + "maxItems" | "minItems" | "minProperties" | "maxProperties" | "minLength" | "maxLength", + {limit: number}, + number | {$data: string} +> + +export type ValidationKeywordError = + | LimitError + | LimitNumberError + | MultipleOfError + | PatternError + | RequiredError + | UniqueItemsError + | ConstError + | EnumError diff --git a/node_modules/ajv/lib/vocabularies/validation/limitContains.ts b/node_modules/ajv/lib/vocabularies/validation/limitContains.ts new file mode 100644 index 0000000000000000000000000000000000000000..8bb43c1a4a66f1d8781181cbd07f06edb76aea02 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/limitContains.ts @@ -0,0 +1,16 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {checkStrictMode} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: ["maxContains", "minContains"], + type: "array", + schemaType: "number", + code({keyword, parentSchema, it}: KeywordCxt) { + if (parentSchema.contains === undefined) { + checkStrictMode(it, `"${keyword}" without "contains" is ignored`) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/limitItems.ts b/node_modules/ajv/lib/vocabularies/validation/limitItems.ts new file mode 100644 index 0000000000000000000000000000000000000000..566de8588b3be2fcccdeff56f26338be0dc6fcb4 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/limitItems.ts @@ -0,0 +1,26 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, operators} from "../../compile/codegen" + +const error: KeywordErrorDefinition = { + message({keyword, schemaCode}) { + const comp = keyword === "maxItems" ? "more" : "fewer" + return str`must NOT have ${comp} than ${schemaCode} items` + }, + params: ({schemaCode}) => _`{limit: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {keyword, data, schemaCode} = cxt + const op = keyword === "maxItems" ? operators.GT : operators.LT + cxt.fail$data(_`${data}.length ${op} ${schemaCode}`) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/limitLength.ts b/node_modules/ajv/lib/vocabularies/validation/limitLength.ts new file mode 100644 index 0000000000000000000000000000000000000000..f4f947259549ad3d0e9fe992e5a92a83696e1177 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/limitLength.ts @@ -0,0 +1,30 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, operators} from "../../compile/codegen" +import {useFunc} from "../../compile/util" +import ucs2length from "../../runtime/ucs2length" + +const error: KeywordErrorDefinition = { + message({keyword, schemaCode}) { + const comp = keyword === "maxLength" ? "more" : "fewer" + return str`must NOT have ${comp} than ${schemaCode} characters` + }, + params: ({schemaCode}) => _`{limit: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {keyword, data, schemaCode, it} = cxt + const op = keyword === "maxLength" ? operators.GT : operators.LT + const len = + it.opts.unicode === false ? _`${data}.length` : _`${useFunc(cxt.gen, ucs2length)}(${data})` + cxt.fail$data(_`${len} ${op} ${schemaCode}`) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/limitNumber.ts b/node_modules/ajv/lib/vocabularies/validation/limitNumber.ts new file mode 100644 index 0000000000000000000000000000000000000000..5499202efbfec965a9acd8c71e145e79110923d9 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/limitNumber.ts @@ -0,0 +1,42 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, operators, Code} from "../../compile/codegen" + +const ops = operators + +type Kwd = "maximum" | "minimum" | "exclusiveMaximum" | "exclusiveMinimum" + +type Comparison = "<=" | ">=" | "<" | ">" + +const KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = { + maximum: {okStr: "<=", ok: ops.LTE, fail: ops.GT}, + minimum: {okStr: ">=", ok: ops.GTE, fail: ops.LT}, + exclusiveMaximum: {okStr: "<", ok: ops.LT, fail: ops.GTE}, + exclusiveMinimum: {okStr: ">", ok: ops.GT, fail: ops.LTE}, +} + +export type LimitNumberError = ErrorObject< + Kwd, + {limit: number; comparison: Comparison}, + number | {$data: string} +> + +const error: KeywordErrorDefinition = { + message: ({keyword, schemaCode}) => str`must be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`, + params: ({keyword, schemaCode}) => + _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {keyword, data, schemaCode} = cxt + cxt.fail$data(_`${data} ${KWDs[keyword as Kwd].fail} ${schemaCode} || isNaN(${data})`) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/limitProperties.ts b/node_modules/ajv/lib/vocabularies/validation/limitProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..07fffa8b39a03798262a94da5c55ac6e3e7ce200 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/limitProperties.ts @@ -0,0 +1,26 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, operators} from "../../compile/codegen" + +const error: KeywordErrorDefinition = { + message({keyword, schemaCode}) { + const comp = keyword === "maxProperties" ? "more" : "fewer" + return str`must NOT have ${comp} than ${schemaCode} properties` + }, + params: ({schemaCode}) => _`{limit: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {keyword, data, schemaCode} = cxt + const op = keyword === "maxProperties" ? operators.GT : operators.LT + cxt.fail$data(_`Object.keys(${data}).length ${op} ${schemaCode}`) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/multipleOf.ts b/node_modules/ajv/lib/vocabularies/validation/multipleOf.ts new file mode 100644 index 0000000000000000000000000000000000000000..1fd79abbd91c41d872ec775441f48b69550e8655 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/multipleOf.ts @@ -0,0 +1,34 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str} from "../../compile/codegen" + +export type MultipleOfError = ErrorObject< + "multipleOf", + {multipleOf: number}, + number | {$data: string} +> + +const error: KeywordErrorDefinition = { + message: ({schemaCode}) => str`must be multiple of ${schemaCode}`, + params: ({schemaCode}) => _`{multipleOf: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, data, schemaCode, it} = cxt + // const bdt = bad$DataType(schemaCode, def.schemaType, $data) + const prec = it.opts.multipleOfPrecision + const res = gen.let("res") + const invalid = prec + ? _`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` + : _`${res} !== parseInt(${res})` + cxt.fail$data(_`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`) + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/pattern.ts b/node_modules/ajv/lib/vocabularies/validation/pattern.ts new file mode 100644 index 0000000000000000000000000000000000000000..bb0203b88794d72d91717f1091009766ea0bc548 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/pattern.ts @@ -0,0 +1,39 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {usePattern} from "../code" +import {useFunc} from "../../compile/util" +import {_, str} from "../../compile/codegen" + +export type PatternError = ErrorObject<"pattern", {pattern: string}, string | {$data: string}> + +const error: KeywordErrorDefinition = { + message: ({schemaCode}) => str`must match pattern "${schemaCode}"`, + params: ({schemaCode}) => _`{pattern: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, data, $data, schema, schemaCode, it} = cxt + const u = it.opts.unicodeRegExp ? "u" : "" + if ($data) { + const {regExp} = it.opts.code + const regExpCode = regExp.code === "new RegExp" ? _`new RegExp` : useFunc(gen, regExp) + const valid = gen.let("valid") + gen.try( + () => gen.assign(valid, _`${regExpCode}(${schemaCode}, ${u}).test(${data})`), + () => gen.assign(valid, false) + ) + cxt.fail$data(_`!${valid}`) + } else { + const regExp = usePattern(cxt, schema) + cxt.fail$data(_`!${regExp}.test(${data})`) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/required.ts b/node_modules/ajv/lib/vocabularies/validation/required.ts new file mode 100644 index 0000000000000000000000000000000000000000..fea7367ed7b8f0cfeee2a73a1cecaca7f8c0c115 --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/required.ts @@ -0,0 +1,98 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import { + checkReportMissingProp, + checkMissingProp, + reportMissingProp, + propertyInData, + noPropertyInData, +} from "../code" +import {_, str, nil, not, Name, Code} from "../../compile/codegen" +import {checkStrictMode} from "../../compile/util" + +export type RequiredError = ErrorObject< + "required", + {missingProperty: string}, + string[] | {$data: string} +> + +const error: KeywordErrorDefinition = { + message: ({params: {missingProperty}}) => str`must have required property '${missingProperty}'`, + params: ({params: {missingProperty}}) => _`{missingProperty: ${missingProperty}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, schema, schemaCode, data, $data, it} = cxt + const {opts} = it + if (!$data && schema.length === 0) return + const useLoop = schema.length >= opts.loopRequired + if (it.allErrors) allErrorsMode() + else exitOnErrorMode() + + if (opts.strictRequired) { + const props = cxt.parentSchema.properties + const {definedProperties} = cxt.it + for (const requiredKey of schema) { + if (props?.[requiredKey] === undefined && !definedProperties.has(requiredKey)) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath + const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)` + checkStrictMode(it, msg, it.opts.strictRequired) + } + } + } + + function allErrorsMode(): void { + if (useLoop || $data) { + cxt.block$data(nil, loopAllRequired) + } else { + for (const prop of schema) { + checkReportMissingProp(cxt, prop) + } + } + } + + function exitOnErrorMode(): void { + const missing = gen.let("missing") + if (useLoop || $data) { + const valid = gen.let("valid", true) + cxt.block$data(valid, () => loopUntilMissing(missing, valid)) + cxt.ok(valid) + } else { + gen.if(checkMissingProp(cxt, schema, missing)) + reportMissingProp(cxt, missing) + gen.else() + } + } + + function loopAllRequired(): void { + gen.forOf("prop", schemaCode as Code, (prop) => { + cxt.setParams({missingProperty: prop}) + gen.if(noPropertyInData(gen, data, prop, opts.ownProperties), () => cxt.error()) + }) + } + + function loopUntilMissing(missing: Name, valid: Name): void { + cxt.setParams({missingProperty: missing}) + gen.forOf( + missing, + schemaCode as Code, + () => { + gen.assign(valid, propertyInData(gen, data, missing, opts.ownProperties)) + gen.if(not(valid), () => { + cxt.error() + gen.break() + }) + }, + nil + ) + } + }, +} + +export default def diff --git a/node_modules/ajv/lib/vocabularies/validation/uniqueItems.ts b/node_modules/ajv/lib/vocabularies/validation/uniqueItems.ts new file mode 100644 index 0000000000000000000000000000000000000000..765c4d04fc2472b774838d06fe13c15a98b58a9b --- /dev/null +++ b/node_modules/ajv/lib/vocabularies/validation/uniqueItems.ts @@ -0,0 +1,79 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {checkDataTypes, getSchemaTypes, DataType} from "../../compile/validate/dataType" +import {_, str, Name} from "../../compile/codegen" +import {useFunc} from "../../compile/util" +import equal from "../../runtime/equal" + +export type UniqueItemsError = ErrorObject< + "uniqueItems", + {i: number; j: number}, + boolean | {$data: string} +> + +const error: KeywordErrorDefinition = { + message: ({params: {i, j}}) => + str`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({params: {i, j}}) => _`{i: ${i}, j: ${j}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, data, $data, schema, parentSchema, schemaCode, it} = cxt + if (!$data && !schema) return + const valid = gen.let("valid") + const itemTypes = parentSchema.items ? getSchemaTypes(parentSchema.items) : [] + cxt.block$data(valid, validateUniqueItems, _`${schemaCode} === false`) + cxt.ok(valid) + + function validateUniqueItems(): void { + const i = gen.let("i", _`${data}.length`) + const j = gen.let("j") + cxt.setParams({i, j}) + gen.assign(valid, true) + gen.if(_`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)) + } + + function canOptimize(): boolean { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array") + } + + function loopN(i: Name, j: Name): void { + const item = gen.name("item") + const wrongType = checkDataTypes(itemTypes, item, it.opts.strictNumbers, DataType.Wrong) + const indices = gen.const("indices", _`{}`) + gen.for(_`;${i}--;`, () => { + gen.let(item, _`${data}[${i}]`) + gen.if(wrongType, _`continue`) + if (itemTypes.length > 1) gen.if(_`typeof ${item} == "string"`, _`${item} += "_"`) + gen + .if(_`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, _`${indices}[${item}]`) + cxt.error() + gen.assign(valid, false).break() + }) + .code(_`${indices}[${item}] = ${i}`) + }) + } + + function loopN2(i: Name, j: Name): void { + const eql = useFunc(gen, equal) + const outer = gen.name("outer") + gen.label(outer).for(_`;${i}--;`, () => + gen.for(_`${j} = ${i}; ${j}--;`, () => + gen.if(_`${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error() + gen.assign(valid, false).break(outer) + }) + ) + ) + } + }, +} + +export default def diff --git a/node_modules/ajv/package.json b/node_modules/ajv/package.json new file mode 100644 index 0000000000000000000000000000000000000000..50fa6a639c704492f0a6c0c28a3c86d20321a395 --- /dev/null +++ b/node_modules/ajv/package.json @@ -0,0 +1,126 @@ +{ + "name": "ajv", + "version": "8.20.0", + "description": "Another JSON Schema Validator", + "main": "dist/ajv.js", + "types": "dist/ajv.d.ts", + "files": [ + "lib/", + "dist/", + ".runkit_example.js" + ], + "sideEffects": false, + "scripts": { + "eslint": "eslint \"lib/**/*.ts\" \"spec/**/*.*s\" --ignore-pattern spec/JSON-Schema-Test-Suite", + "prettier:write": "prettier --write \"./**/*.{json,yaml,js,ts}\"", + "prettier:check": "prettier --list-different \"./**/*.{json,yaml,js,ts}\"", + "test-spec": "cross-env TS_NODE_PROJECT=spec/tsconfig.json mocha -r ts-node/register \"spec/**/*.spec.{ts,js}\" -R dot", + "test-codegen": "nyc cross-env TS_NODE_PROJECT=spec/tsconfig.json mocha -r ts-node/register 'spec/codegen.spec.ts' -R spec", + "test-debug": "npm run test-spec -- --inspect-brk", + "test-cov": "nyc npm run test-spec", + "rollup": "rm -rf bundle && rollup -c", + "bundle": "rm -rf bundle && node ./scripts/bundle.js ajv ajv7 ajv7 && node ./scripts/bundle.js 2019 ajv2019 ajv2019 && node ./scripts/bundle.js 2020 ajv2020 ajv2020 && node ./scripts/bundle.js jtd ajvJTD ajvJTD", + "build": "rm -rf dist && tsc && cp -r lib/refs dist && rm dist/refs/json-schema-2019-09/index.ts && rm dist/refs/json-schema-2020-12/index.ts && rm dist/refs/jtd-schema.ts", + "json-tests": "rm -rf spec/_json/*.js && node scripts/jsontests", + "test-karma": "karma start", + "test-browser": "rm -rf .browser && npm run bundle && scripts/prepare-tests && karma start", + "test-all": "npm run test-cov", + "test": "npm run json-tests && npm run prettier:check && npm run eslint && npm link && npm link --legacy-peer-deps ajv && npm run test-cov", + "test-ci": "AJV_FULL_TEST=true npm test", + "prepublish": "npm run build", + "benchmark": "npm i && npm run build && npm link && cd ./benchmark && npm link --legacy-peer-deps ajv && npm i && node ./jtd", + "docs:dev": "./scripts/prepare-site && vuepress dev docs", + "docs:build": "./scripts/prepare-site && vuepress build docs" + }, + "nyc": { + "exclude": [ + "**/spec/**", + "node_modules" + ], + "reporter": [ + "lcov", + "text-summary" + ] + }, + "repository": "ajv-validator/ajv", + "keywords": [ + "JSON", + "schema", + "validator", + "validation", + "jsonschema", + "json-schema", + "json-schema-validator", + "json-schema-validation" + ], + "author": "Evgeny Poberezkin", + "license": "MIT", + "bugs": "https://github.com/ajv-validator/ajv/issues", + "homepage": "https://ajv.js.org", + "runkitExampleFilename": ".runkit_example.js", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "devDependencies": { + "@ajv-validator/config": "^0.5.0", + "@rollup/plugin-commonjs": "^25.0.7", + "@rollup/plugin-json": "^6.1.0", + "@rollup/plugin-node-resolve": "^15.2.3", + "@rollup/plugin-typescript": "^11.1.6", + "@types/chai": "^4.3.11", + "@types/mocha": "^10.0.6", + "@types/node": "^20.11.30", + "@types/require-from-string": "^1.2.3", + "@typescript-eslint/eslint-plugin": "^7.3.1", + "@typescript-eslint/parser": "^7.3.1", + "ajv-formats": "^3.0.1", + "browserify": "^17.0.0", + "chai": "^4.4.1", + "cross-env": "^7.0.3", + "dayjs": "^1.11.10", + "dayjs-plugin-utc": "^0.1.2", + "eslint": "^8.57.0", + "eslint-config-prettier": "^9.1.0", + "glob": "^10.3.10", + "husky": "^9.0.11", + "jimp": "^0.22.10", + "js-beautify": "^1.15.1", + "json-schema-test": "^2.0.0", + "karma": "^6.4.2", + "karma-chrome-launcher": "^3.2.0", + "karma-mocha": "^2.0.1", + "lint-staged": "^15.2.2", + "mocha": "^10.3.0", + "module-from-string": "^3.3.0", + "node-fetch": "^3.3.2", + "nyc": "^15.1.0", + "prettier": "3.0.3", + "re2": "^1.20.9", + "rollup": "^2.79.1", + "rollup-plugin-terser": "^7.0.2", + "ts-node": "^10.9.2", + "tsify": "^5.0.4", + "typescript": "5.3.3", + "uri-js": "^4.4.1" + }, + "collective": { + "type": "opencollective", + "url": "https://opencollective.com/ajv" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + }, + "prettier": "@ajv-validator/config/prettierrc.json", + "husky": { + "hooks": { + "pre-commit": "lint-staged && npm test" + } + }, + "lint-staged": { + "*.{json,yaml,js,ts}": "prettier --write" + } +} diff --git a/node_modules/ansi-regex/index.d.ts b/node_modules/ansi-regex/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d562e9ca9587112d974ee108bdb884b33c5546e --- /dev/null +++ b/node_modules/ansi-regex/index.d.ts @@ -0,0 +1,33 @@ +export type Options = { + /** + Match only the first ANSI escape. + + @default false + */ + readonly onlyFirst: boolean; +}; + +/** +Regular expression for matching ANSI escape codes. + +@example +``` +import ansiRegex from 'ansi-regex'; + +ansiRegex().test('\u001B[4mcake\u001B[0m'); +//=> true + +ansiRegex().test('cake'); +//=> false + +'\u001B[4mcake\u001B[0m'.match(ansiRegex()); +//=> ['\u001B[4m', '\u001B[0m'] + +'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); +//=> ['\u001B[4m'] + +'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); +//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] +``` +*/ +export default function ansiRegex(options?: Options): RegExp; diff --git a/node_modules/ansi-regex/index.js b/node_modules/ansi-regex/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2cc5ca2419f1b2f191826b449192354ad5c4a065 --- /dev/null +++ b/node_modules/ansi-regex/index.js @@ -0,0 +1,14 @@ +export default function ansiRegex({onlyFirst = false} = {}) { + // Valid string terminator sequences are BEL, ESC\, and 0x9c + const ST = '(?:\\u0007|\\u001B\\u005C|\\u009C)'; + + // OSC sequences only: ESC ] ... ST (non-greedy until the first ST) + const osc = `(?:\\u001B\\][\\s\\S]*?${ST})`; + + // CSI and related: ESC/C1, optional intermediates, optional params (supports ; and :) then final byte + const csi = '[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]'; + + const pattern = `${osc}|${csi}`; + + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +} diff --git a/node_modules/ansi-regex/license b/node_modules/ansi-regex/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/node_modules/ansi-regex/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/ansi-regex/package.json b/node_modules/ansi-regex/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2efe9ebbe66be160939aa5e4a1c4e4ada16cad6c --- /dev/null +++ b/node_modules/ansi-regex/package.json @@ -0,0 +1,61 @@ +{ + "name": "ansi-regex", + "version": "6.2.2", + "description": "Regular expression for matching ANSI escape codes", + "license": "MIT", + "repository": "chalk/ansi-regex", + "funding": "https://github.com/chalk/ansi-regex?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": "./index.js", + "types": "./index.d.ts", + "sideEffects": false, + "engines": { + "node": ">=12" + }, + "scripts": { + "test": "xo && ava && tsd", + "view-supported": "node fixtures/view-codes.js" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "text", + "regex", + "regexp", + "re", + "match", + "test", + "find", + "pattern" + ], + "devDependencies": { + "ansi-escapes": "^5.0.0", + "ava": "^3.15.0", + "tsd": "^0.21.0", + "xo": "^0.54.2" + } +} diff --git a/node_modules/ansi-regex/readme.md b/node_modules/ansi-regex/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..4d3c415a4bec63c03f5f8c158c79c388a4764467 --- /dev/null +++ b/node_modules/ansi-regex/readme.md @@ -0,0 +1,66 @@ +# ansi-regex + +> Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) + +## Install + +```sh +npm install ansi-regex +``` + +## Usage + +```js +import ansiRegex from 'ansi-regex'; + +ansiRegex().test('\u001B[4mcake\u001B[0m'); +//=> true + +ansiRegex().test('cake'); +//=> false + +'\u001B[4mcake\u001B[0m'.match(ansiRegex()); +//=> ['\u001B[4m', '\u001B[0m'] + +'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); +//=> ['\u001B[4m'] + +'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); +//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] +``` + +## API + +### ansiRegex(options?) + +Returns a regex for matching ANSI escape codes. + +#### options + +Type: `object` + +##### onlyFirst + +Type: `boolean`\ +Default: `false` *(Matches any ANSI escape codes in a string)* + +Match only the first ANSI escape. + +## Important + +If you run the regex against untrusted user input in a server context, you should [give it a timeout](https://github.com/sindresorhus/super-regex). + +**I do not consider [ReDoS](https://blog.yossarian.net/2022/12/28/ReDoS-vulnerabilities-and-misaligned-incentives) a valid vulnerability for this package.** + +## FAQ + +### Why do you test for codes not in the ECMA 48 standard? + +Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them. + +On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out. + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) diff --git a/node_modules/ansi-styles/index.d.ts b/node_modules/ansi-styles/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee8bc27ca190cc9cc63cb4f596ab550ab09a13b4 --- /dev/null +++ b/node_modules/ansi-styles/index.d.ts @@ -0,0 +1,236 @@ +export type CSPair = { // eslint-disable-line @typescript-eslint/naming-convention + /** + The ANSI terminal control sequence for starting this style. + */ + readonly open: string; + + /** + The ANSI terminal control sequence for ending this style. + */ + readonly close: string; +}; + +export type ColorBase = { + /** + The ANSI terminal control sequence for ending this color. + */ + readonly close: string; + + ansi(code: number): string; + + ansi256(code: number): string; + + ansi16m(red: number, green: number, blue: number): string; +}; + +export type Modifier = { + /** + Resets the current color chain. + */ + readonly reset: CSPair; + + /** + Make text bold. + */ + readonly bold: CSPair; + + /** + Emitting only a small amount of light. + */ + readonly dim: CSPair; + + /** + Make text italic. (Not widely supported) + */ + readonly italic: CSPair; + + /** + Make text underline. (Not widely supported) + */ + readonly underline: CSPair; + + /** + Make text overline. + + Supported on VTE-based terminals, the GNOME terminal, mintty, and Git Bash. + */ + readonly overline: CSPair; + + /** + Inverse background and foreground colors. + */ + readonly inverse: CSPair; + + /** + Prints the text, but makes it invisible. + */ + readonly hidden: CSPair; + + /** + Puts a horizontal line through the center of the text. (Not widely supported) + */ + readonly strikethrough: CSPair; +}; + +export type ForegroundColor = { + readonly black: CSPair; + readonly red: CSPair; + readonly green: CSPair; + readonly yellow: CSPair; + readonly blue: CSPair; + readonly cyan: CSPair; + readonly magenta: CSPair; + readonly white: CSPair; + + /** + Alias for `blackBright`. + */ + readonly gray: CSPair; + + /** + Alias for `blackBright`. + */ + readonly grey: CSPair; + + readonly blackBright: CSPair; + readonly redBright: CSPair; + readonly greenBright: CSPair; + readonly yellowBright: CSPair; + readonly blueBright: CSPair; + readonly cyanBright: CSPair; + readonly magentaBright: CSPair; + readonly whiteBright: CSPair; +}; + +export type BackgroundColor = { + readonly bgBlack: CSPair; + readonly bgRed: CSPair; + readonly bgGreen: CSPair; + readonly bgYellow: CSPair; + readonly bgBlue: CSPair; + readonly bgCyan: CSPair; + readonly bgMagenta: CSPair; + readonly bgWhite: CSPair; + + /** + Alias for `bgBlackBright`. + */ + readonly bgGray: CSPair; + + /** + Alias for `bgBlackBright`. + */ + readonly bgGrey: CSPair; + + readonly bgBlackBright: CSPair; + readonly bgRedBright: CSPair; + readonly bgGreenBright: CSPair; + readonly bgYellowBright: CSPair; + readonly bgBlueBright: CSPair; + readonly bgCyanBright: CSPair; + readonly bgMagentaBright: CSPair; + readonly bgWhiteBright: CSPair; +}; + +export type ConvertColor = { + /** + Convert from the RGB color space to the ANSI 256 color space. + + @param red - (`0...255`) + @param green - (`0...255`) + @param blue - (`0...255`) + */ + rgbToAnsi256(red: number, green: number, blue: number): number; + + /** + Convert from the RGB HEX color space to the RGB color space. + + @param hex - A hexadecimal string containing RGB data. + */ + hexToRgb(hex: string): [red: number, green: number, blue: number]; + + /** + Convert from the RGB HEX color space to the ANSI 256 color space. + + @param hex - A hexadecimal string containing RGB data. + */ + hexToAnsi256(hex: string): number; + + /** + Convert from the ANSI 256 color space to the ANSI 16 color space. + + @param code - A number representing the ANSI 256 color. + */ + ansi256ToAnsi(code: number): number; + + /** + Convert from the RGB color space to the ANSI 16 color space. + + @param red - (`0...255`) + @param green - (`0...255`) + @param blue - (`0...255`) + */ + rgbToAnsi(red: number, green: number, blue: number): number; + + /** + Convert from the RGB HEX color space to the ANSI 16 color space. + + @param hex - A hexadecimal string containing RGB data. + */ + hexToAnsi(hex: string): number; +}; + +/** +Basic modifier names. +*/ +export type ModifierName = keyof Modifier; + +/** +Basic foreground color names. + +[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) +*/ +export type ForegroundColorName = keyof ForegroundColor; + +/** +Basic background color names. + +[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) +*/ +export type BackgroundColorName = keyof BackgroundColor; + +/** +Basic color names. The combination of foreground and background color names. + +[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) +*/ +export type ColorName = ForegroundColorName | BackgroundColorName; + +/** +Basic modifier names. +*/ +export const modifierNames: readonly ModifierName[]; + +/** +Basic foreground color names. +*/ +export const foregroundColorNames: readonly ForegroundColorName[]; + +/** +Basic background color names. +*/ +export const backgroundColorNames: readonly BackgroundColorName[]; + +/* +Basic color names. The combination of foreground and background color names. +*/ +export const colorNames: readonly ColorName[]; + +declare const ansiStyles: { + readonly modifier: Modifier; + readonly color: ColorBase & ForegroundColor; + readonly bgColor: ColorBase & BackgroundColor; + readonly codes: ReadonlyMap; +} & ForegroundColor & BackgroundColor & Modifier & ConvertColor; + +export default ansiStyles; diff --git a/node_modules/ansi-styles/index.js b/node_modules/ansi-styles/index.js new file mode 100644 index 0000000000000000000000000000000000000000..eaa7bed6cb1ed94a4eab0bf2ef6b61d69057998a --- /dev/null +++ b/node_modules/ansi-styles/index.js @@ -0,0 +1,223 @@ +const ANSI_BACKGROUND_OFFSET = 10; + +const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`; + +const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; + +const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; + +const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + overline: [53, 55], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + + // Bright color + blackBright: [90, 39], + gray: [90, 39], // Alias of `blackBright` + grey: [90, 39], // Alias of `blackBright` + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39], + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgGray: [100, 49], // Alias of `bgBlackBright` + bgGrey: [100, 49], // Alias of `bgBlackBright` + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49], + }, +}; + +export const modifierNames = Object.keys(styles.modifier); +export const foregroundColorNames = Object.keys(styles.color); +export const backgroundColorNames = Object.keys(styles.bgColor); +export const colorNames = [...foregroundColorNames, ...backgroundColorNames]; + +function assembleStyles() { + const codes = new Map(); + + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m`, + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false, + }); + } + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false, + }); + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi = wrapAnsi16(); + styles.color.ansi256 = wrapAnsi256(); + styles.color.ansi16m = wrapAnsi16m(); + styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); + styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); + styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); + + // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js + Object.defineProperties(styles, { + rgbToAnsi256: { + value(red, green, blue) { + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (red === green && green === blue) { + if (red < 8) { + return 16; + } + + if (red > 248) { + return 231; + } + + return Math.round(((red - 8) / 247) * 24) + 232; + } + + return 16 + + (36 * Math.round(red / 255 * 5)) + + (6 * Math.round(green / 255 * 5)) + + Math.round(blue / 255 * 5); + }, + enumerable: false, + }, + hexToRgb: { + value(hex) { + const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); + if (!matches) { + return [0, 0, 0]; + } + + let [colorString] = matches; + + if (colorString.length === 3) { + colorString = [...colorString].map(character => character + character).join(''); + } + + const integer = Number.parseInt(colorString, 16); + + return [ + /* eslint-disable no-bitwise */ + (integer >> 16) & 0xFF, + (integer >> 8) & 0xFF, + integer & 0xFF, + /* eslint-enable no-bitwise */ + ]; + }, + enumerable: false, + }, + hexToAnsi256: { + value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), + enumerable: false, + }, + ansi256ToAnsi: { + value(code) { + if (code < 8) { + return 30 + code; + } + + if (code < 16) { + return 90 + (code - 8); + } + + let red; + let green; + let blue; + + if (code >= 232) { + red = (((code - 232) * 10) + 8) / 255; + green = red; + blue = red; + } else { + code -= 16; + + const remainder = code % 36; + + red = Math.floor(code / 36) / 5; + green = Math.floor(remainder / 6) / 5; + blue = (remainder % 6) / 5; + } + + const value = Math.max(red, green, blue) * 2; + + if (value === 0) { + return 30; + } + + // eslint-disable-next-line no-bitwise + let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red)); + + if (value === 2) { + result += 60; + } + + return result; + }, + enumerable: false, + }, + rgbToAnsi: { + value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), + enumerable: false, + }, + hexToAnsi: { + value: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), + enumerable: false, + }, + }); + + return styles; +} + +const ansiStyles = assembleStyles(); + +export default ansiStyles; diff --git a/node_modules/ansi-styles/license b/node_modules/ansi-styles/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/node_modules/ansi-styles/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/ansi-styles/package.json b/node_modules/ansi-styles/package.json new file mode 100644 index 0000000000000000000000000000000000000000..16b508f0f3a047da67543efd7966bfdda9598391 --- /dev/null +++ b/node_modules/ansi-styles/package.json @@ -0,0 +1,54 @@ +{ + "name": "ansi-styles", + "version": "6.2.3", + "description": "ANSI escape codes for styling strings in the terminal", + "license": "MIT", + "repository": "chalk/ansi-styles", + "funding": "https://github.com/chalk/ansi-styles?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": "./index.js", + "engines": { + "node": ">=12" + }, + "scripts": { + "test": "xo && ava && tsd", + "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "devDependencies": { + "ava": "^6.1.3", + "svg-term-cli": "^2.1.1", + "tsd": "^0.31.1", + "xo": "^0.58.0" + } +} diff --git a/node_modules/ansi-styles/readme.md b/node_modules/ansi-styles/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..6d04183f0c638ec7ffa2414bac93445cc30f9024 --- /dev/null +++ b/node_modules/ansi-styles/readme.md @@ -0,0 +1,173 @@ +# ansi-styles + +> [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal + +You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. + +![](screenshot.png) + +## Install + +```sh +npm install ansi-styles +``` + +## Usage + +```js +import styles from 'ansi-styles'; + +console.log(`${styles.green.open}Hello world!${styles.green.close}`); + + +// Color conversion between 256/truecolor +// NOTE: When converting from truecolor to 256 colors, the original color +// may be degraded to fit the new color palette. This means terminals +// that do not support 16 million colors will best-match the +// original color. +console.log(`${styles.color.ansi(styles.rgbToAnsi(199, 20, 250))}Hello World${styles.color.close}`) +console.log(`${styles.color.ansi256(styles.rgbToAnsi256(199, 20, 250))}Hello World${styles.color.close}`) +console.log(`${styles.color.ansi16m(...styles.hexToRgb('#abcdef'))}Hello World${styles.color.close}`) +``` + +## API + +### `open` and `close` + +Each style has an `open` and `close` property. + +### `modifierNames`, `foregroundColorNames`, `backgroundColorNames`, and `colorNames` + +All supported style strings are exposed as an array of strings for convenience. `colorNames` is the combination of `foregroundColorNames` and `backgroundColorNames`. + +This can be useful if you need to validate input: + +```js +import {modifierNames, foregroundColorNames} from 'ansi-styles'; + +console.log(modifierNames.includes('bold')); +//=> true + +console.log(foregroundColorNames.includes('pink')); +//=> false +``` + +## Styles + +### Modifiers + +- `reset` +- `bold` +- `dim` +- `italic` *(Not widely supported)* +- `underline` +- `overline` *Supported on VTE-based terminals, the GNOME terminal, mintty, and Git Bash.* +- `inverse` +- `hidden` +- `strikethrough` *(Not widely supported)* + +### Colors + +- `black` +- `red` +- `green` +- `yellow` +- `blue` +- `magenta` +- `cyan` +- `white` +- `blackBright` (alias: `gray`, `grey`) +- `redBright` +- `greenBright` +- `yellowBright` +- `blueBright` +- `magentaBright` +- `cyanBright` +- `whiteBright` + +### Background colors + +- `bgBlack` +- `bgRed` +- `bgGreen` +- `bgYellow` +- `bgBlue` +- `bgMagenta` +- `bgCyan` +- `bgWhite` +- `bgBlackBright` (alias: `bgGray`, `bgGrey`) +- `bgRedBright` +- `bgGreenBright` +- `bgYellowBright` +- `bgBlueBright` +- `bgMagentaBright` +- `bgCyanBright` +- `bgWhiteBright` + +## Advanced usage + +By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. + +- `styles.modifier` +- `styles.color` +- `styles.bgColor` + +###### Example + +```js +import styles from 'ansi-styles'; + +console.log(styles.color.green.open); +``` + +Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `styles.codes`, which returns a `Map` with the open codes as keys and close codes as values. + +###### Example + +```js +import styles from 'ansi-styles'; + +console.log(styles.codes.get(36)); +//=> 39 +``` + +## 16 / 256 / 16 million (TrueColor) support + +`ansi-styles` allows converting between various color formats and ANSI escapes, with support for 16, 256 and [16 million colors](https://gist.github.com/XVilka/8346728). + +The following color spaces are supported: + +- `rgb` +- `hex` +- `ansi256` +- `ansi` + +To use these, call the associated conversion function with the intended output, for example: + +```js +import styles from 'ansi-styles'; + +styles.color.ansi(styles.rgbToAnsi(100, 200, 15)); // RGB to 16 color ansi foreground code +styles.bgColor.ansi(styles.hexToAnsi('#C0FFEE')); // HEX to 16 color ansi foreground code + +styles.color.ansi256(styles.rgbToAnsi256(100, 200, 15)); // RGB to 256 color ansi foreground code +styles.bgColor.ansi256(styles.hexToAnsi256('#C0FFEE')); // HEX to 256 color ansi foreground code + +styles.color.ansi16m(100, 200, 15); // RGB to 16 million color foreground code +styles.bgColor.ansi16m(...styles.hexToRgb('#C0FFEE')); // Hex (RGB) to 16 million color foreground code +``` + +## Related + +- [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + +## For enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of `ansi-styles` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-ansi-styles?utm_source=npm-ansi-styles&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/ansis/LICENSE b/node_modules/ansis/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..38d9537c4b9e3e6df905ea8e35dcb097f889a55f --- /dev/null +++ b/node_modules/ansis/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2026, webdiscus + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. \ No newline at end of file diff --git a/node_modules/ansis/README.md b/node_modules/ansis/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d83be56babc3d6c8ab9dff220b2f360fbc255b7a --- /dev/null +++ b/node_modules/ansis/README.md @@ -0,0 +1,5 @@ +# Ansis + +ANSI color library - [Docs](../../) + +![](docs/n.png) \ No newline at end of file diff --git a/node_modules/ansis/index.cjs b/node_modules/ansis/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..6002b7489a7dca51590e1f2059aab6476a92c2aa --- /dev/null +++ b/node_modules/ansis/index.cjs @@ -0,0 +1 @@ +let e,{defineProperty:r,getPrototypeOf:t,setPrototypeOf:n,create:o,keys:l}=Object,i="",{round:f,max:s}=Math,u=e=>{let r=/([a-f\d]{3,6})/i.exec(e)?.[0],t=r?.length,n="0x"+(6^t?3^t?"0":r[0]+r[0]+r[1]+r[1]+r[2]+r[2]:r)|0;return[n>>16,n>>8&255,255&n]},a=e=>{if(8>e)return 30+e;if(16>e)return 82+e;if(e>231)return e>243?37:30;let r=(e-=16)%36,t=e/36|0,n=r/6|0,o=r%6;return 30+(t>2|(n>2)<<1|(o>2)<<2)+(s(t,n,o)>4?60:0)},c={open:i,close:i},g=(e,{open:r="",close:o="",f:l})=>{let f=(e.open||i)+r,s=o+(e.close||i),u=(e,...t)=>{if(!e){if(!o)return r;if((e??i)===i)return i}let n,a=l?l(e,...t):e.raw?String.raw({raw:e},...t):i+e,c=u;if(a.includes(""))for(;c=c.p;){let{t:e,o:r}=c,t=r.length,o=i,l=0;if(t)for(;~(n=a.indexOf(r,l));l=n+t)o+=a.slice(l,n)+e;a=o+a.slice(l)}return f+(a.includes("\n")?a.replace(/(\r?\n)/g,s+"$1"+f):a)+s};return n(u,t(e)).p={t:r,o,p:e.p},u.open=f,u.close=s,u};const d=new function t(s=globalThis){let d="number"==typeof s?s:(r=>{let t=r.process??{},n=t.argv??[],o=t.env??{},i=0;try{i=((r,t,n)=>(e=t.TERM,{"24bit":3,truecolor:3,ansi256:2,ansi:1}[t.COLORTERM]||(t.CI?/,GITHUB/.test(n)?3:1:(t.PM2_HOME||/edge/.test(t.NEXT_RUNTIME)||r.stdout?.isTTY)&&"dumb"!==e?"win32"===r.platform?3:/-256/.test(e)?2:1:0)))(t,o,","+l(o).join(","))}catch(e){o={}}let f,s=i||1,u="FORCE_COLOR",a={false:0,0:0,1:1,2:2,3:3}[o[u]]??s,c=-1;for(f of n)/^--color=?(true|always)?$/.test(f)&&(c=s),/^--(no-color|color=(false|never))$/.test(f)&&(c=0);return r.window?.chrome?3:u in o?a:~c?c:o.NO_COLOR?0:i})(s),b={},p={Ansis:t,level:d,isSupported:()=>m,strip:e=>e.replace(/][^]*|[›][[()#;?]*(?:\d+(?:;\d*)*)?[\dA-ORZcf-nqry=><]/g,i),extend(e){for(let r in e){let t=e[r];"s"===(typeof t)[0]&&(h(w(r),A(...u(t))),t=P(...u(t))),h(r,t)}return n(p,o({},b))}},h=(e,t)=>{b[e]={get(){return r(this,e,{value:t.call?(...e)=>g(this,t(...e)):g(this,t)})[e]}}},y=1^d,$=d>2,m=d>0,O=(e,r)=>m?{open:`[${e}m`,close:r?`[${r}m`:i}:c,w=e=>"bg"+e[0].toUpperCase()+e.slice(1),v=e=>r=>e(...u(r)),x=(e,r)=>(t,n,o)=>O(`${e}8;2;${t};${n};${o}`,r),_=e=>(r,t,n)=>e(((e,r,t)=>e^r|r^t?16+36*f(e/51)+6*f(r/51)+f(t/51):8>e?16:e>248?231:f(24*(e-8)/247)+232)(r,t,n)),k=e=>O(y?"38;5;"+e:a(e),39),R=e=>O(y?"48;5;"+e:a(e)+10,49),P=$?x(3,39):_(k),A=$?x(4,49):_(R),B={fg:k,bg:R,rgb:P,bgRgb:A,hex:v(P),bgHex:v(A),visible:c,reset:O(0,i),bold:O(1,22),dim:O(2,22),italic:O(3,23),underline:O(4,24),inverse:O(7,27),hidden:O(8,28),strikethrough:O(9,29),link:{f:(e,r=e)=>m?`]8;;${e}${r}]8;;`:r!=e?r+` (​${e}​)`:e}},C=(e,r)=>{B[e]=O(r,39),B[w(e)]=O(r+10,49)};return"gray,black,red,green,yellow,blue,magenta,cyan,white".split(",").map(((e,r)=>{r?C(e+"Bright",89+r):r=61,C(e,29+r)})),p.extend(B)};module.exports=d.default=d; diff --git a/node_modules/ansis/index.d.ts b/node_modules/ansis/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..00032595a1b6fa88d7ff3ad87a93a8e20d4de456 --- /dev/null +++ b/node_modules/ansis/index.d.ts @@ -0,0 +1 @@ +type N=number;type S=string;type C='red'|'green'|'yellow'|'blue'|'magenta'|'cyan'|'white';type H=`${C}Bright`;export type AnsiColors='black'|'gray'|C|H|`bg${'Black'|'Gray'|Capitalize}`;export type AnsiStyles='reset'|'inverse'|'hidden'|'visible'|'bold'|'dim'|'italic'|'underline'|'strikethrough';type Q=(n:N)=>A;type L=(s:S)=>A;type R=(r:N,g:N,b:N)=>A;type W=(text:S,url?:S)=>S;type A=Ansis;type Ansis={level:N;open:S;close:S;(v:unknown):S;(s:TemplateStringsArray,...v:any[]):S;fg:Q;bg:Q;rgb:R;bgRgb:R;hex:L;bgHex:L;link:W;isSupported():boolean;strip(s:S):S;extend(c:Record):A&Record}`,A>}&{[K in AnsiStyles|AnsiColors]:A};declare const Ansis:new (o?:N|object)=>A,a:A,fg:Q,rgb:R,hex:L,link:W;export{a as default,Ansis,fg,fg as bg,rgb,rgb as bgRgb,hex,hex as bgHex,link,a as reset,a as inverse,a as hidden,a as visible,a as bold,a as dim,a as italic,a as underline,a as strikethrough,a as black,a as red,a as green,a as yellow,a as blue,a as magenta,a as cyan,a as white,a as gray,a as redBright,a as greenBright,a as yellowBright,a as blueBright,a as magentaBright,a as cyanBright,a as whiteBright,a as bgBlack,a as bgRed,a as bgGreen,a as bgYellow,a as bgBlue,a as bgMagenta,a as bgCyan,a as bgWhite,a as bgGray,a as bgRedBright,a as bgGreenBright,a as bgYellowBright,a as bgBlueBright,a as bgMagentaBright,a as bgCyanBright,a as bgWhiteBright}; \ No newline at end of file diff --git a/node_modules/ansis/index.mjs b/node_modules/ansis/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cb4b7467813a46844503f5087e3827874981496d --- /dev/null +++ b/node_modules/ansis/index.mjs @@ -0,0 +1 @@ +import a from"./index.cjs";export default a;export const{Ansis,fg,bg,rgb,bgRgb,hex,bgHex,reset,inverse,hidden,visible,link,bold,dim,italic,underline,strikethrough,black,red,green,yellow,blue,magenta,cyan,white,gray,redBright,greenBright,yellowBright,blueBright,magentaBright,cyanBright,whiteBright,bgBlack,bgRed,bgGreen,bgYellow,bgBlue,bgMagenta,bgCyan,bgWhite,bgGray,bgRedBright,bgGreenBright,bgYellowBright,bgBlueBright,bgMagentaBright,bgCyanBright,bgWhiteBright}=a; \ No newline at end of file diff --git a/node_modules/ansis/package.json b/node_modules/ansis/package.json new file mode 100644 index 0000000000000000000000000000000000000000..63a7bd91f6c69cc341d4a92ceca875f89fec1ebc --- /dev/null +++ b/node_modules/ansis/package.json @@ -0,0 +1,19 @@ +{ +"name":"ansis", +"version":"4.3.1", +"description":"ANSI color lib", +"keywords":["ansi","colors","cli"], +"license":"ISC", +"author":"webdiscus", +"repository":"webdiscus/ansis", +"type":"module", +"exports":{ + ".":{ + "types":"./index.d.ts", + "require":"./index.cjs", + "import":"./index.mjs" + } +}, +"sideEffects":false, +"engines":{"node":">=14"} +} \ No newline at end of file diff --git a/node_modules/any-base/LICENSE b/node_modules/any-base/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a70ce0cea4ae049d56cfb67a6f4e975d9bb666e7 --- /dev/null +++ b/node_modules/any-base/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Kamil Harasimowicz and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/node_modules/any-base/README.md b/node_modules/any-base/README.md new file mode 100644 index 0000000000000000000000000000000000000000..98887d746555d6a5d278c968f34ecd0961ab70a9 --- /dev/null +++ b/node_modules/any-base/README.md @@ -0,0 +1,55 @@ +# README # + +The library allows you to convert any large numbers in any number base to another number base. The base is determined by specifying the alphabet. So is full freedom + +[![NPM](https://nodei.co/npm/any-base.png?downloads=true&stars=true)](https://nodei.co/npm/any-base/) + +## Installation ## + +``` +npm install any-base --save +``` + +## API ## + +### AnyBase() ### + +``` +converterFunction = anyBase(sourceAlphabet, destinationAlphabet); +``` + +#### Parameters #### + +* {String} __sourceAlphabet__ digits from smallest to the largest +* {String} __destinationAlphabet__ digits from smallest to the largest + +#### Return Values #### + +Returns __function__ that converts the number of source base to the destination + +### Convert() ### + +``` +converterFunction(number) +``` + +#### Parameters #### + +* {String} __number__ number of source base + +#### Return Values #### + +Returns number of destonation base + +## Example ## + +```js +var anyBase = require('any-base'), +dec2hex = anyBase(anyBase.DEC, anyBase.HEX), +shortId = anyBase(anyBase.DEC, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-+!@#$^'), +longId = anyBase('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-+!@#$^', anyBase.DEC); + +dec2hex('123456'); // return: '1E240' +shortId('1234567890'); // return: 'PtmIa' +longId('PtmIa'); // return: '1234567890' +``` diff --git a/node_modules/any-base/index.js b/node_modules/any-base/index.js new file mode 100644 index 0000000000000000000000000000000000000000..17c6694b85e5c6a7c53c7ff8a266a12580aa385e --- /dev/null +++ b/node_modules/any-base/index.js @@ -0,0 +1,30 @@ +var Converter = require('./src/converter'); + +/** + * Function get source and destination alphabet and return convert function + * + * @param {string|Array} srcAlphabet + * @param {string|Array} dstAlphabet + * + * @returns {function(number|Array)} + */ +function anyBase(srcAlphabet, dstAlphabet) { + var converter = new Converter(srcAlphabet, dstAlphabet); + /** + * Convert function + * + * @param {string|Array} number + * + * @return {string|Array} number + */ + return function (number) { + return converter.convert(number); + } +}; + +anyBase.BIN = '01'; +anyBase.OCT = '01234567'; +anyBase.DEC = '0123456789'; +anyBase.HEX = '0123456789abcdef'; + +module.exports = anyBase; \ No newline at end of file diff --git a/node_modules/any-base/package.json b/node_modules/any-base/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1ca20b0af45791d4f4f92d9be49d798f50a60526 --- /dev/null +++ b/node_modules/any-base/package.json @@ -0,0 +1,40 @@ +{ + "name": "any-base", + "version": "1.1.0", + "description": "Converter from any base to other any base", + "main": "index.js", + "scripts": { + "start": "./node_modules/.bin/watchify . -s AnyBase -o dist/any-base.js -v -d", + "build": "./node_modules/.bin/browserify . -s AnyBase | ./node_modules/.bin/uglifyjs -cm > dist/any-base.min.js", + "test": "node tests/test.js" + }, + "keywords": [ + "number", + "convert", + "base", + "alphabet", + "short number", + "long numbers", + "dec", + "hex", + "bin", + "oct", + "any" + ], + "repository": { + "type": "git", + "url": "https://github.com/HarasimowiczKamil/any-base.git" + }, + "author": { + "name": "Kamil Harasimowicz", + "email": "mifczu@gmail.com" + }, + "license": "MIT", + "dependencies": {}, + "devDependencies": { + "browserify": "^13.1.1", + "punycode": "^2.1.0", + "uglify-js": "^2.7.4", + "watchify": "^3.7.0" + } +} diff --git a/node_modules/any-base/src/converter.js b/node_modules/any-base/src/converter.js new file mode 100644 index 0000000000000000000000000000000000000000..b2b07f3fbd3496fa766570e17cc2b842714e386d --- /dev/null +++ b/node_modules/any-base/src/converter.js @@ -0,0 +1,80 @@ +'use strict'; + +/** + * Converter + * + * @param {string|Array} srcAlphabet + * @param {string|Array} dstAlphabet + * @constructor + */ +function Converter(srcAlphabet, dstAlphabet) { + if (!srcAlphabet || !dstAlphabet || !srcAlphabet.length || !dstAlphabet.length) { + throw new Error('Bad alphabet'); + } + this.srcAlphabet = srcAlphabet; + this.dstAlphabet = dstAlphabet; +} + +/** + * Convert number from source alphabet to destination alphabet + * + * @param {string|Array} number - number represented as a string or array of points + * + * @returns {string|Array} + */ +Converter.prototype.convert = function(number) { + var i, divide, newlen, + numberMap = {}, + fromBase = this.srcAlphabet.length, + toBase = this.dstAlphabet.length, + length = number.length, + result = typeof number === 'string' ? '' : []; + + if (!this.isValid(number)) { + throw new Error('Number "' + number + '" contains of non-alphabetic digits (' + this.srcAlphabet + ')'); + } + + if (this.srcAlphabet === this.dstAlphabet) { + return number; + } + + for (i = 0; i < length; i++) { + numberMap[i] = this.srcAlphabet.indexOf(number[i]); + } + do { + divide = 0; + newlen = 0; + for (i = 0; i < length; i++) { + divide = divide * fromBase + numberMap[i]; + if (divide >= toBase) { + numberMap[newlen++] = parseInt(divide / toBase, 10); + divide = divide % toBase; + } else if (newlen > 0) { + numberMap[newlen++] = 0; + } + } + length = newlen; + result = this.dstAlphabet.slice(divide, divide + 1).concat(result); + } while (newlen !== 0); + + return result; +}; + +/** + * Valid number with source alphabet + * + * @param {number} number + * + * @returns {boolean} + */ +Converter.prototype.isValid = function(number) { + var i = 0; + for (; i < number.length; ++i) { + if (this.srcAlphabet.indexOf(number[i]) === -1) { + return false; + } + } + return true; +}; + +module.exports = Converter; \ No newline at end of file diff --git a/node_modules/any-promise/.jshintrc b/node_modules/any-promise/.jshintrc new file mode 100644 index 0000000000000000000000000000000000000000..979105e9116a60f71f5416bfe5fe432dcbdfde91 --- /dev/null +++ b/node_modules/any-promise/.jshintrc @@ -0,0 +1,4 @@ +{ + "node":true, + "strict":true +} diff --git a/node_modules/any-promise/.npmignore b/node_modules/any-promise/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..1354abc0270ba8c759e4df7c401ce10cb014d58b --- /dev/null +++ b/node_modules/any-promise/.npmignore @@ -0,0 +1,7 @@ +.git* +test/ +test-browser/ +build/ +.travis.yml +*.swp +Makefile diff --git a/node_modules/any-promise/LICENSE b/node_modules/any-promise/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9187fe5d7293980d23902787dd6438a56e99dc0b --- /dev/null +++ b/node_modules/any-promise/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2014-2016 Kevin Beaty + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/any-promise/README.md b/node_modules/any-promise/README.md new file mode 100644 index 0000000000000000000000000000000000000000..174bea4aeb0bd0a7b7af83a9991195bb9b887c97 --- /dev/null +++ b/node_modules/any-promise/README.md @@ -0,0 +1,161 @@ +## Any Promise + +[![Build Status](https://secure.travis-ci.org/kevinbeaty/any-promise.svg)](http://travis-ci.org/kevinbeaty/any-promise) + +Let your library support any ES 2015 (ES6) compatible `Promise` and leave the choice to application authors. The application can *optionally* register its preferred `Promise` implementation and it will be exported when requiring `any-promise` from library code. + +If no preference is registered, defaults to the global `Promise` for newer Node.js versions. The browser version defaults to the window `Promise`, so polyfill or register as necessary. + +### Usage with global Promise: + +Assuming the global `Promise` is the desired implementation: + +```bash +# Install any libraries depending on any-promise +$ npm install mz +``` + +The installed libraries will use global Promise by default. + +```js +// in library +var Promise = require('any-promise') // the global Promise + +function promiseReturningFunction(){ + return new Promise(function(resolve, reject){...}) +} +``` + +### Usage with registration: + +Assuming `bluebird` is the desired Promise implementation: + +```bash +# Install preferred promise library +$ npm install bluebird +# Install any-promise to allow registration +$ npm install any-promise +# Install any libraries you would like to use depending on any-promise +$ npm install mz +``` + +Register your preference in the application entry point before any other `require` of packages that load `any-promise`: + +```javascript +// top of application index.js or other entry point +require('any-promise/register/bluebird') + +// -or- Equivalent to above, but allows customization of Promise library +require('any-promise/register')('bluebird', {Promise: require('bluebird')}) +``` + +Now that the implementation is registered, you can use any package depending on `any-promise`: + + +```javascript +var fsp = require('mz/fs') // mz/fs will use registered bluebird promises +var Promise = require('any-promise') // the registered bluebird promise +``` + +It is safe to call `register` multiple times, but it must always be with the same implementation. + +Again, registration is *optional*. It should only be called by the application user if overriding the global `Promise` implementation is desired. + +### Optional Application Registration + +As an application author, you can *optionally* register a preferred `Promise` implementation on application startup (before any call to `require('any-promise')`: + +You must register your preference before any call to `require('any-promise')` (by you or required packages), and only one implementation can be registered. Typically, this registration would occur at the top of the application entry point. + + +#### Registration shortcuts + +If you are using a known `Promise` implementation, you can register your preference with a shortcut: + + +```js +require('any-promise/register/bluebird') +// -or- +import 'any-promise/register/q'; +``` + +Shortcut registration is the preferred registration method as it works in the browser and Node.js. It is also convenient for using with `import` and many test runners, that offer a `--require` flag: + +``` +$ ava --require=any-promise/register/bluebird test.js +``` + +Current known implementations include `bluebird`, `q`, `when`, `rsvp`, `es6-promise`, `promise`, `native-promise-only`, `pinkie`, `vow` and `lie`. If you are not using a known implementation, you can use another registration method described below. + + +#### Basic Registration + +As an alternative to registration shortcuts, you can call the `register` function with the preferred `Promise` implementation. The benefit of this approach is that a `Promise` library can be required by name without being a known implementation. This approach does NOT work in the browser. To use `any-promise` in the browser use either registration shortcuts or specify the `Promise` constructor using advanced registration (see below). + +```javascript +require('any-promise/register')('when') +// -or- require('any-promise/register')('any other ES6 compatible library (known or otherwise)') +``` + +This registration method will try to detect the `Promise` constructor from requiring the specified implementation. If you would like to specify your own constructor, see advanced registration. + + +#### Advanced Registration + +To use the browser version, you should either install a polyfill or explicitly register the `Promise` constructor: + +```javascript +require('any-promise/register')('bluebird', {Promise: require('bluebird')}) +``` + +This could also be used for registering a custom `Promise` implementation or subclass. + +Your preference will be registered globally, allowing a single registration even if multiple versions of `any-promise` are installed in the NPM dependency tree or are using multiple bundled JavaScript files in the browser. You can bypass this global registration in options: + + +```javascript +require('../register')('es6-promise', {Promise: require('es6-promise').Promise, global: false}) +``` + +### Library Usage + +To use any `Promise` constructor, simply require it: + +```javascript +var Promise = require('any-promise'); + +return Promise + .all([xf, f, init, coll]) + .then(fn); + + +return new Promise(function(resolve, reject){ + try { + resolve(item); + } catch(e){ + reject(e); + } +}); + +``` + +Except noted below, libraries using `any-promise` should only use [documented](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) functions as there is no guarantee which implementation will be chosen by the application author. Libraries should never call `register`, only the application user should call if desired. + + +#### Advanced Library Usage + +If your library needs to branch code based on the registered implementation, you can retrieve it using `var impl = require('any-promise/implementation')`, where `impl` will be the package name (`"bluebird"`, `"when"`, etc.) if registered, `"global.Promise"` if using the global version on Node.js, or `"window.Promise"` if using the browser version. You should always include a default case, as there is no guarantee what package may be registered. + + +### Support for old Node.js versions + +Node.js versions prior to `v0.12` may have contained buggy versions of the global `Promise`. For this reason, the global `Promise` is not loaded automatically for these old versions. If using `any-promise` in Node.js versions versions `<= v0.12`, the user should register a desired implementation. + +If an implementation is not registered, `any-promise` will attempt to discover an installed `Promise` implementation. If no implementation can be found, an error will be thrown on `require('any-promise')`. While the auto-discovery usually avoids errors, it is non-deterministic. It is recommended that the user always register a preferred implementation for older Node.js versions. + +This auto-discovery is only available for Node.jS versions prior to `v0.12`. Any newer versions will always default to the global `Promise` implementation. + +### Related + +- [any-observable](https://github.com/sindresorhus/any-observable) - `any-promise` for Observables. + diff --git a/node_modules/any-promise/implementation.d.ts b/node_modules/any-promise/implementation.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c331a56a82482a6d294bc64af3a248748277227d --- /dev/null +++ b/node_modules/any-promise/implementation.d.ts @@ -0,0 +1,3 @@ +declare var implementation: string; + +export = implementation; diff --git a/node_modules/any-promise/implementation.js b/node_modules/any-promise/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..a45ae94dd5fb8bf2a501ffe11aee554527f9ec66 --- /dev/null +++ b/node_modules/any-promise/implementation.js @@ -0,0 +1 @@ +module.exports = require('./register')().implementation diff --git a/node_modules/any-promise/index.d.ts b/node_modules/any-promise/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9f646c5dc4ed09c42210f0f1ce9a970e7dea2788 --- /dev/null +++ b/node_modules/any-promise/index.d.ts @@ -0,0 +1,73 @@ +declare class Promise implements Promise.Thenable { + /** + * If you call resolve in the body of the callback passed to the constructor, + * your promise is fulfilled with result object passed to resolve. + * If you call reject your promise is rejected with the object passed to resolve. + * For consistency and debugging (eg stack traces), obj should be an instanceof Error. + * Any errors thrown in the constructor callback will be implicitly passed to reject(). + */ + constructor (callback: (resolve : (value?: R | Promise.Thenable) => void, reject: (error?: any) => void) => void); + + /** + * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. + * Both callbacks have a single parameter , the fulfillment value or rejection reason. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. + * If an error is thrown in the callback, the returned promise rejects with that error. + * + * @param onFulfilled called when/if "promise" resolves + * @param onRejected called when/if "promise" rejects + */ + then (onFulfilled?: (value: R) => U | Promise.Thenable, onRejected?: (error: any) => U | Promise.Thenable): Promise; + then (onFulfilled?: (value: R) => U | Promise.Thenable, onRejected?: (error: any) => void): Promise; + + /** + * Sugar for promise.then(undefined, onRejected) + * + * @param onRejected called when/if "promise" rejects + */ + catch (onRejected?: (error: any) => U | Promise.Thenable): Promise; + + /** + * Make a new promise from the thenable. + * A thenable is promise-like in as far as it has a "then" method. + */ + static resolve (): Promise; + static resolve (value: R | Promise.Thenable): Promise; + + /** + * Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error + */ + static reject (error: any): Promise; + + /** + * Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects. + * the array passed to all can be a mixture of promise-like objects and other objects. + * The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value. + */ + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable, T6 | Promise.Thenable, T7 | Promise.Thenable, T8 | Promise.Thenable, T9 | Promise.Thenable, T10 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable, T6 | Promise.Thenable, T7 | Promise.Thenable, T8 | Promise.Thenable, T9 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable, T6 | Promise.Thenable, T7 | Promise.Thenable, T8 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable, T6 | Promise.Thenable, T7 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable, T6 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5, T6]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable ]): Promise<[T1, T2, T3, T4]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable]): Promise<[T1, T2, T3]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable]): Promise<[T1, T2]>; + static all (values: [T1 | Promise.Thenable]): Promise<[T1]>; + static all (values: Array>): Promise; + + /** + * Make a Promise that fulfills when any item fulfills, and rejects if any item rejects. + */ + static race (promises: (R | Promise.Thenable)[]): Promise; +} + +declare namespace Promise { + export interface Thenable { + then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; + then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => void): Thenable; + } +} + +export = Promise; diff --git a/node_modules/any-promise/index.js b/node_modules/any-promise/index.js new file mode 100644 index 0000000000000000000000000000000000000000..74b85483df4daea96f991abd720d03b61fffc1ed --- /dev/null +++ b/node_modules/any-promise/index.js @@ -0,0 +1 @@ +module.exports = require('./register')().Promise diff --git a/node_modules/any-promise/loader.js b/node_modules/any-promise/loader.js new file mode 100644 index 0000000000000000000000000000000000000000..e1649142b444df029f2aa89ddf4955a8289dfa6d --- /dev/null +++ b/node_modules/any-promise/loader.js @@ -0,0 +1,78 @@ +"use strict" + // global key for user preferred registration +var REGISTRATION_KEY = '@@any-promise/REGISTRATION', + // Prior registration (preferred or detected) + registered = null + +/** + * Registers the given implementation. An implementation must + * be registered prior to any call to `require("any-promise")`, + * typically on application load. + * + * If called with no arguments, will return registration in + * following priority: + * + * For Node.js: + * + * 1. Previous registration + * 2. global.Promise if node.js version >= 0.12 + * 3. Auto detected promise based on first sucessful require of + * known promise libraries. Note this is a last resort, as the + * loaded library is non-deterministic. node.js >= 0.12 will + * always use global.Promise over this priority list. + * 4. Throws error. + * + * For Browser: + * + * 1. Previous registration + * 2. window.Promise + * 3. Throws error. + * + * Options: + * + * Promise: Desired Promise constructor + * global: Boolean - Should the registration be cached in a global variable to + * allow cross dependency/bundle registration? (default true) + */ +module.exports = function(root, loadImplementation){ + return function register(implementation, opts){ + implementation = implementation || null + opts = opts || {} + // global registration unless explicitly {global: false} in options (default true) + var registerGlobal = opts.global !== false; + + // load any previous global registration + if(registered === null && registerGlobal){ + registered = root[REGISTRATION_KEY] || null + } + + if(registered !== null + && implementation !== null + && registered.implementation !== implementation){ + // Throw error if attempting to redefine implementation + throw new Error('any-promise already defined as "'+registered.implementation+ + '". You can only register an implementation before the first '+ + ' call to require("any-promise") and an implementation cannot be changed') + } + + if(registered === null){ + // use provided implementation + if(implementation !== null && typeof opts.Promise !== 'undefined'){ + registered = { + Promise: opts.Promise, + implementation: implementation + } + } else { + // require implementation if implementation is specified but not provided + registered = loadImplementation(implementation) + } + + if(registerGlobal){ + // register preference globally in case multiple installations + root[REGISTRATION_KEY] = registered + } + } + + return registered + } +} diff --git a/node_modules/any-promise/optional.js b/node_modules/any-promise/optional.js new file mode 100644 index 0000000000000000000000000000000000000000..f3889420b898e770e33e5710379c5e13c7a330fd --- /dev/null +++ b/node_modules/any-promise/optional.js @@ -0,0 +1,6 @@ +"use strict"; +try { + module.exports = require('./register')().Promise || null +} catch(e) { + module.exports = null +} diff --git a/node_modules/any-promise/package.json b/node_modules/any-promise/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5baf14cf8c87abb445e62f9dcae03d7c588f1d28 --- /dev/null +++ b/node_modules/any-promise/package.json @@ -0,0 +1,45 @@ +{ + "name": "any-promise", + "version": "1.3.0", + "description": "Resolve any installed ES6 compatible promise", + "main": "index.js", + "typings": "index.d.ts", + "browser": { + "./register.js": "./register-shim.js" + }, + "scripts": { + "test": "ava" + }, + "repository": { + "type": "git", + "url": "https://github.com/kevinbeaty/any-promise" + }, + "keywords": [ + "promise", + "es6" + ], + "author": "Kevin Beaty", + "license": "MIT", + "bugs": { + "url": "https://github.com/kevinbeaty/any-promise/issues" + }, + "homepage": "http://github.com/kevinbeaty/any-promise", + "dependencies": {}, + "devDependencies": { + "ava": "^0.14.0", + "bluebird": "^3.0.0", + "es6-promise": "^3.0.0", + "is-promise": "^2.0.0", + "lie": "^3.0.0", + "mocha": "^2.0.0", + "native-promise-only": "^0.8.0", + "phantomjs-prebuilt": "^2.0.0", + "pinkie": "^2.0.0", + "promise": "^7.0.0", + "q": "^1.0.0", + "rsvp": "^3.0.0", + "vow": "^0.4.0", + "when": "^3.0.0", + "zuul": "^3.0.0" + } +} diff --git a/node_modules/any-promise/register-shim.js b/node_modules/any-promise/register-shim.js new file mode 100644 index 0000000000000000000000000000000000000000..9049405c0bfef05aa1a22a79078aa2fcb05ad4a8 --- /dev/null +++ b/node_modules/any-promise/register-shim.js @@ -0,0 +1,18 @@ +"use strict"; +module.exports = require('./loader')(window, loadImplementation) + +/** + * Browser specific loadImplementation. Always uses `window.Promise` + * + * To register a custom implementation, must register with `Promise` option. + */ +function loadImplementation(){ + if(typeof window.Promise === 'undefined'){ + throw new Error("any-promise browser requires a polyfill or explicit registration"+ + " e.g: require('any-promise/register/bluebird')") + } + return { + Promise: window.Promise, + implementation: 'window.Promise' + } +} diff --git a/node_modules/any-promise/register.d.ts b/node_modules/any-promise/register.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..97f2fc051080c9d1717337ede3f74e713f3ee1ad --- /dev/null +++ b/node_modules/any-promise/register.d.ts @@ -0,0 +1,17 @@ +import Promise = require('./index'); + +declare function register (module?: string, options?: register.Options): register.Register; + +declare namespace register { + export interface Register { + Promise: typeof Promise; + implementation: string; + } + + export interface Options { + Promise?: typeof Promise; + global?: boolean + } +} + +export = register; diff --git a/node_modules/any-promise/register.js b/node_modules/any-promise/register.js new file mode 100644 index 0000000000000000000000000000000000000000..255c6e2f516f62d788de60d29c2ecff07dd840f5 --- /dev/null +++ b/node_modules/any-promise/register.js @@ -0,0 +1,94 @@ +"use strict" +module.exports = require('./loader')(global, loadImplementation); + +/** + * Node.js version of loadImplementation. + * + * Requires the given implementation and returns the registration + * containing {Promise, implementation} + * + * If implementation is undefined or global.Promise, loads it + * Otherwise uses require + */ +function loadImplementation(implementation){ + var impl = null + + if(shouldPreferGlobalPromise(implementation)){ + // if no implementation or env specified use global.Promise + impl = { + Promise: global.Promise, + implementation: 'global.Promise' + } + } else if(implementation){ + // if implementation specified, require it + var lib = require(implementation) + impl = { + Promise: lib.Promise || lib, + implementation: implementation + } + } else { + // try to auto detect implementation. This is non-deterministic + // and should prefer other branches, but this is our last chance + // to load something without throwing error + impl = tryAutoDetect() + } + + if(impl === null){ + throw new Error('Cannot find any-promise implementation nor'+ + ' global.Promise. You must install polyfill or call'+ + ' require("any-promise/register") with your preferred'+ + ' implementation, e.g. require("any-promise/register/bluebird")'+ + ' on application load prior to any require("any-promise").') + } + + return impl +} + +/** + * Determines if the global.Promise should be preferred if an implementation + * has not been registered. + */ +function shouldPreferGlobalPromise(implementation){ + if(implementation){ + return implementation === 'global.Promise' + } else if(typeof global.Promise !== 'undefined'){ + // Load global promise if implementation not specified + // Versions < 0.11 did not have global Promise + // Do not use for version < 0.12 as version 0.11 contained buggy versions + var version = (/v(\d+)\.(\d+)\.(\d+)/).exec(process.version) + return !(version && +version[1] == 0 && +version[2] < 12) + } + + // do not have global.Promise or another implementation was specified + return false +} + +/** + * Look for common libs as last resort there is no guarantee that + * this will return a desired implementation or even be deterministic. + * The priority is also nearly arbitrary. We are only doing this + * for older versions of Node.js <0.12 that do not have a reasonable + * global.Promise implementation and we the user has not registered + * the preference. This preserves the behavior of any-promise <= 0.1 + * and may be deprecated or removed in the future + */ +function tryAutoDetect(){ + var libs = [ + "es6-promise", + "promise", + "native-promise-only", + "bluebird", + "rsvp", + "when", + "q", + "pinkie", + "lie", + "vow"] + var i = 0, len = libs.length + for(; i < len; i++){ + try { + return loadImplementation(libs[i]) + } catch(e){} + } + return null +} diff --git a/node_modules/any-promise/register/bluebird.d.ts b/node_modules/any-promise/register/bluebird.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..336ce12bb9106afdf843063ee67c0c1970f70d37 --- /dev/null +++ b/node_modules/any-promise/register/bluebird.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/bluebird.js b/node_modules/any-promise/register/bluebird.js new file mode 100644 index 0000000000000000000000000000000000000000..de0f87eb8e5099e3462608364a599c62e83eb550 --- /dev/null +++ b/node_modules/any-promise/register/bluebird.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('bluebird', {Promise: require('bluebird')}) diff --git a/node_modules/any-promise/register/es6-promise.d.ts b/node_modules/any-promise/register/es6-promise.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..336ce12bb9106afdf843063ee67c0c1970f70d37 --- /dev/null +++ b/node_modules/any-promise/register/es6-promise.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/es6-promise.js b/node_modules/any-promise/register/es6-promise.js new file mode 100644 index 0000000000000000000000000000000000000000..59bd55b761e004dea87e4afc212c8f584ac87dc6 --- /dev/null +++ b/node_modules/any-promise/register/es6-promise.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('es6-promise', {Promise: require('es6-promise').Promise}) diff --git a/node_modules/any-promise/register/lie.d.ts b/node_modules/any-promise/register/lie.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..336ce12bb9106afdf843063ee67c0c1970f70d37 --- /dev/null +++ b/node_modules/any-promise/register/lie.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/lie.js b/node_modules/any-promise/register/lie.js new file mode 100644 index 0000000000000000000000000000000000000000..7d305ca4006a0b53b8d8f8dc048fe5e2270d412f --- /dev/null +++ b/node_modules/any-promise/register/lie.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('lie', {Promise: require('lie')}) diff --git a/node_modules/any-promise/register/native-promise-only.d.ts b/node_modules/any-promise/register/native-promise-only.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..336ce12bb9106afdf843063ee67c0c1970f70d37 --- /dev/null +++ b/node_modules/any-promise/register/native-promise-only.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/native-promise-only.js b/node_modules/any-promise/register/native-promise-only.js new file mode 100644 index 0000000000000000000000000000000000000000..70a5a5e1dec6d467b8c656d734b53dac91005081 --- /dev/null +++ b/node_modules/any-promise/register/native-promise-only.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('native-promise-only', {Promise: require('native-promise-only')}) diff --git a/node_modules/any-promise/register/pinkie.d.ts b/node_modules/any-promise/register/pinkie.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..336ce12bb9106afdf843063ee67c0c1970f70d37 --- /dev/null +++ b/node_modules/any-promise/register/pinkie.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/pinkie.js b/node_modules/any-promise/register/pinkie.js new file mode 100644 index 0000000000000000000000000000000000000000..caaf98a5d04c78d8ba98b4084b87e1fb55776de2 --- /dev/null +++ b/node_modules/any-promise/register/pinkie.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('pinkie', {Promise: require('pinkie')}) diff --git a/node_modules/any-promise/register/promise.d.ts b/node_modules/any-promise/register/promise.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..336ce12bb9106afdf843063ee67c0c1970f70d37 --- /dev/null +++ b/node_modules/any-promise/register/promise.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/promise.js b/node_modules/any-promise/register/promise.js new file mode 100644 index 0000000000000000000000000000000000000000..746620d4e4748cadcf5fa1b9219bd764a1424b14 --- /dev/null +++ b/node_modules/any-promise/register/promise.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('promise', {Promise: require('promise')}) diff --git a/node_modules/any-promise/register/q.d.ts b/node_modules/any-promise/register/q.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..336ce12bb9106afdf843063ee67c0c1970f70d37 --- /dev/null +++ b/node_modules/any-promise/register/q.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/q.js b/node_modules/any-promise/register/q.js new file mode 100644 index 0000000000000000000000000000000000000000..0fc633a93f4ad2b07378afc998962288498aa481 --- /dev/null +++ b/node_modules/any-promise/register/q.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('q', {Promise: require('q').Promise}) diff --git a/node_modules/any-promise/register/rsvp.d.ts b/node_modules/any-promise/register/rsvp.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..336ce12bb9106afdf843063ee67c0c1970f70d37 --- /dev/null +++ b/node_modules/any-promise/register/rsvp.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/rsvp.js b/node_modules/any-promise/register/rsvp.js new file mode 100644 index 0000000000000000000000000000000000000000..02b13180d16be95d8a48d8b0f3765ed591d6977d --- /dev/null +++ b/node_modules/any-promise/register/rsvp.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('rsvp', {Promise: require('rsvp').Promise}) diff --git a/node_modules/any-promise/register/vow.d.ts b/node_modules/any-promise/register/vow.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..336ce12bb9106afdf843063ee67c0c1970f70d37 --- /dev/null +++ b/node_modules/any-promise/register/vow.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/vow.js b/node_modules/any-promise/register/vow.js new file mode 100644 index 0000000000000000000000000000000000000000..5b6868c4c988c069e670512f7964968a69799e87 --- /dev/null +++ b/node_modules/any-promise/register/vow.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('vow', {Promise: require('vow').Promise}) diff --git a/node_modules/any-promise/register/when.d.ts b/node_modules/any-promise/register/when.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..336ce12bb9106afdf843063ee67c0c1970f70d37 --- /dev/null +++ b/node_modules/any-promise/register/when.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/when.js b/node_modules/any-promise/register/when.js new file mode 100644 index 0000000000000000000000000000000000000000..d91c13d35e9b8ed5412012ab981442854db0b6ad --- /dev/null +++ b/node_modules/any-promise/register/when.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('when', {Promise: require('when').Promise}) diff --git a/node_modules/anymatch/LICENSE b/node_modules/anymatch/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..491766ca79a0382e5fc4e370c853201bb641e0d8 --- /dev/null +++ b/node_modules/anymatch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com) + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/anymatch/README.md b/node_modules/anymatch/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1dd67f53446ccbad8d17662fee69dd3c46531ba4 --- /dev/null +++ b/node_modules/anymatch/README.md @@ -0,0 +1,87 @@ +anymatch [![Build Status](https://travis-ci.org/micromatch/anymatch.svg?branch=master)](https://travis-ci.org/micromatch/anymatch) [![Coverage Status](https://img.shields.io/coveralls/micromatch/anymatch.svg?branch=master)](https://coveralls.io/r/micromatch/anymatch?branch=master) +====== +Javascript module to match a string against a regular expression, glob, string, +or function that takes the string as an argument and returns a truthy or falsy +value. The matcher can also be an array of any or all of these. Useful for +allowing a very flexible user-defined config to define things like file paths. + +__Note: This module has Bash-parity, please be aware that Windows-style backslashes are not supported as separators. See https://github.com/micromatch/micromatch#backslashes for more information.__ + + +Usage +----- +```sh +npm install anymatch +``` + +#### anymatch(matchers, testString, [returnIndex], [options]) +* __matchers__: (_Array|String|RegExp|Function_) +String to be directly matched, string with glob patterns, regular expression +test, function that takes the testString as an argument and returns a truthy +value if it should be matched, or an array of any number and mix of these types. +* __testString__: (_String|Array_) The string to test against the matchers. If +passed as an array, the first element of the array will be used as the +`testString` for non-function matchers, while the entire array will be applied +as the arguments for function matchers. +* __options__: (_Object_ [optional]_) Any of the [picomatch](https://github.com/micromatch/picomatch#options) options. + * __returnIndex__: (_Boolean [optional]_) If true, return the array index of +the first matcher that that testString matched, or -1 if no match, instead of a +boolean result. + +```js +const anymatch = require('anymatch'); + +const matchers = [ 'path/to/file.js', 'path/anyjs/**/*.js', /foo.js$/, string => string.includes('bar') && string.length > 10 ] ; + +anymatch(matchers, 'path/to/file.js'); // true +anymatch(matchers, 'path/anyjs/baz.js'); // true +anymatch(matchers, 'path/to/foo.js'); // true +anymatch(matchers, 'path/to/bar.js'); // true +anymatch(matchers, 'bar.js'); // false + +// returnIndex = true +anymatch(matchers, 'foo.js', {returnIndex: true}); // 2 +anymatch(matchers, 'path/anyjs/foo.js', {returnIndex: true}); // 1 + +// any picomatc + +// using globs to match directories and their children +anymatch('node_modules', 'node_modules'); // true +anymatch('node_modules', 'node_modules/somelib/index.js'); // false +anymatch('node_modules/**', 'node_modules/somelib/index.js'); // true +anymatch('node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // false +anymatch('**/node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // true + +const matcher = anymatch(matchers); +['foo.js', 'bar.js'].filter(matcher); // [ 'foo.js' ] +anymatch master* ❯ + +``` + +#### anymatch(matchers) +You can also pass in only your matcher(s) to get a curried function that has +already been bound to the provided matching criteria. This can be used as an +`Array#filter` callback. + +```js +var matcher = anymatch(matchers); + +matcher('path/to/file.js'); // true +matcher('path/anyjs/baz.js', true); // 1 + +['foo.js', 'bar.js'].filter(matcher); // ['foo.js'] +``` + +Changelog +---------- +[See release notes page on GitHub](https://github.com/micromatch/anymatch/releases) + +- **v3.0:** Removed `startIndex` and `endIndex` arguments. Node 8.x-only. +- **v2.0:** [micromatch](https://github.com/jonschlinkert/micromatch) moves away from minimatch-parity and inline with Bash. This includes handling backslashes differently (see https://github.com/micromatch/micromatch#backslashes for more information). +- **v1.2:** anymatch uses [micromatch](https://github.com/jonschlinkert/micromatch) +for glob pattern matching. Issues with glob pattern matching should be +reported directly to the [micromatch issue tracker](https://github.com/jonschlinkert/micromatch/issues). + +License +------- +[ISC](https://raw.github.com/micromatch/anymatch/master/LICENSE) diff --git a/node_modules/anymatch/index.d.ts b/node_modules/anymatch/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ef7eaaddd8b5f479aeae707206d8163f82ada94 --- /dev/null +++ b/node_modules/anymatch/index.d.ts @@ -0,0 +1,20 @@ +type AnymatchFn = (testString: string) => boolean; +type AnymatchPattern = string|RegExp|AnymatchFn; +type AnymatchMatcher = AnymatchPattern|AnymatchPattern[] +type AnymatchTester = { + (testString: string|any[], returnIndex: true): number; + (testString: string|any[]): boolean; +} + +type PicomatchOptions = {dot: boolean}; + +declare const anymatch: { + (matchers: AnymatchMatcher): AnymatchTester; + (matchers: AnymatchMatcher, testString: null, returnIndex: true | PicomatchOptions): AnymatchTester; + (matchers: AnymatchMatcher, testString: string|any[], returnIndex: true | PicomatchOptions): number; + (matchers: AnymatchMatcher, testString: string|any[]): boolean; +} + +export {AnymatchMatcher as Matcher} +export {AnymatchTester as Tester} +export default anymatch diff --git a/node_modules/anymatch/index.js b/node_modules/anymatch/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8eb73e9c9a61d2c642d3c5f44a2fe4cd6cd04615 --- /dev/null +++ b/node_modules/anymatch/index.js @@ -0,0 +1,104 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { value: true }); + +const picomatch = require('picomatch'); +const normalizePath = require('normalize-path'); + +/** + * @typedef {(testString: string) => boolean} AnymatchFn + * @typedef {string|RegExp|AnymatchFn} AnymatchPattern + * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher + */ +const BANG = '!'; +const DEFAULT_OPTIONS = {returnIndex: false}; +const arrify = (item) => Array.isArray(item) ? item : [item]; + +/** + * @param {AnymatchPattern} matcher + * @param {object} options + * @returns {AnymatchFn} + */ +const createPattern = (matcher, options) => { + if (typeof matcher === 'function') { + return matcher; + } + if (typeof matcher === 'string') { + const glob = picomatch(matcher, options); + return (string) => matcher === string || glob(string); + } + if (matcher instanceof RegExp) { + return (string) => matcher.test(string); + } + return (string) => false; +}; + +/** + * @param {Array} patterns + * @param {Array} negPatterns + * @param {String|Array} args + * @param {Boolean} returnIndex + * @returns {boolean|number} + */ +const matchPatterns = (patterns, negPatterns, args, returnIndex) => { + const isList = Array.isArray(args); + const _path = isList ? args[0] : args; + if (!isList && typeof _path !== 'string') { + throw new TypeError('anymatch: second argument must be a string: got ' + + Object.prototype.toString.call(_path)) + } + const path = normalizePath(_path, false); + + for (let index = 0; index < negPatterns.length; index++) { + const nglob = negPatterns[index]; + if (nglob(path)) { + return returnIndex ? -1 : false; + } + } + + const applied = isList && [path].concat(args.slice(1)); + for (let index = 0; index < patterns.length; index++) { + const pattern = patterns[index]; + if (isList ? pattern(...applied) : pattern(path)) { + return returnIndex ? index : true; + } + } + + return returnIndex ? -1 : false; +}; + +/** + * @param {AnymatchMatcher} matchers + * @param {Array|string} testString + * @param {object} options + * @returns {boolean|number|Function} + */ +const anymatch = (matchers, testString, options = DEFAULT_OPTIONS) => { + if (matchers == null) { + throw new TypeError('anymatch: specify first argument'); + } + const opts = typeof options === 'boolean' ? {returnIndex: options} : options; + const returnIndex = opts.returnIndex || false; + + // Early cache for matchers. + const mtchers = arrify(matchers); + const negatedGlobs = mtchers + .filter(item => typeof item === 'string' && item.charAt(0) === BANG) + .map(item => item.slice(1)) + .map(item => picomatch(item, opts)); + const patterns = mtchers + .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG)) + .map(matcher => createPattern(matcher, opts)); + + if (testString == null) { + return (testString, ri = false) => { + const returnIndex = typeof ri === 'boolean' ? ri : false; + return matchPatterns(patterns, negatedGlobs, testString, returnIndex); + } + } + + return matchPatterns(patterns, negatedGlobs, testString, returnIndex); +}; + +anymatch.default = anymatch; +module.exports = anymatch; diff --git a/node_modules/anymatch/package.json b/node_modules/anymatch/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2cb2307e49efc4770c0e8364e4387105162956dd --- /dev/null +++ b/node_modules/anymatch/package.json @@ -0,0 +1,48 @@ +{ + "name": "anymatch", + "version": "3.1.3", + "description": "Matches strings against configurable strings, globs, regular expressions, and/or functions", + "files": [ + "index.js", + "index.d.ts" + ], + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "author": { + "name": "Elan Shanker", + "url": "https://github.com/es128" + }, + "license": "ISC", + "homepage": "https://github.com/micromatch/anymatch", + "repository": { + "type": "git", + "url": "https://github.com/micromatch/anymatch" + }, + "keywords": [ + "match", + "any", + "string", + "file", + "fs", + "list", + "glob", + "regex", + "regexp", + "regular", + "expression", + "function" + ], + "scripts": { + "test": "nyc mocha", + "mocha": "mocha" + }, + "devDependencies": { + "mocha": "^6.1.3", + "nyc": "^14.0.0" + }, + "engines": { + "node": ">= 8" + } +} diff --git a/node_modules/anynum/LICENSE b/node_modules/anynum/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0311839a07c340fb1dfa5eb9b29a42bbd693ff84 --- /dev/null +++ b/node_modules/anynum/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Natural Intelligence + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/anynum/README.md b/node_modules/anynum/README.md new file mode 100644 index 0000000000000000000000000000000000000000..62fc5efa99ee116ee7cbdcd7f38e656e5b717826 --- /dev/null +++ b/node_modules/anynum/README.md @@ -0,0 +1,142 @@ +# anynum + +Normalize Unicode decimal digits and minus signs to ASCII. + +Converts digits from any script — Devanagari, Arabic-Indic, Thai, Bengali, Fullwidth, and [50+ others](#supported-scripts) — to their ASCII equivalents (`0`–`9`). Also normalizes Unicode minus variants (`−`, `-`, `﹣`) to ASCII `-`. + +Pairs naturally with [`strnum`](https://github.com/nicolo-ribaudo/strnum) — use `anynum` to normalize first, then `strnum` to detect the numeric type. + +```js +import anynum from 'anynum'; + +anynum('१२.३४') // → '12.34' (Devanagari) +anynum('٣٫١٤') // → '3.14' (Arabic-Indic) +anynum('−४२') // → '-42' (Unicode minus + Devanagari) +anynum('-99.5') // → '-99.5' (Fullwidth minus + Fullwidth digits) +anynum('hello') // → 'hello' (no digits — zero allocation) +anynum('100') // → '100' (already ASCII — zero allocation) +``` + +--- + +## Install + +```bash +npm install anynum +``` + +--- + +## Usage + +```js +// ESM +import anynum from 'anynum'; +import { anynum } from 'anynum'; + +``` + +### API + +```ts +anynum(str: string): string +``` + +- Accepts a `string`, returns a `string`. +- Non-string values are returned as-is (no throw). +- Non-digit characters pass through unchanged. +- If no conversion is needed, the **original string is returned** (zero allocation). + +--- + +## What gets converted + +### Decimal digits + +Any Unicode character in category `Nd` (decimal digit) is mapped to its ASCII equivalent. This covers all positional decimal digit scripts — every script whose digits represent `0`–`9` by position. + +```js +anynum('๑๒๓') // Thai → '123' +anynum('੧੨੩') // Gurmukhi → '123' +anynum('᠑᠒᠓') // Mongolian → '123' +anynum('𝟏𝟐𝟑') // Math Bold → '123' +``` + +### Unicode minus variants + +Three Unicode characters are normalized to ASCII `-` (`U+002D`): + +| Code point | Character | Name | +|---|---|---| +| `U+2212` | `−` | MINUS SIGN (mathematical) | +| `U+FF0D` | `-` | FULLWIDTH HYPHEN-MINUS | +| `U+FE63` | `﹣` | SMALL HYPHEN-MINUS | + +Dashes used for punctuation — EN DASH (`–`), EM DASH (`—`), HYPHEN (`‐`) — are intentionally **not** converted. + +```js +anynum('−42') // U+2212 MINUS SIGN → '-42' +anynum('-42') // U+FF0D FULLWIDTH → '-42' +anynum('–42') // U+2013 EN DASH → '–42' (unchanged) +``` + +--- + +## Use with strnum + +`anynum` and `strnum` compose cleanly: + +```js +import anynum from 'anynum'; +import strnum from 'strnum'; + +strnum(anynum('१२.३४')) // → 12.34 (number, float) +strnum(anynum('−४२')) // → '-42' (string; strnum handles sign detection) +strnum(anynum('hello')) // → 'hello' +``` + +--- + + +## Supported scripts + +50+ decimal digit scripts from Unicode `Nd` category, including: + +| Script | Zero | Sample | +|---|---|---| +| Devanagari (Hindi/Marathi/Nepali) | `U+0966` | `०१२३४५६७८९` | +| Arabic-Indic | `U+0660` | `٠١٢٣٤٥٦٧٨٩` | +| Extended Arabic-Indic (Urdu/Persian) | `U+06F0` | `۰۱۲۳۴۵۶۷۸۹` | +| Bengali | `U+09E6` | `০১২৩৪৫৬৭৮৯` | +| Gurmukhi | `U+0A66` | `੦੧੨੩੪੫੬੭੮੯` | +| Gujarati | `U+0AE6` | `૦૧૨૩૪૫૬૭૮૯` | +| Odia | `U+0B66` | `୦୧୨୩୪୫୬୭୮୯` | +| Tamil | `U+0BE6` | `௦௧௨௩௪௫௬௭௮௯` | +| Telugu | `U+0C66` | `౦౧౨౩౪౫౬౭౮౯` | +| Kannada | `U+0CE6` | `೦೧೨೩೪೫೬೭೮೯` | +| Malayalam | `U+0D66` | `൦൧൨൩൪൫൬൭൮൯` | +| Thai | `U+0E50` | `๐๑๒๓๔๕๖๗๘๙` | +| Lao | `U+0ED0` | `໐໑໒໓໔໕໖໗໘໙` | +| Tibetan | `U+0F20` | `༠༡༢༣༤༥༦༧༨༩` | +| Myanmar | `U+1040` | `၀၁၂၃၄၅၆၇၈၉` | +| Khmer | `U+17E0` | `០១២៣៤៥៦៧៨៩` | +| Mongolian | `U+1810` | `᠐᠑᠒᠓᠔᠕᠖᠗᠘᠙` | +| Fullwidth (CJK context) | `U+FF10` | `0123456789` | +| Mathematical Bold | `U+1D7CE` | `𝟎𝟏𝟐𝟑𝟒𝟓𝟔𝟕𝟖𝟗` | +| Adlam | `U+1E950` | `𞥐𞥑𞥒𞥓𞥔𞥕𞥖𞥗𞥘𞥙` | +| … and 30+ more | | | + +--- + +## What it does NOT convert + +- **Kanji/Chinese numeral words** (`三`, `百`, `万`) — these are ideographic numerals, not decimal digits. Each language has its own positional system requiring separate parsing logic. +- **Roman numerals** (`Ⅳ`, `Ⅻ`) — not decimal digits. +- **Punctuation dashes** (`–` EN, `—` EM, `‐` HYPHEN) — not numeric signs. +- **Decimal separators** — commas, periods, Arabic decimal comma (`٫`) are passed through as-is. Separator normalization is the caller's responsibility. + +--- + +## License + +MIT \ No newline at end of file diff --git a/node_modules/anynum/anynum.js b/node_modules/anynum/anynum.js new file mode 100644 index 0000000000000000000000000000000000000000..53987d39e8b2631ef63a5385b2a4297923cf8150 --- /dev/null +++ b/node_modules/anynum/anynum.js @@ -0,0 +1,135 @@ +'use strict'; + +import { TABLE, TABLE_OFFSET, HIGH_MAP, NOT_DIGIT } from './digitTable.js'; + +const CHAR_0 = 48; // '0'.charCodeAt(0) +const CHAR_9 = 57; // '9'.charCodeAt(0) +const CHAR_MINUS = 45; // '-'.charCodeAt(0) + +// Unicode minus/hyphen variants worth normalizing to ASCII '-' in numeric context: +// U+2212 MINUS SIGN − (mathematically correct minus) +// U+FF0D FULLWIDTH HYPHEN-MINUS - (Japanese fullwidth context) +// U+FE63 SMALL HYPHEN-MINUS ﹣ (small form variant) +// +// NOT normalized (deliberate): +// U+2013 EN DASH – (punctuation, not a numeric sign) +// U+2014 EM DASH — (punctuation) +// U+2010 HYPHEN ‐ (typographic hyphen) +// +// Rationale: only characters a human or locale formatter would plausibly use +// as a numeric minus sign are normalized. Dashes used for punctuation are left +// alone to avoid mangling non-numeric strings. +const MINUS_SET = new Set([0x2212, 0xFF0D, 0xFE63]); + +/** + * Normalize all Unicode decimal digit characters in a string to ASCII (0-9), + * and normalize Unicode minus variants to ASCII '-' (U+002D). + * + * Non-digit, non-minus characters are passed through unchanged. + * + * Performance design: + * - Fast path: if the string has no convertible characters, return it unchanged + * (zero allocation). + * - BMP digits (0x0660..0xFFFF excl. surrogates): flat Uint8Array lookup (O(1)). + * - Supplementary plane digits (> 0xFFFF, encoded as surrogate pairs): Map lookup. + * - Minus variants: checked inline with a small fixed Set. + * + * @param {string} str + * @returns {string} + */ +function anynum(str) { + if (typeof str !== 'string') return str; + + const len = str.length; + if (len === 0) return str; + + // Scan for first character needing conversion. + // If none found, return original string (zero allocation). + let firstHit = -1; + + for (let i = 0; i < len; i++) { + const cc = str.charCodeAt(i); + + // ASCII digit or ASCII minus — already normalized, skip fast + if ((cc >= CHAR_0 && cc <= CHAR_9) || cc === CHAR_MINUS) continue; + + // Below first unicode digit script — check minus variants only + if (cc < TABLE_OFFSET) { + if (MINUS_SET.has(cc)) { firstHit = i; break; } + continue; + } + + // Surrogate pairs live in BMP range 0xD800-0xDFFF — check before TABLE + if (cc >= 0xD800 && cc <= 0xDBFF) { + if (i + 1 < len) { + const low = str.charCodeAt(i + 1); + if (low >= 0xDC00 && low <= 0xDFFF) { + const cp = 0x10000 + ((cc - 0xD800) << 10) + (low - 0xDC00); + if (HIGH_MAP.has(cp)) { firstHit = i; break; } + } + } + continue; + } + + // BMP non-surrogate: flat table lookup; also check minus variants in this range + if (TABLE[cc - TABLE_OFFSET] !== NOT_DIGIT || MINUS_SET.has(cc)) { + firstHit = i; + break; + } + } + + // Nothing to replace — return original, zero allocation + if (firstHit === -1) return str; + + // Build result: copy unchanged prefix, then convert from firstHit onward + const chars = []; + + if (firstHit > 0) chars.push(str.slice(0, firstHit)); + + for (let i = firstHit; i < len; i++) { + const cc = str.charCodeAt(i); + + // ASCII digit or ASCII minus — pass through + if ((cc >= CHAR_0 && cc <= CHAR_9) || cc === CHAR_MINUS) { + chars.push(str[i]); + continue; + } + + // Below TABLE_OFFSET — check minus variants, else pass through + if (cc < TABLE_OFFSET) { + chars.push(MINUS_SET.has(cc) ? '-' : str[i]); + continue; + } + + // Surrogate pairs + if (cc >= 0xD800 && cc <= 0xDBFF) { + if (i + 1 < len) { + const low = str.charCodeAt(i + 1); + if (low >= 0xDC00 && low <= 0xDFFF) { + const cp = 0x10000 + ((cc - 0xD800) << 10) + (low - 0xDC00); + const d = HIGH_MAP.get(cp); + if (d !== undefined) { + chars.push(String.fromCharCode(d + 48)); + i++; // consume low surrogate + continue; + } + } + } + chars.push(str[i]); + continue; + } + + // BMP non-surrogate: flat table lookup + minus variants + if (MINUS_SET.has(cc)) { + chars.push('-'); + continue; + } + const d = TABLE[cc - TABLE_OFFSET]; + chars.push(d !== NOT_DIGIT ? String.fromCharCode(d + 48) : str[i]); + } + + return chars.join(''); +} + +export { anynum }; +export default anynum; \ No newline at end of file diff --git a/node_modules/anynum/digitTable.js b/node_modules/anynum/digitTable.js new file mode 100644 index 0000000000000000000000000000000000000000..9982e4dc993df4473346bf2340e804e09b6159e7 --- /dev/null +++ b/node_modules/anynum/digitTable.js @@ -0,0 +1,116 @@ +/** + * Flat lookup table: maps Unicode code point → ASCII digit (0-9). + * Only decimal digit characters (Unicode category Nd) are included. + * + * Strategy: Int32Array of size (maxCodePoint - minCodePoint + 1). + * Value 0xFF means "not a digit". Value 0-9 is the ASCII digit value. + * This gives O(1) lookup with no branching, no bisect, no loop. + * + * Memory: range is 0x0660 to 0x1FBF0 → ~129,936 entries × 1 byte = ~127 KB. + * Acceptable for a one-time init; lookup is a single array index. + */ + +// All known Unicode Nd (decimal digit) script zero code points. +// Each script has exactly 10 consecutive digits: zero+0 .. zero+9. +const SCRIPT_ZEROS = [ + // Basic Latin (ASCII) — included for completeness / pass-through + 0x0030, // 0-9 + + // Arabic scripts + 0x0660, // Arabic-Indic ٠١٢٣٤٥٦٧٨٩ + 0x06F0, // Extended Arabic-Indic (Urdu/Persian/Sindhi) ۰۱۲۳ + + // Indic scripts + 0x0966, // Devanagari ०१२३४५६७८९ + 0x09E6, // Bengali ০১২৩৪৫৬৭৮৯ + 0x0A66, // Gurmukhi ੦੧੨੩੪੫੬੭੮੯ + 0x0AE6, // Gujarati ૦૧૨૩૪૫૬૭૮૯ + 0x0B66, // Odia ୦୧୨୩୪୫୬୭୮୯ + 0x0BE6, // Tamil ௦௧௨௩௪௫௬௭௮௯ + 0x0C66, // Telugu ౦౧౨౩౪౫౬౭౮౯ + 0x0CE6, // Kannada ೦೧೨೩೪೫೬೭೮೯ + 0x0D66, // Malayalam ൦൧൨൩൪൫൬൭൮൯ + 0x0DE6, // Sinhala Archaic ෦෧෨෩෪෫෬෭෮෯ + + // Southeast Asian scripts + 0x0E50, // Thai ๐๑๒๓๔๕๖๗๘๙ + 0x0ED0, // Lao ໐໑໒໓໔໕໖໗໘໙ + 0x0F20, // Tibetan ༠༡༢༣༤༥༦༧༨༩ + 0x1040, // Myanmar ၀၁၂၃၄၅၆၇၈၉ + 0x1090, // Myanmar Shan ႐႑႒႓႔႕႖႗႘႙ + 0x17E0, // Khmer ០១២៣៤៥៦៧៨៩ + 0x1810, // Mongolian ᠐᠑᠒᠓᠔᠕᠖᠗᠘᠙ + 0x1946, // Limbu ᥆᥇᥈᥉᥊᥋᥌᥍᥎᥏ + 0x19D0, // New Tai Lue ᧐᧑᧒᧓᧔᧕᧖᧗᧘᧙ + 0x1A80, // Tai Tham Hora ᪀᪁᪂᪃᪄᪅᪆᪇᪈᪉ + 0x1A90, // Tai Tham Tham ᪐᪑᪒᪓᪔᪕᪖᪗᪘᪙ + 0x1B50, // Balinese ᭐᭑᭒᭓᭔᭕᭖᭗᭘᭙ + 0x1BB0, // Sundanese ᮰᮱᮲᮳᮴᮵᮶᮷᮸᮹ + 0x1C40, // Lepcha ᱀᱁᱂᱃᱄᱅᱆᱇᱈᱉ + 0x1C50, // Ol Chiki ᱐᱑᱒᱓᱔᱕᱖᱗᱘᱙ + + // Fullwidth (CJK context) + 0xFF10, // Fullwidth 0123456789 + + // Mathematical digit variants (Unicode math block) + 0x1D7CE, // Mathematical Bold + 0x1D7D8, // Mathematical Double-Struck + 0x1D7E2, // Mathematical Sans-Serif + 0x1D7EC, // Mathematical Sans-Serif Bold + 0x1D7F6, // Mathematical Monospace + + // Other scripts + 0x104A0, // Osmanya 𐒠𐒡𐒢𐒣𐒤𐒥𐒦𐒧𐒨𐒩 + 0x10D30, // Hanifi Rohingya 𐴰𐴱𐴲𐴳𐴴𐴵𐴶𐴷𐴸𐴹 + 0x11066, // Brahmi 𑁦𑁧𑁨𑁩𑁪𑁫𑁬𑁭𑁮𑁯 + 0x110F0, // Sora Sompeng 𑃰𑃱𑃲𑃳𑃴𑃵𑃶𑃷𑃸𑃹 + 0x11136, // Chakma 𑄶𑄷𑄸𑄹𑄺𑄻𑄼𑄽𑄾𑄿 + 0x111D0, // Sharada 𑇐𑇑𑇒𑇓𑇔𑇕𑇖𑇗𑇘𑇙 + 0x112F0, // Khudawadi 𑋰𑋱𑋲𑋳𑋴𑋵𑋶𑋷𑋸𑋹 + 0x11450, // Newa 𑑐𑑑𑑒𑑓𑑔𑑕𑑖𑑗𑑘𑑙 + 0x114D0, // Tirhuta 𑓐𑓑𑓒𑓓𑓔𑓕𑓖𑓗𑓘𑓙 + 0x11650, // Modi 𑙐𑙑𑙒𑙓𑙔𑙕𑙖𑙗𑙘𑙙 + 0x116C0, // Takri 𑛀𑛁𑛂𑛃𑛄𑛅𑛆𑛇𑛈𑛉 + 0x11730, // Ahom 𑜰𑜱𑜲𑜳𑜴𑜵𑜶𑜷𑜸𑜹 + 0x118E0, // Warang Citi 𑣠𑣡𑣢𑣣𑣤𑣥𑣦𑣧𑣨𑣩 + 0x11950, // Dives Akuru 𑥐𑥑𑥒𑥓𑥔𑥕𑥖𑥗𑥘𑥙 + 0x11BF0, // Khitan Small Script 𑯰𑯱𑯲𑯳𑯴𑯵𑯶𑯷𑯸𑯹 + 0x11C50, // Bhaiksuki 𑱐𑱑𑱒𑱓𑱔𑱕𑱖𑱗𑱘𑱙 + 0x11D50, // Masaram Gondi 𑵐𑵑𑵒𑵓𑵔𑵕𑵖𑵗𑵘𑵙 + 0x11DA0, // Gunjala Gondi 𑶠𑶡𑶢𑶣𑶤𑶥𑶦𑶧𑶨𑶩 + 0x11F50, // Kawi 𑽐𑽑𑽒𑽓𑽔𑽕𑽖𑽗𑽘𑽙 + 0x16A60, // Mro 𖩠𖩡𖩢𖩣𖩤𖩥𖩦𖩧𖩨𖩩 + 0x16AC0, // Tangsa 𖫀𖫁𖫂𖫃𖫄𖫅𖫆𖫇𖫈𖫉 + 0x16B50, // Pahawh Hmong 𖭐𖭑𖭒𖭓𖭔𖭕𖭖𖭗𖭘𖭙 + 0x1E140, // Nyiakeng Puachue Hmong 𞅀𞅁𞅂𞅃𞅄𞅅𞅆𞅇𞅈𞅉 + 0x1E2F0, // Wancho 𞋰𞋱𞋲𞋳𞋴𞋵𞋶𞋷𞋸𞋹 + 0x1E4F0, // Nag Mundari 𞓰𞓱𞓲𞓳𞓴𞓵𞓶𞓷𞓸𞓹 + 0x1E950, // Adlam 𞥐𞥑𞥒𞥓𞥔𞥕𞥖𞥗𞥘𞥙 + 0x1FBF0, // Segmented digit symbols 🯰🯱🯲🯳🯴🯵🯶🯷🯸🯹 +]; + +// Build a sparse Map for scripts above 0xFFFF (surrogate-pair range). +// These can't go into a flat Uint8Array indexed by code point efficiently. +const NOT_DIGIT = 0xFF; +const HIGH_MAP = new Map(); // codePoint → digit value (0-9) + +const LOW_MAX = 0xFFFF; +const LOW_MIN = 0x0660; // first non-ASCII digit script + +// Flat Uint8Array covering 0x0660 .. 0xFFFF +const TABLE_OFFSET = LOW_MIN; +const TABLE_SIZE = LOW_MAX - LOW_MIN + 1; +const TABLE = new Uint8Array(TABLE_SIZE).fill(NOT_DIGIT); + +for (const zero of SCRIPT_ZEROS) { + for (let d = 0; d < 10; d++) { + const cp = zero + d; + if (cp <= LOW_MAX) { + TABLE[cp - TABLE_OFFSET] = d; + } else { + HIGH_MAP.set(cp, d); + } + } +} + +export { TABLE, TABLE_OFFSET, HIGH_MAP, NOT_DIGIT }; diff --git a/node_modules/anynum/package.json b/node_modules/anynum/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8277a050278cbfb725bb7808d745673b41026ce4 --- /dev/null +++ b/node_modules/anynum/package.json @@ -0,0 +1,42 @@ +{ + "name": "anynum", + "version": "1.0.0", + "description": "Normalize all Unicode decimal digits (Devanagari, Arabic, Thai, etc.) to ASCII numerals. Zero dependencies, performance-first.", + "type": "module", + "main": "./anynum.js", + "files": [ + "anynum.js", + "digitTable.js", + "README.md" + ], + "scripts": { + "test": "jasmine tests/anynum.test.js", + "bench": "node test/bench.js" + }, + "keywords": [ + "unicode", + "digits", + "normalize", + "devanagari", + "arabic", + "hindi", + "japanese", + "indic", + "asian", + "math", + "numerals", + "strnum" + ], + "repository": { + "type": "git", + "url": "https://github.com/NaturalIntelligence/anynum" + }, + "author": "Amit Gupta (https://solothought.work/)", + "license": "MIT", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ] +} \ No newline at end of file diff --git a/node_modules/append-field/.npmignore b/node_modules/append-field/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..c2658d7d1b31848c3b71960543cb0368e56cd4c7 --- /dev/null +++ b/node_modules/append-field/.npmignore @@ -0,0 +1 @@ +node_modules/ diff --git a/node_modules/append-field/LICENSE b/node_modules/append-field/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..14b1f891b40cc88122b238cdfb966124d7268084 --- /dev/null +++ b/node_modules/append-field/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Linus Unnebäck + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/append-field/README.md b/node_modules/append-field/README.md new file mode 100644 index 0000000000000000000000000000000000000000..62b901b7e8c1f92f113ad0bc728aed6595ee7a13 --- /dev/null +++ b/node_modules/append-field/README.md @@ -0,0 +1,44 @@ +# `append-field` + +A [W3C HTML JSON forms spec](http://www.w3.org/TR/html-json-forms/) compliant +field appender (for lack of a better name). Useful for people implementing +`application/x-www-form-urlencoded` and `multipart/form-data` parsers. + +It works best on objects created with `Object.create(null)`. Otherwise it might +conflict with variables from the prototype (e.g. `hasOwnProperty`). + +## Installation + +```sh +npm install --save append-field +``` + +## Usage + +```javascript +var appendField = require('append-field') +var obj = Object.create(null) + +appendField(obj, 'pets[0][species]', 'Dahut') +appendField(obj, 'pets[0][name]', 'Hypatia') +appendField(obj, 'pets[1][species]', 'Felis Stultus') +appendField(obj, 'pets[1][name]', 'Billie') + +console.log(obj) +``` + +```text +{ pets: + [ { species: 'Dahut', name: 'Hypatia' }, + { species: 'Felis Stultus', name: 'Billie' } ] } +``` + +## API + +### `appendField(store, key, value)` + +Adds the field named `key` with the value `value` to the object `store`. + +## License + +MIT diff --git a/node_modules/append-field/index.js b/node_modules/append-field/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fc5acc8bc41502a08fa7d537987d05b0c7ef5775 --- /dev/null +++ b/node_modules/append-field/index.js @@ -0,0 +1,12 @@ +var parsePath = require('./lib/parse-path') +var setValue = require('./lib/set-value') + +function appendField (store, key, value) { + var steps = parsePath(key) + + steps.reduce(function (context, step) { + return setValue(context, step, context[step.key], value) + }, store) +} + +module.exports = appendField diff --git a/node_modules/append-field/lib/parse-path.js b/node_modules/append-field/lib/parse-path.js new file mode 100644 index 0000000000000000000000000000000000000000..31d617966f02ca37d98f9caa3ef4779118bbd635 --- /dev/null +++ b/node_modules/append-field/lib/parse-path.js @@ -0,0 +1,53 @@ +var reFirstKey = /^[^\[]*/ +var reDigitPath = /^\[(\d+)\]/ +var reNormalPath = /^\[([^\]]+)\]/ + +function parsePath (key) { + function failure () { + return [{ type: 'object', key: key, last: true }] + } + + var firstKey = reFirstKey.exec(key)[0] + if (!firstKey) return failure() + + var len = key.length + var pos = firstKey.length + var tail = { type: 'object', key: firstKey } + var steps = [tail] + + while (pos < len) { + var m + + if (key[pos] === '[' && key[pos + 1] === ']') { + pos += 2 + tail.append = true + if (pos !== len) return failure() + continue + } + + m = reDigitPath.exec(key.substring(pos)) + if (m !== null) { + pos += m[0].length + tail.nextType = 'array' + tail = { type: 'array', key: parseInt(m[1], 10) } + steps.push(tail) + continue + } + + m = reNormalPath.exec(key.substring(pos)) + if (m !== null) { + pos += m[0].length + tail.nextType = 'object' + tail = { type: 'object', key: m[1] } + steps.push(tail) + continue + } + + return failure() + } + + tail.last = true + return steps +} + +module.exports = parsePath diff --git a/node_modules/append-field/lib/set-value.js b/node_modules/append-field/lib/set-value.js new file mode 100644 index 0000000000000000000000000000000000000000..c15e87377bc84537acdceb74466320644592b72d --- /dev/null +++ b/node_modules/append-field/lib/set-value.js @@ -0,0 +1,64 @@ +function valueType (value) { + if (value === undefined) return 'undefined' + if (Array.isArray(value)) return 'array' + if (typeof value === 'object') return 'object' + return 'scalar' +} + +function setLastValue (context, step, currentValue, entryValue) { + switch (valueType(currentValue)) { + case 'undefined': + if (step.append) { + context[step.key] = [entryValue] + } else { + context[step.key] = entryValue + } + break + case 'array': + context[step.key].push(entryValue) + break + case 'object': + return setLastValue(currentValue, { type: 'object', key: '', last: true }, currentValue[''], entryValue) + case 'scalar': + context[step.key] = [context[step.key], entryValue] + break + } + + return context +} + +function setValue (context, step, currentValue, entryValue) { + if (step.last) return setLastValue(context, step, currentValue, entryValue) + + var obj + switch (valueType(currentValue)) { + case 'undefined': + if (step.nextType === 'array') { + context[step.key] = [] + } else { + context[step.key] = Object.create(null) + } + return context[step.key] + case 'object': + return context[step.key] + case 'array': + if (step.nextType === 'array') { + return currentValue + } + + obj = Object.create(null) + context[step.key] = obj + currentValue.forEach(function (item, i) { + if (item !== undefined) obj['' + i] = item + }) + + return obj + case 'scalar': + obj = Object.create(null) + obj[''] = currentValue + context[step.key] = obj + return obj + } +} + +module.exports = setValue diff --git a/node_modules/append-field/package.json b/node_modules/append-field/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8d6e716433ff4f99e99412f2e63523459dc0f9a8 --- /dev/null +++ b/node_modules/append-field/package.json @@ -0,0 +1,19 @@ +{ + "name": "append-field", + "version": "1.0.0", + "license": "MIT", + "author": "Linus Unnebäck ", + "main": "index.js", + "devDependencies": { + "mocha": "^2.2.4", + "standard": "^6.0.5", + "testdata-w3c-json-form": "^0.2.0" + }, + "scripts": { + "test": "standard && mocha" + }, + "repository": { + "type": "git", + "url": "http://github.com/LinusU/node-append-field.git" + } +} diff --git a/node_modules/append-field/test/forms.js b/node_modules/append-field/test/forms.js new file mode 100644 index 0000000000000000000000000000000000000000..dd6fbc988e8b71f9cc438d5ddf114f8ad704216f --- /dev/null +++ b/node_modules/append-field/test/forms.js @@ -0,0 +1,19 @@ +/* eslint-env mocha */ + +var assert = require('assert') +var appendField = require('../') +var testData = require('testdata-w3c-json-form') + +describe('Append Field', function () { + for (var test of testData) { + it('handles ' + test.name, function () { + var store = Object.create(null) + + for (var field of test.fields) { + appendField(store, field.key, field.value) + } + + assert.deepEqual(store, test.expected) + }) + } +}) diff --git a/node_modules/archiver-utils/LICENSE b/node_modules/archiver-utils/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f12cd49cae3978dcdb337c7bad10842b3412ce59 --- /dev/null +++ b/node_modules/archiver-utils/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2015 Chris Talkington. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/archiver-utils/README.md b/node_modules/archiver-utils/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4de3b9d1a31e4dc02cbadf58e9b35ced611cf13e --- /dev/null +++ b/node_modules/archiver-utils/README.md @@ -0,0 +1,6 @@ +# Archiver Utils + +## Things of Interest +- [Changelog](https://github.com/archiverjs/archiver-utils/releases) +- [Contributing](https://github.com/archiverjs/archiver-utils/blob/master/CONTRIBUTING.md) +- [MIT License](https://github.com/archiverjs/archiver-utils/blob/master/LICENSE) diff --git a/node_modules/archiver-utils/file.js b/node_modules/archiver-utils/file.js new file mode 100644 index 0000000000000000000000000000000000000000..e507bceac6503cf4e4478fe5505c4e0af4c2110d --- /dev/null +++ b/node_modules/archiver-utils/file.js @@ -0,0 +1,209 @@ +/** + * archiver-utils + * + * Copyright (c) 2012-2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-archiver/blob/master/LICENSE-MIT + */ +var fs = require('graceful-fs'); +var path = require('path'); + +var flatten = require('lodash/flatten'); +var difference = require('lodash/difference'); +var union = require('lodash/union'); +var isPlainObject = require('lodash/isPlainObject'); + +var glob = require('glob'); + +var file = module.exports = {}; + +var pathSeparatorRe = /[\/\\]/g; + +// Process specified wildcard glob patterns or filenames against a +// callback, excluding and uniquing files in the result set. +var processPatterns = function(patterns, fn) { + // Filepaths to return. + var result = []; + // Iterate over flattened patterns array. + flatten(patterns).forEach(function(pattern) { + // If the first character is ! it should be omitted + var exclusion = pattern.indexOf('!') === 0; + // If the pattern is an exclusion, remove the ! + if (exclusion) { pattern = pattern.slice(1); } + // Find all matching files for this pattern. + var matches = fn(pattern); + if (exclusion) { + // If an exclusion, remove matching files. + result = difference(result, matches); + } else { + // Otherwise add matching files. + result = union(result, matches); + } + }); + return result; +}; + +// True if the file path exists. +file.exists = function() { + var filepath = path.join.apply(path, arguments); + return fs.existsSync(filepath); +}; + +// Return an array of all file paths that match the given wildcard patterns. +file.expand = function(...args) { + // If the first argument is an options object, save those options to pass + // into the File.prototype.glob.sync method. + var options = isPlainObject(args[0]) ? args.shift() : {}; + // Use the first argument if it's an Array, otherwise convert the arguments + // object to an array and use that. + var patterns = Array.isArray(args[0]) ? args[0] : args; + // Return empty set if there are no patterns or filepaths. + if (patterns.length === 0) { return []; } + // Return all matching filepaths. + var matches = processPatterns(patterns, function(pattern) { + // Find all matching files for this pattern. + return glob.sync(pattern, options); + }); + // Filter result set? + if (options.filter) { + matches = matches.filter(function(filepath) { + filepath = path.join(options.cwd || '', filepath); + try { + if (typeof options.filter === 'function') { + return options.filter(filepath); + } else { + // If the file is of the right type and exists, this should work. + return fs.statSync(filepath)[options.filter](); + } + } catch(e) { + // Otherwise, it's probably not the right type. + return false; + } + }); + } + return matches; +}; + +// Build a multi task "files" object dynamically. +file.expandMapping = function(patterns, destBase, options) { + options = Object.assign({ + rename: function(destBase, destPath) { + return path.join(destBase || '', destPath); + } + }, options); + var files = []; + var fileByDest = {}; + // Find all files matching pattern, using passed-in options. + file.expand(options, patterns).forEach(function(src) { + var destPath = src; + // Flatten? + if (options.flatten) { + destPath = path.basename(destPath); + } + // Change the extension? + if (options.ext) { + destPath = destPath.replace(/(\.[^\/]*)?$/, options.ext); + } + // Generate destination filename. + var dest = options.rename(destBase, destPath, options); + // Prepend cwd to src path if necessary. + if (options.cwd) { src = path.join(options.cwd, src); } + // Normalize filepaths to be unix-style. + dest = dest.replace(pathSeparatorRe, '/'); + src = src.replace(pathSeparatorRe, '/'); + // Map correct src path to dest path. + if (fileByDest[dest]) { + // If dest already exists, push this src onto that dest's src array. + fileByDest[dest].src.push(src); + } else { + // Otherwise create a new src-dest file mapping object. + files.push({ + src: [src], + dest: dest, + }); + // And store a reference for later use. + fileByDest[dest] = files[files.length - 1]; + } + }); + return files; +}; + +// reusing bits of grunt's multi-task source normalization +file.normalizeFilesArray = function(data) { + var files = []; + + data.forEach(function(obj) { + var prop; + if ('src' in obj || 'dest' in obj) { + files.push(obj); + } + }); + + if (files.length === 0) { + return []; + } + + files = _(files).chain().forEach(function(obj) { + if (!('src' in obj) || !obj.src) { return; } + // Normalize .src properties to flattened array. + if (Array.isArray(obj.src)) { + obj.src = flatten(obj.src); + } else { + obj.src = [obj.src]; + } + }).map(function(obj) { + // Build options object, removing unwanted properties. + var expandOptions = Object.assign({}, obj); + delete expandOptions.src; + delete expandOptions.dest; + + // Expand file mappings. + if (obj.expand) { + return file.expandMapping(obj.src, obj.dest, expandOptions).map(function(mapObj) { + // Copy obj properties to result. + var result = Object.assign({}, obj); + // Make a clone of the orig obj available. + result.orig = Object.assign({}, obj); + // Set .src and .dest, processing both as templates. + result.src = mapObj.src; + result.dest = mapObj.dest; + // Remove unwanted properties. + ['expand', 'cwd', 'flatten', 'rename', 'ext'].forEach(function(prop) { + delete result[prop]; + }); + return result; + }); + } + + // Copy obj properties to result, adding an .orig property. + var result = Object.assign({}, obj); + // Make a clone of the orig obj available. + result.orig = Object.assign({}, obj); + + if ('src' in result) { + // Expose an expand-on-demand getter method as .src. + Object.defineProperty(result, 'src', { + enumerable: true, + get: function fn() { + var src; + if (!('result' in fn)) { + src = obj.src; + // If src is an array, flatten it. Otherwise, make it into an array. + src = Array.isArray(src) ? flatten(src) : [src]; + // Expand src files, memoizing result. + fn.result = file.expand(expandOptions, src); + } + return fn.result; + } + }); + } + + if ('dest' in result) { + result.dest = obj.dest; + } + + return result; + }).flatten().value(); + + return files; +}; diff --git a/node_modules/archiver-utils/index.js b/node_modules/archiver-utils/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6da3e1f416057bdfab0c2f78fd2651fe87e7e2e9 --- /dev/null +++ b/node_modules/archiver-utils/index.js @@ -0,0 +1,154 @@ +/** + * archiver-utils + * + * Copyright (c) 2015 Chris Talkington. + * Licensed under the MIT license. + * https://github.com/archiverjs/archiver-utils/blob/master/LICENSE + */ +var fs = require('graceful-fs'); +var path = require('path'); +var lazystream = require('lazystream'); +var normalizePath = require('normalize-path'); +var defaults = require('lodash/defaults'); + +var Stream = require('stream').Stream; +var PassThrough = require('readable-stream').PassThrough; + +var utils = module.exports = {}; +utils.file = require('./file.js'); + +utils.collectStream = function(source, callback) { + var collection = []; + var size = 0; + + source.on('error', callback); + + source.on('data', function(chunk) { + collection.push(chunk); + size += chunk.length; + }); + + source.on('end', function() { + var buf = Buffer.alloc(size); + var offset = 0; + + collection.forEach(function(data) { + data.copy(buf, offset); + offset += data.length; + }); + + callback(null, buf); + }); +}; + +utils.dateify = function(dateish) { + dateish = dateish || new Date(); + + if (dateish instanceof Date) { + dateish = dateish; + } else if (typeof dateish === 'string') { + dateish = new Date(dateish); + } else { + dateish = new Date(); + } + + return dateish; +}; + +// this is slightly different from lodash version +utils.defaults = function(object, source, guard) { + var args = arguments; + args[0] = args[0] || {}; + + return defaults(...args); +}; + +utils.isStream = function(source) { + return source instanceof Stream; +}; + +utils.lazyReadStream = function(filepath) { + return new lazystream.Readable(function() { + return fs.createReadStream(filepath); + }); +}; + +utils.normalizeInputSource = function(source) { + if (source === null) { + return Buffer.alloc(0); + } else if (typeof source === 'string') { + return Buffer.from(source); + } else if (utils.isStream(source)) { + // Always pipe through a PassThrough stream to guarantee pausing the stream if it's already flowing, + // since it will only be processed in a (distant) future iteration of the event loop, and will lose + // data if already flowing now. + return source.pipe(new PassThrough()); + } + + return source; +}; + +utils.sanitizePath = function(filepath) { + return normalizePath(filepath, false).replace(/^\w+:/, '').replace(/^(\.\.\/|\/)+/, ''); +}; + +utils.trailingSlashIt = function(str) { + return str.slice(-1) !== '/' ? str + '/' : str; +}; + +utils.unixifyPath = function(filepath) { + return normalizePath(filepath, false).replace(/^\w+:/, ''); +}; + +utils.walkdir = function(dirpath, base, callback) { + var results = []; + + if (typeof base === 'function') { + callback = base; + base = dirpath; + } + + fs.readdir(dirpath, function(err, list) { + var i = 0; + var file; + var filepath; + + if (err) { + return callback(err); + } + + (function next() { + file = list[i++]; + + if (!file) { + return callback(null, results); + } + + filepath = path.join(dirpath, file); + + fs.stat(filepath, function(err, stats) { + results.push({ + path: filepath, + relative: path.relative(base, filepath).replace(/\\/g, '/'), + stats: stats + }); + + if (stats && stats.isDirectory()) { + utils.walkdir(filepath, base, function(err, res) { + if(err){ + return callback(err); + } + + res.forEach(function(dirEntry) { + results.push(dirEntry); + }); + + next(); + }); + } else { + next(); + } + }); + })(); + }); +}; diff --git a/node_modules/archiver-utils/package.json b/node_modules/archiver-utils/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bd3b05cd70fde45ba6ae65650ae49313ad9d1969 --- /dev/null +++ b/node_modules/archiver-utils/package.json @@ -0,0 +1,50 @@ +{ + "name": "archiver-utils", + "version": "4.0.1", + "license": "MIT", + "description": "utility functions for archiver", + "homepage": "https://github.com/archiverjs/archiver-utils#readme", + "author": { + "name": "Chris Talkington", + "url": "http://christalkington.com/" + }, + "repository": { + "type": "git", + "url": "https://github.com/archiverjs/archiver-utils.git" + }, + "bugs": { + "url": "https://github.com/archiverjs/archiver-utils/issues" + }, + "keywords": [ + "archiver", + "utils" + ], + "main": "index.js", + "files": [ + "index.js", + "file.js" + ], + "engines": { + "node": ">= 12.0.0" + }, + "scripts": { + "test": "mocha --reporter dot" + }, + "dependencies": { + "glob": "^8.0.0", + "graceful-fs": "^4.2.0", + "lazystream": "^1.0.0", + "lodash": "^4.17.15", + "normalize-path": "^3.0.0", + "readable-stream": "^3.6.0" + }, + "devDependencies": { + "chai": "4.3.8", + "mkdirp": "3.0.1", + "mocha": "9.2.2", + "rimraf": "3.0.2" + }, + "publishConfig": { + "registry": "https://registry.npmjs.org/" + } +} diff --git a/node_modules/archiver/LICENSE b/node_modules/archiver/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..88caf8710bef80b7fcd3801e0ff0fdaaa1d75c86 --- /dev/null +++ b/node_modules/archiver/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2012-2014 Chris Talkington, contributors. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/archiver/README.md b/node_modules/archiver/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2ee7c171acec44fc8a770464207f75e9f540aee6 --- /dev/null +++ b/node_modules/archiver/README.md @@ -0,0 +1,92 @@ +# Archiver + +A streaming interface for archive generation + +Visit the [API documentation](https://www.archiverjs.com/) for a list of all methods available. + +## Install + +```bash +npm install archiver --save +``` + +## Quick Start + +```js +// require modules +const fs = require('fs'); +const archiver = require('archiver'); + +// create a file to stream archive data to. +const output = fs.createWriteStream(__dirname + '/example.zip'); +const archive = archiver('zip', { + zlib: { level: 9 } // Sets the compression level. +}); + +// listen for all archive data to be written +// 'close' event is fired only when a file descriptor is involved +output.on('close', function() { + console.log(archive.pointer() + ' total bytes'); + console.log('archiver has been finalized and the output file descriptor has closed.'); +}); + +// This event is fired when the data source is drained no matter what was the data source. +// It is not part of this library but rather from the NodeJS Stream API. +// @see: https://nodejs.org/api/stream.html#stream_event_end +output.on('end', function() { + console.log('Data has been drained'); +}); + +// good practice to catch warnings (ie stat failures and other non-blocking errors) +archive.on('warning', function(err) { + if (err.code === 'ENOENT') { + // log warning + } else { + // throw error + throw err; + } +}); + +// good practice to catch this error explicitly +archive.on('error', function(err) { + throw err; +}); + +// pipe archive data to the file +archive.pipe(output); + +// append a file from stream +const file1 = __dirname + '/file1.txt'; +archive.append(fs.createReadStream(file1), { name: 'file1.txt' }); + +// append a file from string +archive.append('string cheese!', { name: 'file2.txt' }); + +// append a file from buffer +const buffer3 = Buffer.from('buff it!'); +archive.append(buffer3, { name: 'file3.txt' }); + +// append a file +archive.file('file1.txt', { name: 'file4.txt' }); + +// append files from a sub-directory and naming it `new-subdir` within the archive +archive.directory('subdir/', 'new-subdir'); + +// append files from a sub-directory, putting its contents at the root of archive +archive.directory('subdir/', false); + +// append files from a glob pattern +archive.glob('file*.txt', {cwd:__dirname}); + +// finalize the archive (ie we are done appending files but streams have to finish yet) +// 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand +archive.finalize(); +``` + +## Formats + +Archiver ships with out of the box support for TAR and ZIP archives. + +You can register additional formats with `registerFormat`. + +You can check if format already exists before to register a new one with `isRegisteredFormat`. diff --git a/node_modules/archiver/index.js b/node_modules/archiver/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0996daefb22b5c0ea2f51e11358f218dab36ef7e --- /dev/null +++ b/node_modules/archiver/index.js @@ -0,0 +1,84 @@ +/** + * Archiver Vending + * + * @ignore + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ +var Archiver = require('./lib/core'); + +var formats = {}; + +/** + * Dispenses a new Archiver instance. + * + * @constructor + * @param {String} format The archive format to use. + * @param {Object} options See [Archiver]{@link Archiver} + * @return {Archiver} + */ +var vending = function(format, options) { + return vending.create(format, options); +}; + +/** + * Creates a new Archiver instance. + * + * @param {String} format The archive format to use. + * @param {Object} options See [Archiver]{@link Archiver} + * @return {Archiver} + */ +vending.create = function(format, options) { + if (formats[format]) { + var instance = new Archiver(format, options); + instance.setFormat(format); + instance.setModule(new formats[format](options)); + + return instance; + } else { + throw new Error('create(' + format + '): format not registered'); + } +}; + +/** + * Registers a format for use with archiver. + * + * @param {String} format The name of the format. + * @param {Function} module The function for archiver to interact with. + * @return void + */ +vending.registerFormat = function(format, module) { + if (formats[format]) { + throw new Error('register(' + format + '): format already registered'); + } + + if (typeof module !== 'function') { + throw new Error('register(' + format + '): format module invalid'); + } + + if (typeof module.prototype.append !== 'function' || typeof module.prototype.finalize !== 'function') { + throw new Error('register(' + format + '): format module missing methods'); + } + + formats[format] = module; +}; + +/** + * Check if the format is already registered. + * + * @param {String} format the name of the format. + * @return boolean + */ +vending.isRegisteredFormat = function (format) { + if (formats[format]) { + return true; + } + + return false; +}; + +vending.registerFormat('zip', require('./lib/plugins/zip')); +vending.registerFormat('tar', require('./lib/plugins/tar')); +vending.registerFormat('json', require('./lib/plugins/json')); + +module.exports = vending; \ No newline at end of file diff --git a/node_modules/archiver/lib/core.js b/node_modules/archiver/lib/core.js new file mode 100644 index 0000000000000000000000000000000000000000..7c0a74d7ff29266f1a492f41129bb3cf1adb0efd --- /dev/null +++ b/node_modules/archiver/lib/core.js @@ -0,0 +1,974 @@ +/** + * Archiver Core + * + * @ignore + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ +var fs = require('fs'); +var glob = require('readdir-glob'); +var async = require('async'); +var path = require('path'); +var util = require('archiver-utils'); + +var inherits = require('util').inherits; +var ArchiverError = require('./error'); +var Transform = require('readable-stream').Transform; + +var win32 = process.platform === 'win32'; + +/** + * @constructor + * @param {String} format The archive format to use. + * @param {(CoreOptions|TransformOptions)} options See also {@link ZipOptions} and {@link TarOptions}. + */ +var Archiver = function(format, options) { + if (!(this instanceof Archiver)) { + return new Archiver(format, options); + } + + if (typeof format !== 'string') { + options = format; + format = 'zip'; + } + + options = this.options = util.defaults(options, { + highWaterMark: 1024 * 1024, + statConcurrency: 4 + }); + + Transform.call(this, options); + + this._format = false; + this._module = false; + this._pending = 0; + this._pointer = 0; + + this._entriesCount = 0; + this._entriesProcessedCount = 0; + this._fsEntriesTotalBytes = 0; + this._fsEntriesProcessedBytes = 0; + + this._queue = async.queue(this._onQueueTask.bind(this), 1); + this._queue.drain(this._onQueueDrain.bind(this)); + + this._statQueue = async.queue(this._onStatQueueTask.bind(this), options.statConcurrency); + this._statQueue.drain(this._onQueueDrain.bind(this)); + + this._state = { + aborted: false, + finalize: false, + finalizing: false, + finalized: false, + modulePiped: false + }; + + this._streams = []; +}; + +inherits(Archiver, Transform); + +/** + * Internal logic for `abort`. + * + * @private + * @return void + */ +Archiver.prototype._abort = function() { + this._state.aborted = true; + this._queue.kill(); + this._statQueue.kill(); + + if (this._queue.idle()) { + this._shutdown(); + } +}; + +/** + * Internal helper for appending files. + * + * @private + * @param {String} filepath The source filepath. + * @param {EntryData} data The entry data. + * @return void + */ +Archiver.prototype._append = function(filepath, data) { + data = data || {}; + + var task = { + source: null, + filepath: filepath + }; + + if (!data.name) { + data.name = filepath; + } + + data.sourcePath = filepath; + task.data = data; + this._entriesCount++; + + if (data.stats && data.stats instanceof fs.Stats) { + task = this._updateQueueTaskWithStats(task, data.stats); + if (task) { + if (data.stats.size) { + this._fsEntriesTotalBytes += data.stats.size; + } + + this._queue.push(task); + } + } else { + this._statQueue.push(task); + } +}; + +/** + * Internal logic for `finalize`. + * + * @private + * @return void + */ +Archiver.prototype._finalize = function() { + if (this._state.finalizing || this._state.finalized || this._state.aborted) { + return; + } + + this._state.finalizing = true; + + this._moduleFinalize(); + + this._state.finalizing = false; + this._state.finalized = true; +}; + +/** + * Checks the various state variables to determine if we can `finalize`. + * + * @private + * @return {Boolean} + */ +Archiver.prototype._maybeFinalize = function() { + if (this._state.finalizing || this._state.finalized || this._state.aborted) { + return false; + } + + if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { + this._finalize(); + return true; + } + + return false; +}; + +/** + * Appends an entry to the module. + * + * @private + * @fires Archiver#entry + * @param {(Buffer|Stream)} source + * @param {EntryData} data + * @param {Function} callback + * @return void + */ +Archiver.prototype._moduleAppend = function(source, data, callback) { + if (this._state.aborted) { + callback(); + return; + } + + this._module.append(source, data, function(err) { + this._task = null; + + if (this._state.aborted) { + this._shutdown(); + return; + } + + if (err) { + this.emit('error', err); + setImmediate(callback); + return; + } + + /** + * Fires when the entry's input has been processed and appended to the archive. + * + * @event Archiver#entry + * @type {EntryData} + */ + this.emit('entry', data); + this._entriesProcessedCount++; + + if (data.stats && data.stats.size) { + this._fsEntriesProcessedBytes += data.stats.size; + } + + /** + * @event Archiver#progress + * @type {ProgressData} + */ + this.emit('progress', { + entries: { + total: this._entriesCount, + processed: this._entriesProcessedCount + }, + fs: { + totalBytes: this._fsEntriesTotalBytes, + processedBytes: this._fsEntriesProcessedBytes + } + }); + + setImmediate(callback); + }.bind(this)); +}; + +/** + * Finalizes the module. + * + * @private + * @return void + */ +Archiver.prototype._moduleFinalize = function() { + if (typeof this._module.finalize === 'function') { + this._module.finalize(); + } else if (typeof this._module.end === 'function') { + this._module.end(); + } else { + this.emit('error', new ArchiverError('NOENDMETHOD')); + } +}; + +/** + * Pipes the module to our internal stream with error bubbling. + * + * @private + * @return void + */ +Archiver.prototype._modulePipe = function() { + this._module.on('error', this._onModuleError.bind(this)); + this._module.pipe(this); + this._state.modulePiped = true; +}; + +/** + * Determines if the current module supports a defined feature. + * + * @private + * @param {String} key + * @return {Boolean} + */ +Archiver.prototype._moduleSupports = function(key) { + if (!this._module.supports || !this._module.supports[key]) { + return false; + } + + return this._module.supports[key]; +}; + +/** + * Unpipes the module from our internal stream. + * + * @private + * @return void + */ +Archiver.prototype._moduleUnpipe = function() { + this._module.unpipe(this); + this._state.modulePiped = false; +}; + +/** + * Normalizes entry data with fallbacks for key properties. + * + * @private + * @param {Object} data + * @param {fs.Stats} stats + * @return {Object} + */ +Archiver.prototype._normalizeEntryData = function(data, stats) { + data = util.defaults(data, { + type: 'file', + name: null, + date: null, + mode: null, + prefix: null, + sourcePath: null, + stats: false + }); + + if (stats && data.stats === false) { + data.stats = stats; + } + + var isDir = data.type === 'directory'; + + if (data.name) { + if (typeof data.prefix === 'string' && '' !== data.prefix) { + data.name = data.prefix + '/' + data.name; + data.prefix = null; + } + + data.name = util.sanitizePath(data.name); + + if (data.type !== 'symlink' && data.name.slice(-1) === '/') { + isDir = true; + data.type = 'directory'; + } else if (isDir) { + data.name += '/'; + } + } + + // 511 === 0777; 493 === 0755; 438 === 0666; 420 === 0644 + if (typeof data.mode === 'number') { + if (win32) { + data.mode &= 511; + } else { + data.mode &= 4095 + } + } else if (data.stats && data.mode === null) { + if (win32) { + data.mode = data.stats.mode & 511; + } else { + data.mode = data.stats.mode & 4095; + } + + // stat isn't reliable on windows; force 0755 for dir + if (win32 && isDir) { + data.mode = 493; + } + } else if (data.mode === null) { + data.mode = isDir ? 493 : 420; + } + + if (data.stats && data.date === null) { + data.date = data.stats.mtime; + } else { + data.date = util.dateify(data.date); + } + + return data; +}; + +/** + * Error listener that re-emits error on to our internal stream. + * + * @private + * @param {Error} err + * @return void + */ +Archiver.prototype._onModuleError = function(err) { + /** + * @event Archiver#error + * @type {ErrorData} + */ + this.emit('error', err); +}; + +/** + * Checks the various state variables after queue has drained to determine if + * we need to `finalize`. + * + * @private + * @return void + */ +Archiver.prototype._onQueueDrain = function() { + if (this._state.finalizing || this._state.finalized || this._state.aborted) { + return; + } + + if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { + this._finalize(); + } +}; + +/** + * Appends each queue task to the module. + * + * @private + * @param {Object} task + * @param {Function} callback + * @return void + */ +Archiver.prototype._onQueueTask = function(task, callback) { + var fullCallback = () => { + if(task.data.callback) { + task.data.callback(); + } + callback(); + } + + if (this._state.finalizing || this._state.finalized || this._state.aborted) { + fullCallback(); + return; + } + + this._task = task; + this._moduleAppend(task.source, task.data, fullCallback); +}; + +/** + * Performs a file stat and reinjects the task back into the queue. + * + * @private + * @param {Object} task + * @param {Function} callback + * @return void + */ +Archiver.prototype._onStatQueueTask = function(task, callback) { + if (this._state.finalizing || this._state.finalized || this._state.aborted) { + callback(); + return; + } + + fs.lstat(task.filepath, function(err, stats) { + if (this._state.aborted) { + setImmediate(callback); + return; + } + + if (err) { + this._entriesCount--; + + /** + * @event Archiver#warning + * @type {ErrorData} + */ + this.emit('warning', err); + setImmediate(callback); + return; + } + + task = this._updateQueueTaskWithStats(task, stats); + + if (task) { + if (stats.size) { + this._fsEntriesTotalBytes += stats.size; + } + + this._queue.push(task); + } + + setImmediate(callback); + }.bind(this)); +}; + +/** + * Unpipes the module and ends our internal stream. + * + * @private + * @return void + */ +Archiver.prototype._shutdown = function() { + this._moduleUnpipe(); + this.end(); +}; + +/** + * Tracks the bytes emitted by our internal stream. + * + * @private + * @param {Buffer} chunk + * @param {String} encoding + * @param {Function} callback + * @return void + */ +Archiver.prototype._transform = function(chunk, encoding, callback) { + if (chunk) { + this._pointer += chunk.length; + } + + callback(null, chunk); +}; + +/** + * Updates and normalizes a queue task using stats data. + * + * @private + * @param {Object} task + * @param {fs.Stats} stats + * @return {Object} + */ +Archiver.prototype._updateQueueTaskWithStats = function(task, stats) { + if (stats.isFile()) { + task.data.type = 'file'; + task.data.sourceType = 'stream'; + task.source = util.lazyReadStream(task.filepath); + } else if (stats.isDirectory() && this._moduleSupports('directory')) { + task.data.name = util.trailingSlashIt(task.data.name); + task.data.type = 'directory'; + task.data.sourcePath = util.trailingSlashIt(task.filepath); + task.data.sourceType = 'buffer'; + task.source = Buffer.concat([]); + } else if (stats.isSymbolicLink() && this._moduleSupports('symlink')) { + var linkPath = fs.readlinkSync(task.filepath); + var dirName = path.dirname(task.filepath); + task.data.type = 'symlink'; + task.data.linkname = path.relative(dirName, path.resolve(dirName, linkPath)); + task.data.sourceType = 'buffer'; + task.source = Buffer.concat([]); + } else { + if (stats.isDirectory()) { + this.emit('warning', new ArchiverError('DIRECTORYNOTSUPPORTED', task.data)); + } else if (stats.isSymbolicLink()) { + this.emit('warning', new ArchiverError('SYMLINKNOTSUPPORTED', task.data)); + } else { + this.emit('warning', new ArchiverError('ENTRYNOTSUPPORTED', task.data)); + } + + return null; + } + + task.data = this._normalizeEntryData(task.data, stats); + + return task; +}; + +/** + * Aborts the archiving process, taking a best-effort approach, by: + * + * - removing any pending queue tasks + * - allowing any active queue workers to finish + * - detaching internal module pipes + * - ending both sides of the Transform stream + * + * It will NOT drain any remaining sources. + * + * @return {this} + */ +Archiver.prototype.abort = function() { + if (this._state.aborted || this._state.finalized) { + return this; + } + + this._abort(); + + return this; +}; + +/** + * Appends an input source (text string, buffer, or stream) to the instance. + * + * When the instance has received, processed, and emitted the input, the `entry` + * event is fired. + * + * @fires Archiver#entry + * @param {(Buffer|Stream|String)} source The input source. + * @param {EntryData} data See also {@link ZipEntryData} and {@link TarEntryData}. + * @return {this} + */ +Archiver.prototype.append = function(source, data) { + if (this._state.finalize || this._state.aborted) { + this.emit('error', new ArchiverError('QUEUECLOSED')); + return this; + } + + data = this._normalizeEntryData(data); + + if (typeof data.name !== 'string' || data.name.length === 0) { + this.emit('error', new ArchiverError('ENTRYNAMEREQUIRED')); + return this; + } + + if (data.type === 'directory' && !this._moduleSupports('directory')) { + this.emit('error', new ArchiverError('DIRECTORYNOTSUPPORTED', { name: data.name })); + return this; + } + + source = util.normalizeInputSource(source); + + if (Buffer.isBuffer(source)) { + data.sourceType = 'buffer'; + } else if (util.isStream(source)) { + data.sourceType = 'stream'; + } else { + this.emit('error', new ArchiverError('INPUTSTEAMBUFFERREQUIRED', { name: data.name })); + return this; + } + + this._entriesCount++; + this._queue.push({ + data: data, + source: source + }); + + return this; +}; + +/** + * Appends a directory and its files, recursively, given its dirpath. + * + * @param {String} dirpath The source directory path. + * @param {String} destpath The destination path within the archive. + * @param {(EntryData|Function)} data See also [ZipEntryData]{@link ZipEntryData} and + * [TarEntryData]{@link TarEntryData}. + * @return {this} + */ +Archiver.prototype.directory = function(dirpath, destpath, data) { + if (this._state.finalize || this._state.aborted) { + this.emit('error', new ArchiverError('QUEUECLOSED')); + return this; + } + + if (typeof dirpath !== 'string' || dirpath.length === 0) { + this.emit('error', new ArchiverError('DIRECTORYDIRPATHREQUIRED')); + return this; + } + + this._pending++; + + if (destpath === false) { + destpath = ''; + } else if (typeof destpath !== 'string'){ + destpath = dirpath; + } + + var dataFunction = false; + if (typeof data === 'function') { + dataFunction = data; + data = {}; + } else if (typeof data !== 'object') { + data = {}; + } + + var globOptions = { + stat: true, + dot: true + }; + + function onGlobEnd() { + this._pending--; + this._maybeFinalize(); + } + + function onGlobError(err) { + this.emit('error', err); + } + + function onGlobMatch(match){ + globber.pause(); + + var ignoreMatch = false; + var entryData = Object.assign({}, data); + entryData.name = match.relative; + entryData.prefix = destpath; + entryData.stats = match.stat; + entryData.callback = globber.resume.bind(globber); + + try { + if (dataFunction) { + entryData = dataFunction(entryData); + + if (entryData === false) { + ignoreMatch = true; + } else if (typeof entryData !== 'object') { + throw new ArchiverError('DIRECTORYFUNCTIONINVALIDDATA', { dirpath: dirpath }); + } + } + } catch(e) { + this.emit('error', e); + return; + } + + if (ignoreMatch) { + globber.resume(); + return; + } + + this._append(match.absolute, entryData); + } + + var globber = glob(dirpath, globOptions); + globber.on('error', onGlobError.bind(this)); + globber.on('match', onGlobMatch.bind(this)); + globber.on('end', onGlobEnd.bind(this)); + + return this; +}; + +/** + * Appends a file given its filepath using a + * [lazystream]{@link https://github.com/jpommerening/node-lazystream} wrapper to + * prevent issues with open file limits. + * + * When the instance has received, processed, and emitted the file, the `entry` + * event is fired. + * + * @param {String} filepath The source filepath. + * @param {EntryData} data See also [ZipEntryData]{@link ZipEntryData} and + * [TarEntryData]{@link TarEntryData}. + * @return {this} + */ +Archiver.prototype.file = function(filepath, data) { + if (this._state.finalize || this._state.aborted) { + this.emit('error', new ArchiverError('QUEUECLOSED')); + return this; + } + + if (typeof filepath !== 'string' || filepath.length === 0) { + this.emit('error', new ArchiverError('FILEFILEPATHREQUIRED')); + return this; + } + + this._append(filepath, data); + + return this; +}; + +/** + * Appends multiple files that match a glob pattern. + * + * @param {String} pattern The [glob pattern]{@link https://github.com/isaacs/minimatch} to match. + * @param {Object} options See [node-readdir-glob]{@link https://github.com/yqnn/node-readdir-glob#options}. + * @param {EntryData} data See also [ZipEntryData]{@link ZipEntryData} and + * [TarEntryData]{@link TarEntryData}. + * @return {this} + */ +Archiver.prototype.glob = function(pattern, options, data) { + this._pending++; + + options = util.defaults(options, { + stat: true, + pattern: pattern + }); + + function onGlobEnd() { + this._pending--; + this._maybeFinalize(); + } + + function onGlobError(err) { + this.emit('error', err); + } + + function onGlobMatch(match){ + globber.pause(); + var entryData = Object.assign({}, data); + entryData.callback = globber.resume.bind(globber); + entryData.stats = match.stat; + entryData.name = match.relative; + + this._append(match.absolute, entryData); + } + + var globber = glob(options.cwd || '.', options); + globber.on('error', onGlobError.bind(this)); + globber.on('match', onGlobMatch.bind(this)); + globber.on('end', onGlobEnd.bind(this)); + + return this; +}; + +/** + * Finalizes the instance and prevents further appending to the archive + * structure (queue will continue til drained). + * + * The `end`, `close` or `finish` events on the destination stream may fire + * right after calling this method so you should set listeners beforehand to + * properly detect stream completion. + * + * @return {Promise} + */ +Archiver.prototype.finalize = function() { + if (this._state.aborted) { + var abortedError = new ArchiverError('ABORTED'); + this.emit('error', abortedError); + return Promise.reject(abortedError); + } + + if (this._state.finalize) { + var finalizingError = new ArchiverError('FINALIZING'); + this.emit('error', finalizingError); + return Promise.reject(finalizingError); + } + + this._state.finalize = true; + + if (this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { + this._finalize(); + } + + var self = this; + + return new Promise(function(resolve, reject) { + var errored; + + self._module.on('end', function() { + if (!errored) { + resolve(); + } + }) + + self._module.on('error', function(err) { + errored = true; + reject(err); + }) + }) +}; + +/** + * Sets the module format name used for archiving. + * + * @param {String} format The name of the format. + * @return {this} + */ +Archiver.prototype.setFormat = function(format) { + if (this._format) { + this.emit('error', new ArchiverError('FORMATSET')); + return this; + } + + this._format = format; + + return this; +}; + +/** + * Sets the module used for archiving. + * + * @param {Function} module The function for archiver to interact with. + * @return {this} + */ +Archiver.prototype.setModule = function(module) { + if (this._state.aborted) { + this.emit('error', new ArchiverError('ABORTED')); + return this; + } + + if (this._state.module) { + this.emit('error', new ArchiverError('MODULESET')); + return this; + } + + this._module = module; + this._modulePipe(); + + return this; +}; + +/** + * Appends a symlink to the instance. + * + * This does NOT interact with filesystem and is used for programmatically creating symlinks. + * + * @param {String} filepath The symlink path (within archive). + * @param {String} target The target path (within archive). + * @param {Number} mode Sets the entry permissions. + * @return {this} + */ +Archiver.prototype.symlink = function(filepath, target, mode) { + if (this._state.finalize || this._state.aborted) { + this.emit('error', new ArchiverError('QUEUECLOSED')); + return this; + } + + if (typeof filepath !== 'string' || filepath.length === 0) { + this.emit('error', new ArchiverError('SYMLINKFILEPATHREQUIRED')); + return this; + } + + if (typeof target !== 'string' || target.length === 0) { + this.emit('error', new ArchiverError('SYMLINKTARGETREQUIRED', { filepath: filepath })); + return this; + } + + if (!this._moduleSupports('symlink')) { + this.emit('error', new ArchiverError('SYMLINKNOTSUPPORTED', { filepath: filepath })); + return this; + } + + var data = {}; + data.type = 'symlink'; + data.name = filepath.replace(/\\/g, '/'); + data.linkname = target.replace(/\\/g, '/'); + data.sourceType = 'buffer'; + + if (typeof mode === "number") { + data.mode = mode; + } + + this._entriesCount++; + this._queue.push({ + data: data, + source: Buffer.concat([]) + }); + + return this; +}; + +/** + * Returns the current length (in bytes) that has been emitted. + * + * @return {Number} + */ +Archiver.prototype.pointer = function() { + return this._pointer; +}; + +/** + * Middleware-like helper that has yet to be fully implemented. + * + * @private + * @param {Function} plugin + * @return {this} + */ +Archiver.prototype.use = function(plugin) { + this._streams.push(plugin); + return this; +}; + +module.exports = Archiver; + +/** + * @typedef {Object} CoreOptions + * @global + * @property {Number} [statConcurrency=4] Sets the number of workers used to + * process the internal fs stat queue. + */ + +/** + * @typedef {Object} TransformOptions + * @property {Boolean} [allowHalfOpen=true] If set to false, then the stream + * will automatically end the readable side when the writable side ends and vice + * versa. + * @property {Boolean} [readableObjectMode=false] Sets objectMode for readable + * side of the stream. Has no effect if objectMode is true. + * @property {Boolean} [writableObjectMode=false] Sets objectMode for writable + * side of the stream. Has no effect if objectMode is true. + * @property {Boolean} [decodeStrings=true] Whether or not to decode strings + * into Buffers before passing them to _write(). `Writable` + * @property {String} [encoding=NULL] If specified, then buffers will be decoded + * to strings using the specified encoding. `Readable` + * @property {Number} [highWaterMark=16kb] The maximum number of bytes to store + * in the internal buffer before ceasing to read from the underlying resource. + * `Readable` `Writable` + * @property {Boolean} [objectMode=false] Whether this stream should behave as a + * stream of objects. Meaning that stream.read(n) returns a single value instead + * of a Buffer of size n. `Readable` `Writable` + */ + +/** + * @typedef {Object} EntryData + * @property {String} name Sets the entry name including internal path. + * @property {(String|Date)} [date=NOW()] Sets the entry date. + * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions. + * @property {String} [prefix] Sets a path prefix for the entry name. Useful + * when working with methods like `directory` or `glob`. + * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing + * for reduction of fs stat calls when stat data is already known. + */ + +/** + * @typedef {Object} ErrorData + * @property {String} message The message of the error. + * @property {String} code The error code assigned to this error. + * @property {String} data Additional data provided for reporting or debugging (where available). + */ + +/** + * @typedef {Object} ProgressData + * @property {Object} entries + * @property {Number} entries.total Number of entries that have been appended. + * @property {Number} entries.processed Number of entries that have been processed. + * @property {Object} fs + * @property {Number} fs.totalBytes Number of bytes that have been appended. Calculated asynchronously and might not be accurate: it growth while entries are added. (based on fs.Stats) + * @property {Number} fs.processedBytes Number of bytes that have been processed. (based on fs.Stats) + */ diff --git a/node_modules/archiver/lib/error.js b/node_modules/archiver/lib/error.js new file mode 100644 index 0000000000000000000000000000000000000000..6bcb0ae1a788b4d7b704966846e38ba17794126b --- /dev/null +++ b/node_modules/archiver/lib/error.js @@ -0,0 +1,40 @@ +/** + * Archiver Core + * + * @ignore + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ + +var util = require('util'); + +const ERROR_CODES = { + 'ABORTED': 'archive was aborted', + 'DIRECTORYDIRPATHREQUIRED': 'diretory dirpath argument must be a non-empty string value', + 'DIRECTORYFUNCTIONINVALIDDATA': 'invalid data returned by directory custom data function', + 'ENTRYNAMEREQUIRED': 'entry name must be a non-empty string value', + 'FILEFILEPATHREQUIRED': 'file filepath argument must be a non-empty string value', + 'FINALIZING': 'archive already finalizing', + 'QUEUECLOSED': 'queue closed', + 'NOENDMETHOD': 'no suitable finalize/end method defined by module', + 'DIRECTORYNOTSUPPORTED': 'support for directory entries not defined by module', + 'FORMATSET': 'archive format already set', + 'INPUTSTEAMBUFFERREQUIRED': 'input source must be valid Stream or Buffer instance', + 'MODULESET': 'module already set', + 'SYMLINKNOTSUPPORTED': 'support for symlink entries not defined by module', + 'SYMLINKFILEPATHREQUIRED': 'symlink filepath argument must be a non-empty string value', + 'SYMLINKTARGETREQUIRED': 'symlink target argument must be a non-empty string value', + 'ENTRYNOTSUPPORTED': 'entry not supported' +}; + +function ArchiverError(code, data) { + Error.captureStackTrace(this, this.constructor); + //this.name = this.constructor.name; + this.message = ERROR_CODES[code] || code; + this.code = code; + this.data = data; +} + +util.inherits(ArchiverError, Error); + +exports = module.exports = ArchiverError; \ No newline at end of file diff --git a/node_modules/archiver/lib/plugins/json.js b/node_modules/archiver/lib/plugins/json.js new file mode 100644 index 0000000000000000000000000000000000000000..caf63de9475abf200eb57af32b313e1751ad292b --- /dev/null +++ b/node_modules/archiver/lib/plugins/json.js @@ -0,0 +1,110 @@ +/** + * JSON Format Plugin + * + * @module plugins/json + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ +var inherits = require('util').inherits; +var Transform = require('readable-stream').Transform; + +var crc32 = require('buffer-crc32'); +var util = require('archiver-utils'); + +/** + * @constructor + * @param {(JsonOptions|TransformOptions)} options + */ +var Json = function(options) { + if (!(this instanceof Json)) { + return new Json(options); + } + + options = this.options = util.defaults(options, {}); + + Transform.call(this, options); + + this.supports = { + directory: true, + symlink: true + }; + + this.files = []; +}; + +inherits(Json, Transform); + +/** + * [_transform description] + * + * @private + * @param {Buffer} chunk + * @param {String} encoding + * @param {Function} callback + * @return void + */ +Json.prototype._transform = function(chunk, encoding, callback) { + callback(null, chunk); +}; + +/** + * [_writeStringified description] + * + * @private + * @return void + */ +Json.prototype._writeStringified = function() { + var fileString = JSON.stringify(this.files); + this.write(fileString); +}; + +/** + * [append description] + * + * @param {(Buffer|Stream)} source + * @param {EntryData} data + * @param {Function} callback + * @return void + */ +Json.prototype.append = function(source, data, callback) { + var self = this; + + data.crc32 = 0; + + function onend(err, sourceBuffer) { + if (err) { + callback(err); + return; + } + + data.size = sourceBuffer.length || 0; + data.crc32 = crc32.unsigned(sourceBuffer); + + self.files.push(data); + + callback(null, data); + } + + if (data.sourceType === 'buffer') { + onend(null, source); + } else if (data.sourceType === 'stream') { + util.collectStream(source, onend); + } +}; + +/** + * [finalize description] + * + * @return void + */ +Json.prototype.finalize = function() { + this._writeStringified(); + this.end(); +}; + +module.exports = Json; + +/** + * @typedef {Object} JsonOptions + * @global + */ diff --git a/node_modules/archiver/lib/plugins/tar.js b/node_modules/archiver/lib/plugins/tar.js new file mode 100644 index 0000000000000000000000000000000000000000..3a17009004d15ed72180d9a2e82cfb726fe33107 --- /dev/null +++ b/node_modules/archiver/lib/plugins/tar.js @@ -0,0 +1,167 @@ +/** + * TAR Format Plugin + * + * @module plugins/tar + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ +var zlib = require('zlib'); + +var engine = require('tar-stream'); +var util = require('archiver-utils'); + +/** + * @constructor + * @param {TarOptions} options + */ +var Tar = function(options) { + if (!(this instanceof Tar)) { + return new Tar(options); + } + + options = this.options = util.defaults(options, { + gzip: false + }); + + if (typeof options.gzipOptions !== 'object') { + options.gzipOptions = {}; + } + + this.supports = { + directory: true, + symlink: true + }; + + this.engine = engine.pack(options); + this.compressor = false; + + if (options.gzip) { + this.compressor = zlib.createGzip(options.gzipOptions); + this.compressor.on('error', this._onCompressorError.bind(this)); + } +}; + +/** + * [_onCompressorError description] + * + * @private + * @param {Error} err + * @return void + */ +Tar.prototype._onCompressorError = function(err) { + this.engine.emit('error', err); +}; + +/** + * [append description] + * + * @param {(Buffer|Stream)} source + * @param {TarEntryData} data + * @param {Function} callback + * @return void + */ +Tar.prototype.append = function(source, data, callback) { + var self = this; + + data.mtime = data.date; + + function append(err, sourceBuffer) { + if (err) { + callback(err); + return; + } + + self.engine.entry(data, sourceBuffer, function(err) { + callback(err, data); + }); + } + + if (data.sourceType === 'buffer') { + append(null, source); + } else if (data.sourceType === 'stream' && data.stats) { + data.size = data.stats.size; + + var entry = self.engine.entry(data, function(err) { + callback(err, data); + }); + + source.pipe(entry); + } else if (data.sourceType === 'stream') { + util.collectStream(source, append); + } +}; + +/** + * [finalize description] + * + * @return void + */ +Tar.prototype.finalize = function() { + this.engine.finalize(); +}; + +/** + * [on description] + * + * @return this.engine + */ +Tar.prototype.on = function() { + return this.engine.on.apply(this.engine, arguments); +}; + +/** + * [pipe description] + * + * @param {String} destination + * @param {Object} options + * @return this.engine + */ +Tar.prototype.pipe = function(destination, options) { + if (this.compressor) { + return this.engine.pipe.apply(this.engine, [this.compressor]).pipe(destination, options); + } else { + return this.engine.pipe.apply(this.engine, arguments); + } +}; + +/** + * [unpipe description] + * + * @return this.engine + */ +Tar.prototype.unpipe = function() { + if (this.compressor) { + return this.compressor.unpipe.apply(this.compressor, arguments); + } else { + return this.engine.unpipe.apply(this.engine, arguments); + } +}; + +module.exports = Tar; + +/** + * @typedef {Object} TarOptions + * @global + * @property {Boolean} [gzip=false] Compress the tar archive using gzip. + * @property {Object} [gzipOptions] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} + * to control compression. + * @property {*} [*] See [tar-stream]{@link https://github.com/mafintosh/tar-stream} documentation for additional properties. + */ + +/** + * @typedef {Object} TarEntryData + * @global + * @property {String} name Sets the entry name including internal path. + * @property {(String|Date)} [date=NOW()] Sets the entry date. + * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions. + * @property {String} [prefix] Sets a path prefix for the entry name. Useful + * when working with methods like `directory` or `glob`. + * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing + * for reduction of fs stat calls when stat data is already known. + */ + +/** + * TarStream Module + * @external TarStream + * @see {@link https://github.com/mafintosh/tar-stream} + */ diff --git a/node_modules/archiver/lib/plugins/zip.js b/node_modules/archiver/lib/plugins/zip.js new file mode 100644 index 0000000000000000000000000000000000000000..df6f07432814b803056d6bde963a2a6281490c56 --- /dev/null +++ b/node_modules/archiver/lib/plugins/zip.js @@ -0,0 +1,120 @@ +/** + * ZIP Format Plugin + * + * @module plugins/zip + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ +var engine = require('zip-stream'); +var util = require('archiver-utils'); + +/** + * @constructor + * @param {ZipOptions} [options] + * @param {String} [options.comment] Sets the zip archive comment. + * @param {Boolean} [options.forceLocalTime=false] Forces the archive to contain local file times instead of UTC. + * @param {Boolean} [options.forceZip64=false] Forces the archive to contain ZIP64 headers. + * @param {Boolean} [options.namePrependSlash=false] Prepends a forward slash to archive file paths. + * @param {Boolean} [options.store=false] Sets the compression method to STORE. + * @param {Object} [options.zlib] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} + */ +var Zip = function(options) { + if (!(this instanceof Zip)) { + return new Zip(options); + } + + options = this.options = util.defaults(options, { + comment: '', + forceUTC: false, + namePrependSlash: false, + store: false + }); + + this.supports = { + directory: true, + symlink: true + }; + + this.engine = new engine(options); +}; + +/** + * @param {(Buffer|Stream)} source + * @param {ZipEntryData} data + * @param {String} data.name Sets the entry name including internal path. + * @param {(String|Date)} [data.date=NOW()] Sets the entry date. + * @param {Number} [data.mode=D:0755/F:0644] Sets the entry permissions. + * @param {String} [data.prefix] Sets a path prefix for the entry name. Useful + * when working with methods like `directory` or `glob`. + * @param {fs.Stats} [data.stats] Sets the fs stat data for this entry allowing + * for reduction of fs stat calls when stat data is already known. + * @param {Boolean} [data.store=ZipOptions.store] Sets the compression method to STORE. + * @param {Function} callback + * @return void + */ +Zip.prototype.append = function(source, data, callback) { + this.engine.entry(source, data, callback); +}; + +/** + * @return void + */ +Zip.prototype.finalize = function() { + this.engine.finalize(); +}; + +/** + * @return this.engine + */ +Zip.prototype.on = function() { + return this.engine.on.apply(this.engine, arguments); +}; + +/** + * @return this.engine + */ +Zip.prototype.pipe = function() { + return this.engine.pipe.apply(this.engine, arguments); +}; + +/** + * @return this.engine + */ +Zip.prototype.unpipe = function() { + return this.engine.unpipe.apply(this.engine, arguments); +}; + +module.exports = Zip; + +/** + * @typedef {Object} ZipOptions + * @global + * @property {String} [comment] Sets the zip archive comment. + * @property {Boolean} [forceLocalTime=false] Forces the archive to contain local file times instead of UTC. + * @property {Boolean} [forceZip64=false] Forces the archive to contain ZIP64 headers. + * @prpperty {Boolean} [namePrependSlash=false] Prepends a forward slash to archive file paths. + * @property {Boolean} [store=false] Sets the compression method to STORE. + * @property {Object} [zlib] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} + * to control compression. + * @property {*} [*] See [zip-stream]{@link https://archiverjs.com/zip-stream/ZipStream.html} documentation for current list of properties. + */ + +/** + * @typedef {Object} ZipEntryData + * @global + * @property {String} name Sets the entry name including internal path. + * @property {(String|Date)} [date=NOW()] Sets the entry date. + * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions. + * @property {Boolean} [namePrependSlash=ZipOptions.namePrependSlash] Prepends a forward slash to archive file paths. + * @property {String} [prefix] Sets a path prefix for the entry name. Useful + * when working with methods like `directory` or `glob`. + * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing + * for reduction of fs stat calls when stat data is already known. + * @property {Boolean} [store=ZipOptions.store] Sets the compression method to STORE. + */ + +/** + * ZipStream Module + * @external ZipStream + * @see {@link https://www.archiverjs.com/zip-stream/ZipStream.html} + */ diff --git a/node_modules/archiver/package.json b/node_modules/archiver/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9145a7a7a6b5b57d069b0d0c161a117db7b1f4ef --- /dev/null +++ b/node_modules/archiver/package.json @@ -0,0 +1,60 @@ +{ + "name": "archiver", + "version": "6.0.2", + "description": "a streaming interface for archive generation", + "homepage": "https://github.com/archiverjs/node-archiver", + "author": { + "name": "Chris Talkington", + "url": "http://christalkington.com/" + }, + "repository": { + "type": "git", + "url": "https://github.com/archiverjs/node-archiver.git" + }, + "bugs": { + "url": "https://github.com/archiverjs/node-archiver/issues" + }, + "license": "MIT", + "main": "index.js", + "files": [ + "index.js", + "lib" + ], + "engines": { + "node": ">= 12.0.0" + }, + "scripts": { + "test": "mocha --reporter dot", + "bench": "node benchmark/simple/pack-zip.js" + }, + "dependencies": { + "archiver-utils": "^4.0.1", + "async": "^3.2.4", + "buffer-crc32": "^0.2.1", + "readable-stream": "^3.6.0", + "readdir-glob": "^1.1.2", + "tar-stream": "^3.0.0", + "zip-stream": "^5.0.1" + }, + "devDependencies": { + "archiver-jsdoc-theme": "1.1.3", + "chai": "4.4.1", + "jsdoc": "4.0.2", + "mkdirp": "3.0.1", + "mocha": "9.2.2", + "rimraf": "4.4.1", + "stream-bench": "0.1.2", + "tar": "6.2.0", + "yauzl": "2.10.0" + }, + "keywords": [ + "archive", + "archiver", + "stream", + "zip", + "tar" + ], + "publishConfig": { + "registry": "https://registry.npmjs.org/" + } +} diff --git a/node_modules/arg/LICENSE.md b/node_modules/arg/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..b708f872cb51eb69058c6f83864300a5ce4b0658 --- /dev/null +++ b/node_modules/arg/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2021 Vercel, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/arg/README.md b/node_modules/arg/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6501df5980d25fb1dc4f3f569ae36192cdb8f5cb --- /dev/null +++ b/node_modules/arg/README.md @@ -0,0 +1,317 @@ +# Arg + +`arg` is an unopinionated, no-frills CLI argument parser. + +## Installation + +```bash +npm install arg +``` + +## Usage + +`arg()` takes either 1 or 2 arguments: + +1. Command line specification object (see below) +2. Parse options (_Optional_, defaults to `{permissive: false, argv: process.argv.slice(2), stopAtPositional: false}`) + +It returns an object with any values present on the command-line (missing options are thus +missing from the resulting object). Arg performs no validation/requirement checking - we +leave that up to the application. + +All parameters that aren't consumed by options (commonly referred to as "extra" parameters) +are added to `result._`, which is _always_ an array (even if no extra parameters are passed, +in which case an empty array is returned). + +```javascript +const arg = require('arg'); + +// `options` is an optional parameter +const args = arg( + spec, + (options = { permissive: false, argv: process.argv.slice(2) }) +); +``` + +For example: + +```console +$ node ./hello.js --verbose -vvv --port=1234 -n 'My name' foo bar --tag qux --tag=qix -- --foobar +``` + +```javascript +// hello.js +const arg = require('arg'); + +const args = arg({ + // Types + '--help': Boolean, + '--version': Boolean, + '--verbose': arg.COUNT, // Counts the number of times --verbose is passed + '--port': Number, // --port or --port= + '--name': String, // --name or --name= + '--tag': [String], // --tag or --tag= + + // Aliases + '-v': '--verbose', + '-n': '--name', // -n ; result is stored in --name + '--label': '--name' // --label or --label=; + // result is stored in --name +}); + +console.log(args); +/* +{ + _: ["foo", "bar", "--foobar"], + '--port': 1234, + '--verbose': 4, + '--name': "My name", + '--tag': ["qux", "qix"] +} +*/ +``` + +The values for each key=>value pair is either a type (function or [function]) or a string (indicating an alias). + +- In the case of a function, the string value of the argument's value is passed to it, + and the return value is used as the ultimate value. + +- In the case of an array, the only element _must_ be a type function. Array types indicate + that the argument may be passed multiple times, and as such the resulting value in the returned + object is an array with all of the values that were passed using the specified flag. + +- In the case of a string, an alias is established. If a flag is passed that matches the _key_, + then the _value_ is substituted in its place. + +Type functions are passed three arguments: + +1. The parameter value (always a string) +2. The parameter name (e.g. `--label`) +3. The previous value for the destination (useful for reduce-like operations or for supporting `-v` multiple times, etc.) + +This means the built-in `String`, `Number`, and `Boolean` type constructors "just work" as type functions. + +Note that `Boolean` and `[Boolean]` have special treatment - an option argument is _not_ consumed or passed, but instead `true` is +returned. These options are called "flags". + +For custom handlers that wish to behave as flags, you may pass the function through `arg.flag()`: + +```javascript +const arg = require('arg'); + +const argv = [ + '--foo', + 'bar', + '-ff', + 'baz', + '--foo', + '--foo', + 'qux', + '-fff', + 'qix' +]; + +function myHandler(value, argName, previousValue) { + /* `value` is always `true` */ + return 'na ' + (previousValue || 'batman!'); +} + +const args = arg( + { + '--foo': arg.flag(myHandler), + '-f': '--foo' + }, + { + argv + } +); + +console.log(args); +/* +{ + _: ['bar', 'baz', 'qux', 'qix'], + '--foo': 'na na na na na na na na batman!' +} +*/ +``` + +As well, `arg` supplies a helper argument handler called `arg.COUNT`, which equivalent to a `[Boolean]` argument's `.length` +property - effectively counting the number of times the boolean flag, denoted by the key, is passed on the command line.. +For example, this is how you could implement `ssh`'s multiple levels of verbosity (`-vvvv` being the most verbose). + +```javascript +const arg = require('arg'); + +const argv = ['-AAAA', '-BBBB']; + +const args = arg( + { + '-A': arg.COUNT, + '-B': [Boolean] + }, + { + argv + } +); + +console.log(args); +/* +{ + _: [], + '-A': 4, + '-B': [true, true, true, true] +} +*/ +``` + +### Options + +If a second parameter is specified and is an object, it specifies parsing options to modify the behavior of `arg()`. + +#### `argv` + +If you have already sliced or generated a number of raw arguments to be parsed (as opposed to letting `arg` +slice them from `process.argv`) you may specify them in the `argv` option. + +For example: + +```javascript +const args = arg( + { + '--foo': String + }, + { + argv: ['hello', '--foo', 'world'] + } +); +``` + +results in: + +```javascript +const args = { + _: ['hello'], + '--foo': 'world' +}; +``` + +#### `permissive` + +When `permissive` set to `true`, `arg` will push any unknown arguments +onto the "extra" argument array (`result._`) instead of throwing an error about +an unknown flag. + +For example: + +```javascript +const arg = require('arg'); + +const argv = [ + '--foo', + 'hello', + '--qux', + 'qix', + '--bar', + '12345', + 'hello again' +]; + +const args = arg( + { + '--foo': String, + '--bar': Number + }, + { + argv, + permissive: true + } +); +``` + +results in: + +```javascript +const args = { + _: ['--qux', 'qix', 'hello again'], + '--foo': 'hello', + '--bar': 12345 +}; +``` + +#### `stopAtPositional` + +When `stopAtPositional` is set to `true`, `arg` will halt parsing at the first +positional argument. + +For example: + +```javascript +const arg = require('arg'); + +const argv = ['--foo', 'hello', '--bar']; + +const args = arg( + { + '--foo': Boolean, + '--bar': Boolean + }, + { + argv, + stopAtPositional: true + } +); +``` + +results in: + +```javascript +const args = { + _: ['hello', '--bar'], + '--foo': true +}; +``` + +### Errors + +Some errors that `arg` throws provide a `.code` property in order to aid in recovering from user error, or to +differentiate between user error and developer error (bug). + +##### ARG_UNKNOWN_OPTION + +If an unknown option (not defined in the spec object) is passed, an error with code `ARG_UNKNOWN_OPTION` will be thrown: + +```js +// cli.js +try { + require('arg')({ '--hi': String }); +} catch (err) { + if (err.code === 'ARG_UNKNOWN_OPTION') { + console.log(err.message); + } else { + throw err; + } +} +``` + +```shell +node cli.js --extraneous true +Unknown or unexpected option: --extraneous +``` + +# FAQ + +A few questions and answers that have been asked before: + +### How do I require an argument with `arg`? + +Do the assertion yourself, such as: + +```javascript +const args = arg({ '--name': String }); + +if (!args['--name']) throw new Error('missing required argument: --name'); +``` + +# License + +Released under the [MIT License](LICENSE.md). diff --git a/node_modules/arg/index.d.ts b/node_modules/arg/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..44f9f354ba3354257f701bbcf669dc5fae45792a --- /dev/null +++ b/node_modules/arg/index.d.ts @@ -0,0 +1,44 @@ +declare function arg( + spec: T, + options?: arg.Options +): arg.Result; + +declare namespace arg { + export const flagSymbol: unique symbol; + + export function flag(fn: T): T & { [arg.flagSymbol]: true }; + + export const COUNT: Handler & { [arg.flagSymbol]: true }; + + export type Handler = ( + value: string, + name: string, + previousValue?: T + ) => T; + + export class ArgError extends Error { + constructor(message: string, code: string); + + code: string; + } + + export interface Spec { + [key: string]: string | Handler | [Handler]; + } + + export type Result = { _: string[] } & { + [K in keyof T]?: T[K] extends Handler + ? ReturnType + : T[K] extends [Handler] + ? Array> + : never; + }; + + export interface Options { + argv?: string[]; + permissive?: boolean; + stopAtPositional?: boolean; + } +} + +export = arg; diff --git a/node_modules/arg/index.js b/node_modules/arg/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3f60f4cadc95780cfbb37bf27e972a864c69cbff --- /dev/null +++ b/node_modules/arg/index.js @@ -0,0 +1,195 @@ +const flagSymbol = Symbol('arg flag'); + +class ArgError extends Error { + constructor(msg, code) { + super(msg); + this.name = 'ArgError'; + this.code = code; + + Object.setPrototypeOf(this, ArgError.prototype); + } +} + +function arg( + opts, + { + argv = process.argv.slice(2), + permissive = false, + stopAtPositional = false + } = {} +) { + if (!opts) { + throw new ArgError( + 'argument specification object is required', + 'ARG_CONFIG_NO_SPEC' + ); + } + + const result = { _: [] }; + + const aliases = {}; + const handlers = {}; + + for (const key of Object.keys(opts)) { + if (!key) { + throw new ArgError( + 'argument key cannot be an empty string', + 'ARG_CONFIG_EMPTY_KEY' + ); + } + + if (key[0] !== '-') { + throw new ArgError( + `argument key must start with '-' but found: '${key}'`, + 'ARG_CONFIG_NONOPT_KEY' + ); + } + + if (key.length === 1) { + throw new ArgError( + `argument key must have a name; singular '-' keys are not allowed: ${key}`, + 'ARG_CONFIG_NONAME_KEY' + ); + } + + if (typeof opts[key] === 'string') { + aliases[key] = opts[key]; + continue; + } + + let type = opts[key]; + let isFlag = false; + + if ( + Array.isArray(type) && + type.length === 1 && + typeof type[0] === 'function' + ) { + const [fn] = type; + type = (value, name, prev = []) => { + prev.push(fn(value, name, prev[prev.length - 1])); + return prev; + }; + isFlag = fn === Boolean || fn[flagSymbol] === true; + } else if (typeof type === 'function') { + isFlag = type === Boolean || type[flagSymbol] === true; + } else { + throw new ArgError( + `type missing or not a function or valid array type: ${key}`, + 'ARG_CONFIG_VAD_TYPE' + ); + } + + if (key[1] !== '-' && key.length > 2) { + throw new ArgError( + `short argument keys (with a single hyphen) must have only one character: ${key}`, + 'ARG_CONFIG_SHORTOPT_TOOLONG' + ); + } + + handlers[key] = [type, isFlag]; + } + + for (let i = 0, len = argv.length; i < len; i++) { + const wholeArg = argv[i]; + + if (stopAtPositional && result._.length > 0) { + result._ = result._.concat(argv.slice(i)); + break; + } + + if (wholeArg === '--') { + result._ = result._.concat(argv.slice(i + 1)); + break; + } + + if (wholeArg.length > 1 && wholeArg[0] === '-') { + /* eslint-disable operator-linebreak */ + const separatedArguments = + wholeArg[1] === '-' || wholeArg.length === 2 + ? [wholeArg] + : wholeArg + .slice(1) + .split('') + .map((a) => `-${a}`); + /* eslint-enable operator-linebreak */ + + for (let j = 0; j < separatedArguments.length; j++) { + const arg = separatedArguments[j]; + const [originalArgName, argStr] = + arg[1] === '-' ? arg.split(/=(.*)/, 2) : [arg, undefined]; + + let argName = originalArgName; + while (argName in aliases) { + argName = aliases[argName]; + } + + if (!(argName in handlers)) { + if (permissive) { + result._.push(arg); + continue; + } else { + throw new ArgError( + `unknown or unexpected option: ${originalArgName}`, + 'ARG_UNKNOWN_OPTION' + ); + } + } + + const [type, isFlag] = handlers[argName]; + + if (!isFlag && j + 1 < separatedArguments.length) { + throw new ArgError( + `option requires argument (but was followed by another short argument): ${originalArgName}`, + 'ARG_MISSING_REQUIRED_SHORTARG' + ); + } + + if (isFlag) { + result[argName] = type(true, argName, result[argName]); + } else if (argStr === undefined) { + if ( + argv.length < i + 2 || + (argv[i + 1].length > 1 && + argv[i + 1][0] === '-' && + !( + argv[i + 1].match(/^-?\d*(\.(?=\d))?\d*$/) && + (type === Number || + // eslint-disable-next-line no-undef + (typeof BigInt !== 'undefined' && type === BigInt)) + )) + ) { + const extended = + originalArgName === argName ? '' : ` (alias for ${argName})`; + throw new ArgError( + `option requires argument: ${originalArgName}${extended}`, + 'ARG_MISSING_REQUIRED_LONGARG' + ); + } + + result[argName] = type(argv[i + 1], argName, result[argName]); + ++i; + } else { + result[argName] = type(argStr, argName, result[argName]); + } + } + } else { + result._.push(wholeArg); + } + } + + return result; +} + +arg.flag = (fn) => { + fn[flagSymbol] = true; + return fn; +}; + +// Utility types +arg.COUNT = arg.flag((v, name, existingCount) => (existingCount || 0) + 1); + +// Expose error class +arg.ArgError = ArgError; + +module.exports = arg; diff --git a/node_modules/arg/package.json b/node_modules/arg/package.json new file mode 100644 index 0000000000000000000000000000000000000000..47368d76d2b916bb003ec35e0ff6162d3f23768f --- /dev/null +++ b/node_modules/arg/package.json @@ -0,0 +1,28 @@ +{ + "name": "arg", + "version": "5.0.2", + "description": "Unopinionated, no-frills CLI argument parser", + "main": "index.js", + "types": "index.d.ts", + "repository": "vercel/arg", + "author": "Josh Junon ", + "license": "MIT", + "files": [ + "index.js", + "index.d.ts" + ], + "scripts": { + "test": "WARN_EXIT=1 jest --coverage -w 2" + }, + "devDependencies": { + "chai": "^4.1.1", + "jest": "^27.0.6", + "prettier": "^2.3.2" + }, + "prettier": { + "arrowParens": "always", + "singleQuote": true, + "tabWidth": 2, + "trailingComma": "none" + } +} diff --git a/node_modules/argparse/CHANGELOG.md b/node_modules/argparse/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..dc39ed6952f87adcd961d07749e1ffe7a2b7335b --- /dev/null +++ b/node_modules/argparse/CHANGELOG.md @@ -0,0 +1,216 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + + +## [2.0.1] - 2020-08-29 +### Fixed +- Fix issue with `process.argv` when used with interpreters (`coffee`, `ts-node`, etc.), #150. + + +## [2.0.0] - 2020-08-14 +### Changed +- Full rewrite. Now port from python 3.9.0 & more precise following. + See [doc](./doc) for difference and migration info. +- node.js 10+ required +- Removed most of local docs in favour of original ones. + + +## [1.0.10] - 2018-02-15 +### Fixed +- Use .concat instead of + for arrays, #122. + + +## [1.0.9] - 2016-09-29 +### Changed +- Rerelease after 1.0.8 - deps cleanup. + + +## [1.0.8] - 2016-09-29 +### Changed +- Maintenance (deps bump, fix node 6.5+ tests, coverage report). + + +## [1.0.7] - 2016-03-17 +### Changed +- Teach `addArgument` to accept string arg names. #97, @tomxtobin. + + +## [1.0.6] - 2016-02-06 +### Changed +- Maintenance: moved to eslint & updated CS. + + +## [1.0.5] - 2016-02-05 +### Changed +- Removed lodash dependency to significantly reduce install size. + Thanks to @mourner. + + +## [1.0.4] - 2016-01-17 +### Changed +- Maintenance: lodash update to 4.0.0. + + +## [1.0.3] - 2015-10-27 +### Fixed +- Fix parse `=` in args: `--examplepath="C:\myfolder\env=x64"`. #84, @CatWithApple. + + +## [1.0.2] - 2015-03-22 +### Changed +- Relaxed lodash version dependency. + + +## [1.0.1] - 2015-02-20 +### Changed +- Changed dependencies to be compatible with ancient nodejs. + + +## [1.0.0] - 2015-02-19 +### Changed +- Maintenance release. +- Replaced `underscore` with `lodash`. +- Bumped version to 1.0.0 to better reflect semver meaning. +- HISTORY.md -> CHANGELOG.md + + +## [0.1.16] - 2013-12-01 +### Changed +- Maintenance release. Updated dependencies and docs. + + +## [0.1.15] - 2013-05-13 +### Fixed +- Fixed #55, @trebor89 + + +## [0.1.14] - 2013-05-12 +### Fixed +- Fixed #62, @maxtaco + + +## [0.1.13] - 2013-04-08 +### Changed +- Added `.npmignore` to reduce package size + + +## [0.1.12] - 2013-02-10 +### Fixed +- Fixed conflictHandler (#46), @hpaulj + + +## [0.1.11] - 2013-02-07 +### Added +- Added 70+ tests (ported from python), @hpaulj +- Added conflictHandler, @applepicke +- Added fromfilePrefixChar, @hpaulj + +### Fixed +- Multiple bugfixes, @hpaulj + + +## [0.1.10] - 2012-12-30 +### Added +- Added [mutual exclusion](http://docs.python.org/dev/library/argparse.html#mutual-exclusion) + support, thanks to @hpaulj + +### Fixed +- Fixed options check for `storeConst` & `appendConst` actions, thanks to @hpaulj + + +## [0.1.9] - 2012-12-27 +### Fixed +- Fixed option dest interferens with other options (issue #23), thanks to @hpaulj +- Fixed default value behavior with `*` positionals, thanks to @hpaulj +- Improve `getDefault()` behavior, thanks to @hpaulj +- Improve negative argument parsing, thanks to @hpaulj + + +## [0.1.8] - 2012-12-01 +### Fixed +- Fixed parser parents (issue #19), thanks to @hpaulj +- Fixed negative argument parse (issue #20), thanks to @hpaulj + + +## [0.1.7] - 2012-10-14 +### Fixed +- Fixed 'choices' argument parse (issue #16) +- Fixed stderr output (issue #15) + + +## [0.1.6] - 2012-09-09 +### Fixed +- Fixed check for conflict of options (thanks to @tomxtobin) + + +## [0.1.5] - 2012-09-03 +### Fixed +- Fix parser #setDefaults method (thanks to @tomxtobin) + + +## [0.1.4] - 2012-07-30 +### Fixed +- Fixed pseudo-argument support (thanks to @CGamesPlay) +- Fixed addHelp default (should be true), if not set (thanks to @benblank) + + +## [0.1.3] - 2012-06-27 +### Fixed +- Fixed formatter api name: Formatter -> HelpFormatter + + +## [0.1.2] - 2012-05-29 +### Fixed +- Removed excess whitespace in help +- Fixed error reporting, when parcer with subcommands + called with empty arguments + +### Added +- Added basic tests + + +## [0.1.1] - 2012-05-23 +### Fixed +- Fixed line wrapping in help formatter +- Added better error reporting on invalid arguments + + +## [0.1.0] - 2012-05-16 +### Added +- First release. + + +[2.0.1]: https://github.com/nodeca/argparse/compare/2.0.0...2.0.1 +[2.0.0]: https://github.com/nodeca/argparse/compare/1.0.10...2.0.0 +[1.0.10]: https://github.com/nodeca/argparse/compare/1.0.9...1.0.10 +[1.0.9]: https://github.com/nodeca/argparse/compare/1.0.8...1.0.9 +[1.0.8]: https://github.com/nodeca/argparse/compare/1.0.7...1.0.8 +[1.0.7]: https://github.com/nodeca/argparse/compare/1.0.6...1.0.7 +[1.0.6]: https://github.com/nodeca/argparse/compare/1.0.5...1.0.6 +[1.0.5]: https://github.com/nodeca/argparse/compare/1.0.4...1.0.5 +[1.0.4]: https://github.com/nodeca/argparse/compare/1.0.3...1.0.4 +[1.0.3]: https://github.com/nodeca/argparse/compare/1.0.2...1.0.3 +[1.0.2]: https://github.com/nodeca/argparse/compare/1.0.1...1.0.2 +[1.0.1]: https://github.com/nodeca/argparse/compare/1.0.0...1.0.1 +[1.0.0]: https://github.com/nodeca/argparse/compare/0.1.16...1.0.0 +[0.1.16]: https://github.com/nodeca/argparse/compare/0.1.15...0.1.16 +[0.1.15]: https://github.com/nodeca/argparse/compare/0.1.14...0.1.15 +[0.1.14]: https://github.com/nodeca/argparse/compare/0.1.13...0.1.14 +[0.1.13]: https://github.com/nodeca/argparse/compare/0.1.12...0.1.13 +[0.1.12]: https://github.com/nodeca/argparse/compare/0.1.11...0.1.12 +[0.1.11]: https://github.com/nodeca/argparse/compare/0.1.10...0.1.11 +[0.1.10]: https://github.com/nodeca/argparse/compare/0.1.9...0.1.10 +[0.1.9]: https://github.com/nodeca/argparse/compare/0.1.8...0.1.9 +[0.1.8]: https://github.com/nodeca/argparse/compare/0.1.7...0.1.8 +[0.1.7]: https://github.com/nodeca/argparse/compare/0.1.6...0.1.7 +[0.1.6]: https://github.com/nodeca/argparse/compare/0.1.5...0.1.6 +[0.1.5]: https://github.com/nodeca/argparse/compare/0.1.4...0.1.5 +[0.1.4]: https://github.com/nodeca/argparse/compare/0.1.3...0.1.4 +[0.1.3]: https://github.com/nodeca/argparse/compare/0.1.2...0.1.3 +[0.1.2]: https://github.com/nodeca/argparse/compare/0.1.1...0.1.2 +[0.1.1]: https://github.com/nodeca/argparse/compare/0.1.0...0.1.1 +[0.1.0]: https://github.com/nodeca/argparse/releases/tag/0.1.0 diff --git a/node_modules/argparse/LICENSE b/node_modules/argparse/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..66a3ac80d729a3a5bdfd22002d34be59a6daf222 --- /dev/null +++ b/node_modules/argparse/LICENSE @@ -0,0 +1,254 @@ +A. HISTORY OF THE SOFTWARE +========================== + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands +as a successor of a language called ABC. Guido remains Python's +principal author, although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for +National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) +in Reston, Virginia where he released several versions of the +software. + +In May 2000, Guido and the Python core development team moved to +BeOpen.com to form the BeOpen PythonLabs team. In October of the same +year, the PythonLabs team moved to Digital Creations, which became +Zope Corporation. In 2001, the Python Software Foundation (PSF, see +https://www.python.org/psf/) was formed, a non-profit organization +created specifically to own Python-related Intellectual Property. +Zope Corporation was a sponsoring member of the PSF. + +All Python releases are Open Source (see http://www.opensource.org for +the Open Source Definition). Historically, most, but not all, Python +releases have also been GPL-compatible; the table below summarizes +the various releases. + + Release Derived Year Owner GPL- + from compatible? (1) + + 0.9.0 thru 1.2 1991-1995 CWI yes + 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes + 1.6 1.5.2 2000 CNRI no + 2.0 1.6 2000 BeOpen.com no + 1.6.1 1.6 2001 CNRI yes (2) + 2.1 2.0+1.6.1 2001 PSF no + 2.0.1 2.0+1.6.1 2001 PSF yes + 2.1.1 2.1+2.0.1 2001 PSF yes + 2.1.2 2.1.1 2002 PSF yes + 2.1.3 2.1.2 2002 PSF yes + 2.2 and above 2.1.1 2001-now PSF yes + +Footnotes: + +(1) GPL-compatible doesn't mean that we're distributing Python under + the GPL. All Python licenses, unlike the GPL, let you distribute + a modified version without making your changes open source. The + GPL-compatible licenses make it possible to combine Python with + other software that is released under the GPL; the others don't. + +(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, + because its license has a choice of law clause. According to + CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 + is "not incompatible" with the GPL. + +Thanks to the many outside volunteers who have worked under Guido's +direction to make these releases possible. + + +B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON +=============================================================== + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an +office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the +Individual or Organization ("Licensee") accessing and otherwise using +this software in source or binary form and its associated +documentation ("the Software"). + +2. Subject to the terms and conditions of this BeOpen Python License +Agreement, BeOpen hereby grants Licensee a non-exclusive, +royalty-free, world-wide license to reproduce, analyze, test, perform +and/or display publicly, prepare derivative works, distribute, and +otherwise use the Software alone or in any derivative version, +provided, however, that the BeOpen Python License is retained in the +Software, alone or in any derivative version prepared by Licensee. + +3. BeOpen is making the Software available to Licensee on an "AS IS" +basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE +SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS +AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY +DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +5. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +6. This License Agreement shall be governed by and interpreted in all +respects by the law of the State of California, excluding conflict of +law provisions. Nothing in this License Agreement shall be deemed to +create any relationship of agency, partnership, or joint venture +between BeOpen and Licensee. This License Agreement does not grant +permission to use BeOpen trademarks or trade names in a trademark +sense to endorse or promote products or services of Licensee, or any +third party. As an exception, the "BeOpen Python" logos available at +http://www.pythonlabs.com/logos.html may be used according to the +permissions granted on that web page. + +7. By copying, installing or otherwise using the software, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +1. This LICENSE AGREEMENT is between the Corporation for National +Research Initiatives, having an office at 1895 Preston White Drive, +Reston, VA 20191 ("CNRI"), and the Individual or Organization +("Licensee") accessing and otherwise using Python 1.6.1 software in +source or binary form and its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, CNRI +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python 1.6.1 +alone or in any derivative version, provided, however, that CNRI's +License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) +1995-2001 Corporation for National Research Initiatives; All Rights +Reserved" are retained in Python 1.6.1 alone or in any derivative +version prepared by Licensee. Alternately, in lieu of CNRI's License +Agreement, Licensee may substitute the following text (omitting the +quotes): "Python 1.6.1 is made available subject to the terms and +conditions in CNRI's License Agreement. This Agreement together with +Python 1.6.1 may be located on the Internet using the following +unique, persistent identifier (known as a handle): 1895.22/1013. This +Agreement may also be obtained from a proxy server on the Internet +using the following URL: http://hdl.handle.net/1895.22/1013". + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python 1.6.1 or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python 1.6.1. + +4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" +basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. This License Agreement shall be governed by the federal +intellectual property law of the United States, including without +limitation the federal copyright law, and, to the extent such +U.S. federal law does not apply, by the law of the Commonwealth of +Virginia, excluding Virginia's conflict of law provisions. +Notwithstanding the foregoing, with regard to derivative works based +on Python 1.6.1 that incorporate non-separable material that was +previously distributed under the GNU General Public License (GPL), the +law of the Commonwealth of Virginia shall govern this License +Agreement only as to issues arising under or with respect to +Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this +License Agreement shall be deemed to create any relationship of +agency, partnership, or joint venture between CNRI and Licensee. This +License Agreement does not grant permission to use CNRI trademarks or +trade name in a trademark sense to endorse or promote products or +services of Licensee, or any third party. + +8. By clicking on the "ACCEPT" button where indicated, or by copying, +installing or otherwise using Python 1.6.1, Licensee agrees to be +bound by the terms and conditions of this License Agreement. + + ACCEPT + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, +The Netherlands. All rights reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/argparse/README.md b/node_modules/argparse/README.md new file mode 100644 index 0000000000000000000000000000000000000000..550b5c9b7b00aaa18ba240b485e5b31598ef04b2 --- /dev/null +++ b/node_modules/argparse/README.md @@ -0,0 +1,84 @@ +argparse +======== + +[![Build Status](https://secure.travis-ci.org/nodeca/argparse.svg?branch=master)](http://travis-ci.org/nodeca/argparse) +[![NPM version](https://img.shields.io/npm/v/argparse.svg)](https://www.npmjs.org/package/argparse) + +CLI arguments parser for node.js, with [sub-commands](https://docs.python.org/3.9/library/argparse.html#sub-commands) support. Port of python's [argparse](http://docs.python.org/dev/library/argparse.html) (version [3.9.0](https://github.com/python/cpython/blob/v3.9.0rc1/Lib/argparse.py)). + +**Difference with original.** + +- JS has no keyword arguments support. + - Pass options instead: `new ArgumentParser({ description: 'example', add_help: true })`. +- JS has no python's types `int`, `float`, ... + - Use string-typed names: `.add_argument('-b', { type: 'int', help: 'help' })`. +- `%r` format specifier uses `require('util').inspect()`. + +More details in [doc](./doc). + + +Example +------- + +`test.js` file: + +```javascript +#!/usr/bin/env node +'use strict'; + +const { ArgumentParser } = require('argparse'); +const { version } = require('./package.json'); + +const parser = new ArgumentParser({ + description: 'Argparse example' +}); + +parser.add_argument('-v', '--version', { action: 'version', version }); +parser.add_argument('-f', '--foo', { help: 'foo bar' }); +parser.add_argument('-b', '--bar', { help: 'bar foo' }); +parser.add_argument('--baz', { help: 'baz bar' }); + +console.dir(parser.parse_args()); +``` + +Display help: + +``` +$ ./test.js -h +usage: test.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ] + +Argparse example + +optional arguments: + -h, --help show this help message and exit + -v, --version show program's version number and exit + -f FOO, --foo FOO foo bar + -b BAR, --bar BAR bar foo + --baz BAZ baz bar +``` + +Parse arguments: + +``` +$ ./test.js -f=3 --bar=4 --baz 5 +{ foo: '3', bar: '4', baz: '5' } +``` + + +API docs +-------- + +Since this is a port with minimal divergence, there's no separate documentation. +Use original one instead, with notes about difference. + +1. [Original doc](https://docs.python.org/3.9/library/argparse.html). +2. [Original tutorial](https://docs.python.org/3.9/howto/argparse.html). +3. [Difference with python](./doc). + + +argparse for enterprise +----------------------- + +Available as part of the Tidelift Subscription + +The maintainers of argparse and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-argparse?utm_source=npm-argparse&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/argparse/argparse.js b/node_modules/argparse/argparse.js new file mode 100644 index 0000000000000000000000000000000000000000..2b8c8c63177af9757a44926cfc3ab7d9878c9387 --- /dev/null +++ b/node_modules/argparse/argparse.js @@ -0,0 +1,3707 @@ +// Port of python's argparse module, version 3.9.0: +// https://github.com/python/cpython/blob/v3.9.0rc1/Lib/argparse.py + +'use strict' + +// Copyright (C) 2010-2020 Python Software Foundation. +// Copyright (C) 2020 argparse.js authors + +/* + * Command-line parsing library + * + * This module is an optparse-inspired command-line parsing library that: + * + * - handles both optional and positional arguments + * - produces highly informative usage messages + * - supports parsers that dispatch to sub-parsers + * + * The following is a simple usage example that sums integers from the + * command-line and writes the result to a file:: + * + * parser = argparse.ArgumentParser( + * description='sum the integers at the command line') + * parser.add_argument( + * 'integers', metavar='int', nargs='+', type=int, + * help='an integer to be summed') + * parser.add_argument( + * '--log', default=sys.stdout, type=argparse.FileType('w'), + * help='the file where the sum should be written') + * args = parser.parse_args() + * args.log.write('%s' % sum(args.integers)) + * args.log.close() + * + * The module contains the following public classes: + * + * - ArgumentParser -- The main entry point for command-line parsing. As the + * example above shows, the add_argument() method is used to populate + * the parser with actions for optional and positional arguments. Then + * the parse_args() method is invoked to convert the args at the + * command-line into an object with attributes. + * + * - ArgumentError -- The exception raised by ArgumentParser objects when + * there are errors with the parser's actions. Errors raised while + * parsing the command-line are caught by ArgumentParser and emitted + * as command-line messages. + * + * - FileType -- A factory for defining types of files to be created. As the + * example above shows, instances of FileType are typically passed as + * the type= argument of add_argument() calls. + * + * - Action -- The base class for parser actions. Typically actions are + * selected by passing strings like 'store_true' or 'append_const' to + * the action= argument of add_argument(). However, for greater + * customization of ArgumentParser actions, subclasses of Action may + * be defined and passed as the action= argument. + * + * - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, + * ArgumentDefaultsHelpFormatter -- Formatter classes which + * may be passed as the formatter_class= argument to the + * ArgumentParser constructor. HelpFormatter is the default, + * RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser + * not to change the formatting for help text, and + * ArgumentDefaultsHelpFormatter adds information about argument defaults + * to the help. + * + * All other classes in this module are considered implementation details. + * (Also note that HelpFormatter and RawDescriptionHelpFormatter are only + * considered public as object names -- the API of the formatter objects is + * still considered an implementation detail.) + */ + +const SUPPRESS = '==SUPPRESS==' + +const OPTIONAL = '?' +const ZERO_OR_MORE = '*' +const ONE_OR_MORE = '+' +const PARSER = 'A...' +const REMAINDER = '...' +const _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args' + + +// ================================== +// Utility functions used for porting +// ================================== +const assert = require('assert') +const util = require('util') +const fs = require('fs') +const sub = require('./lib/sub') +const path = require('path') +const repr = util.inspect + +function get_argv() { + // omit first argument (which is assumed to be interpreter - `node`, `coffee`, `ts-node`, etc.) + return process.argv.slice(1) +} + +function get_terminal_size() { + return { + columns: +process.env.COLUMNS || process.stdout.columns || 80 + } +} + +function hasattr(object, name) { + return Object.prototype.hasOwnProperty.call(object, name) +} + +function getattr(object, name, value) { + return hasattr(object, name) ? object[name] : value +} + +function setattr(object, name, value) { + object[name] = value +} + +function setdefault(object, name, value) { + if (!hasattr(object, name)) object[name] = value + return object[name] +} + +function delattr(object, name) { + delete object[name] +} + +function range(from, to, step=1) { + // range(10) is equivalent to range(0, 10) + if (arguments.length === 1) [ to, from ] = [ from, 0 ] + if (typeof from !== 'number' || typeof to !== 'number' || typeof step !== 'number') { + throw new TypeError('argument cannot be interpreted as an integer') + } + if (step === 0) throw new TypeError('range() arg 3 must not be zero') + + let result = [] + if (step > 0) { + for (let i = from; i < to; i += step) result.push(i) + } else { + for (let i = from; i > to; i += step) result.push(i) + } + return result +} + +function splitlines(str, keepends = false) { + let result + if (!keepends) { + result = str.split(/\r\n|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029]/) + } else { + result = [] + let parts = str.split(/(\r\n|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029])/) + for (let i = 0; i < parts.length; i += 2) { + result.push(parts[i] + (i + 1 < parts.length ? parts[i + 1] : '')) + } + } + if (!result[result.length - 1]) result.pop() + return result +} + +function _string_lstrip(string, prefix_chars) { + let idx = 0 + while (idx < string.length && prefix_chars.includes(string[idx])) idx++ + return idx ? string.slice(idx) : string +} + +function _string_split(string, sep, maxsplit) { + let result = string.split(sep) + if (result.length > maxsplit) { + result = result.slice(0, maxsplit).concat([ result.slice(maxsplit).join(sep) ]) + } + return result +} + +function _array_equal(array1, array2) { + if (array1.length !== array2.length) return false + for (let i = 0; i < array1.length; i++) { + if (array1[i] !== array2[i]) return false + } + return true +} + +function _array_remove(array, item) { + let idx = array.indexOf(item) + if (idx === -1) throw new TypeError(sub('%r not in list', item)) + array.splice(idx, 1) +} + +// normalize choices to array; +// this isn't required in python because `in` and `map` operators work with anything, +// but in js dealing with multiple types here is too clunky +function _choices_to_array(choices) { + if (choices === undefined) { + return [] + } else if (Array.isArray(choices)) { + return choices + } else if (choices !== null && typeof choices[Symbol.iterator] === 'function') { + return Array.from(choices) + } else if (typeof choices === 'object' && choices !== null) { + return Object.keys(choices) + } else { + throw new Error(sub('invalid choices value: %r', choices)) + } +} + +// decorator that allows a class to be called without new +function _callable(cls) { + let result = { // object is needed for inferred class name + [cls.name]: function (...args) { + let this_class = new.target === result || !new.target + return Reflect.construct(cls, args, this_class ? cls : new.target) + } + } + result[cls.name].prototype = cls.prototype + // fix default tag for toString, e.g. [object Action] instead of [object Object] + cls.prototype[Symbol.toStringTag] = cls.name + return result[cls.name] +} + +function _alias(object, from, to) { + try { + let name = object.constructor.name + Object.defineProperty(object, from, { + value: util.deprecate(object[to], sub('%s.%s() is renamed to %s.%s()', + name, from, name, to)), + enumerable: false + }) + } catch {} +} + +// decorator that allows snake_case class methods to be called with camelCase and vice versa +function _camelcase_alias(_class) { + for (let name of Object.getOwnPropertyNames(_class.prototype)) { + let camelcase = name.replace(/\w_[a-z]/g, s => s[0] + s[2].toUpperCase()) + if (camelcase !== name) _alias(_class.prototype, camelcase, name) + } + return _class +} + +function _to_legacy_name(key) { + key = key.replace(/\w_[a-z]/g, s => s[0] + s[2].toUpperCase()) + if (key === 'default') key = 'defaultValue' + if (key === 'const') key = 'constant' + return key +} + +function _to_new_name(key) { + if (key === 'defaultValue') key = 'default' + if (key === 'constant') key = 'const' + key = key.replace(/[A-Z]/g, c => '_' + c.toLowerCase()) + return key +} + +// parse options +let no_default = Symbol('no_default_value') +function _parse_opts(args, descriptor) { + function get_name() { + let stack = new Error().stack.split('\n') + .map(x => x.match(/^ at (.*) \(.*\)$/)) + .filter(Boolean) + .map(m => m[1]) + .map(fn => fn.match(/[^ .]*$/)[0]) + + if (stack.length && stack[0] === get_name.name) stack.shift() + if (stack.length && stack[0] === _parse_opts.name) stack.shift() + return stack.length ? stack[0] : '' + } + + args = Array.from(args) + let kwargs = {} + let result = [] + let last_opt = args.length && args[args.length - 1] + + if (typeof last_opt === 'object' && last_opt !== null && !Array.isArray(last_opt) && + (!last_opt.constructor || last_opt.constructor.name === 'Object')) { + kwargs = Object.assign({}, args.pop()) + } + + // LEGACY (v1 compatibility): camelcase + let renames = [] + for (let key of Object.keys(descriptor)) { + let old_name = _to_legacy_name(key) + if (old_name !== key && (old_name in kwargs)) { + if (key in kwargs) { + // default and defaultValue specified at the same time, happens often in old tests + //throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), key)) + } else { + kwargs[key] = kwargs[old_name] + } + renames.push([ old_name, key ]) + delete kwargs[old_name] + } + } + if (renames.length) { + let name = get_name() + deprecate('camelcase_' + name, sub('%s(): following options are renamed: %s', + name, renames.map(([ a, b ]) => sub('%r -> %r', a, b)))) + } + // end + + let missing_positionals = [] + let positional_count = args.length + + for (let [ key, def ] of Object.entries(descriptor)) { + if (key[0] === '*') { + if (key.length > 0 && key[1] === '*') { + // LEGACY (v1 compatibility): camelcase + let renames = [] + for (let key of Object.keys(kwargs)) { + let new_name = _to_new_name(key) + if (new_name !== key && (key in kwargs)) { + if (new_name in kwargs) { + // default and defaultValue specified at the same time, happens often in old tests + //throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), new_name)) + } else { + kwargs[new_name] = kwargs[key] + } + renames.push([ key, new_name ]) + delete kwargs[key] + } + } + if (renames.length) { + let name = get_name() + deprecate('camelcase_' + name, sub('%s(): following options are renamed: %s', + name, renames.map(([ a, b ]) => sub('%r -> %r', a, b)))) + } + // end + result.push(kwargs) + kwargs = {} + } else { + result.push(args) + args = [] + } + } else if (key in kwargs && args.length > 0) { + throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), key)) + } else if (key in kwargs) { + result.push(kwargs[key]) + delete kwargs[key] + } else if (args.length > 0) { + result.push(args.shift()) + } else if (def !== no_default) { + result.push(def) + } else { + missing_positionals.push(key) + } + } + + if (Object.keys(kwargs).length) { + throw new TypeError(sub('%s() got an unexpected keyword argument %r', + get_name(), Object.keys(kwargs)[0])) + } + + if (args.length) { + let from = Object.entries(descriptor).filter(([ k, v ]) => k[0] !== '*' && v !== no_default).length + let to = Object.entries(descriptor).filter(([ k ]) => k[0] !== '*').length + throw new TypeError(sub('%s() takes %s positional argument%s but %s %s given', + get_name(), + from === to ? sub('from %s to %s', from, to) : to, + from === to && to === 1 ? '' : 's', + positional_count, + positional_count === 1 ? 'was' : 'were')) + } + + if (missing_positionals.length) { + let strs = missing_positionals.map(repr) + if (strs.length > 1) strs[strs.length - 1] = 'and ' + strs[strs.length - 1] + let str_joined = strs.join(strs.length === 2 ? '' : ', ') + throw new TypeError(sub('%s() missing %i required positional argument%s: %s', + get_name(), strs.length, strs.length === 1 ? '' : 's', str_joined)) + } + + return result +} + +let _deprecations = {} +function deprecate(id, string) { + _deprecations[id] = _deprecations[id] || util.deprecate(() => {}, string) + _deprecations[id]() +} + + +// ============================= +// Utility functions and classes +// ============================= +function _AttributeHolder(cls = Object) { + /* + * Abstract base class that provides __repr__. + * + * The __repr__ method returns a string in the format:: + * ClassName(attr=name, attr=name, ...) + * The attributes are determined either by a class-level attribute, + * '_kwarg_names', or by inspecting the instance __dict__. + */ + + return class _AttributeHolder extends cls { + [util.inspect.custom]() { + let type_name = this.constructor.name + let arg_strings = [] + let star_args = {} + for (let arg of this._get_args()) { + arg_strings.push(repr(arg)) + } + for (let [ name, value ] of this._get_kwargs()) { + if (/^[a-z_][a-z0-9_$]*$/i.test(name)) { + arg_strings.push(sub('%s=%r', name, value)) + } else { + star_args[name] = value + } + } + if (Object.keys(star_args).length) { + arg_strings.push(sub('**%s', repr(star_args))) + } + return sub('%s(%s)', type_name, arg_strings.join(', ')) + } + + toString() { + return this[util.inspect.custom]() + } + + _get_kwargs() { + return Object.entries(this) + } + + _get_args() { + return [] + } + } +} + + +function _copy_items(items) { + if (items === undefined) { + return [] + } + return items.slice(0) +} + + +// =============== +// Formatting Help +// =============== +const HelpFormatter = _camelcase_alias(_callable(class HelpFormatter { + /* + * Formatter for generating usage messages and argument help strings. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + */ + + constructor() { + let [ + prog, + indent_increment, + max_help_position, + width + ] = _parse_opts(arguments, { + prog: no_default, + indent_increment: 2, + max_help_position: 24, + width: undefined + }) + + // default setting for width + if (width === undefined) { + width = get_terminal_size().columns + width -= 2 + } + + this._prog = prog + this._indent_increment = indent_increment + this._max_help_position = Math.min(max_help_position, + Math.max(width - 20, indent_increment * 2)) + this._width = width + + this._current_indent = 0 + this._level = 0 + this._action_max_length = 0 + + this._root_section = this._Section(this, undefined) + this._current_section = this._root_section + + this._whitespace_matcher = /[ \t\n\r\f\v]+/g // equivalent to python /\s+/ with ASCII flag + this._long_break_matcher = /\n\n\n+/g + } + + // =============================== + // Section and indentation methods + // =============================== + _indent() { + this._current_indent += this._indent_increment + this._level += 1 + } + + _dedent() { + this._current_indent -= this._indent_increment + assert(this._current_indent >= 0, 'Indent decreased below 0.') + this._level -= 1 + } + + _add_item(func, args) { + this._current_section.items.push([ func, args ]) + } + + // ======================== + // Message building methods + // ======================== + start_section(heading) { + this._indent() + let section = this._Section(this, this._current_section, heading) + this._add_item(section.format_help.bind(section), []) + this._current_section = section + } + + end_section() { + this._current_section = this._current_section.parent + this._dedent() + } + + add_text(text) { + if (text !== SUPPRESS && text !== undefined) { + this._add_item(this._format_text.bind(this), [text]) + } + } + + add_usage(usage, actions, groups, prefix = undefined) { + if (usage !== SUPPRESS) { + let args = [ usage, actions, groups, prefix ] + this._add_item(this._format_usage.bind(this), args) + } + } + + add_argument(action) { + if (action.help !== SUPPRESS) { + + // find all invocations + let invocations = [this._format_action_invocation(action)] + for (let subaction of this._iter_indented_subactions(action)) { + invocations.push(this._format_action_invocation(subaction)) + } + + // update the maximum item length + let invocation_length = Math.max(...invocations.map(invocation => invocation.length)) + let action_length = invocation_length + this._current_indent + this._action_max_length = Math.max(this._action_max_length, + action_length) + + // add the item to the list + this._add_item(this._format_action.bind(this), [action]) + } + } + + add_arguments(actions) { + for (let action of actions) { + this.add_argument(action) + } + } + + // ======================= + // Help-formatting methods + // ======================= + format_help() { + let help = this._root_section.format_help() + if (help) { + help = help.replace(this._long_break_matcher, '\n\n') + help = help.replace(/^\n+|\n+$/g, '') + '\n' + } + return help + } + + _join_parts(part_strings) { + return part_strings.filter(part => part && part !== SUPPRESS).join('') + } + + _format_usage(usage, actions, groups, prefix) { + if (prefix === undefined) { + prefix = 'usage: ' + } + + // if usage is specified, use that + if (usage !== undefined) { + usage = sub(usage, { prog: this._prog }) + + // if no optionals or positionals are available, usage is just prog + } else if (usage === undefined && !actions.length) { + usage = sub('%(prog)s', { prog: this._prog }) + + // if optionals and positionals are available, calculate usage + } else if (usage === undefined) { + let prog = sub('%(prog)s', { prog: this._prog }) + + // split optionals from positionals + let optionals = [] + let positionals = [] + for (let action of actions) { + if (action.option_strings.length) { + optionals.push(action) + } else { + positionals.push(action) + } + } + + // build full usage string + let action_usage = this._format_actions_usage([].concat(optionals).concat(positionals), groups) + usage = [ prog, action_usage ].map(String).join(' ') + + // wrap the usage parts if it's too long + let text_width = this._width - this._current_indent + if (prefix.length + usage.length > text_width) { + + // break usage into wrappable parts + let part_regexp = /\(.*?\)+(?=\s|$)|\[.*?\]+(?=\s|$)|\S+/g + let opt_usage = this._format_actions_usage(optionals, groups) + let pos_usage = this._format_actions_usage(positionals, groups) + let opt_parts = opt_usage.match(part_regexp) || [] + let pos_parts = pos_usage.match(part_regexp) || [] + assert(opt_parts.join(' ') === opt_usage) + assert(pos_parts.join(' ') === pos_usage) + + // helper for wrapping lines + let get_lines = (parts, indent, prefix = undefined) => { + let lines = [] + let line = [] + let line_len + if (prefix !== undefined) { + line_len = prefix.length - 1 + } else { + line_len = indent.length - 1 + } + for (let part of parts) { + if (line_len + 1 + part.length > text_width && line) { + lines.push(indent + line.join(' ')) + line = [] + line_len = indent.length - 1 + } + line.push(part) + line_len += part.length + 1 + } + if (line.length) { + lines.push(indent + line.join(' ')) + } + if (prefix !== undefined) { + lines[0] = lines[0].slice(indent.length) + } + return lines + } + + let lines + + // if prog is short, follow it with optionals or positionals + if (prefix.length + prog.length <= 0.75 * text_width) { + let indent = ' '.repeat(prefix.length + prog.length + 1) + if (opt_parts.length) { + lines = get_lines([prog].concat(opt_parts), indent, prefix) + lines = lines.concat(get_lines(pos_parts, indent)) + } else if (pos_parts.length) { + lines = get_lines([prog].concat(pos_parts), indent, prefix) + } else { + lines = [prog] + } + + // if prog is long, put it on its own line + } else { + let indent = ' '.repeat(prefix.length) + let parts = [].concat(opt_parts).concat(pos_parts) + lines = get_lines(parts, indent) + if (lines.length > 1) { + lines = [] + lines = lines.concat(get_lines(opt_parts, indent)) + lines = lines.concat(get_lines(pos_parts, indent)) + } + lines = [prog].concat(lines) + } + + // join lines into usage + usage = lines.join('\n') + } + } + + // prefix with 'usage:' + return sub('%s%s\n\n', prefix, usage) + } + + _format_actions_usage(actions, groups) { + // find group indices and identify actions in groups + let group_actions = new Set() + let inserts = {} + for (let group of groups) { + let start = actions.indexOf(group._group_actions[0]) + if (start === -1) { + continue + } else { + let end = start + group._group_actions.length + if (_array_equal(actions.slice(start, end), group._group_actions)) { + for (let action of group._group_actions) { + group_actions.add(action) + } + if (!group.required) { + if (start in inserts) { + inserts[start] += ' [' + } else { + inserts[start] = '[' + } + if (end in inserts) { + inserts[end] += ']' + } else { + inserts[end] = ']' + } + } else { + if (start in inserts) { + inserts[start] += ' (' + } else { + inserts[start] = '(' + } + if (end in inserts) { + inserts[end] += ')' + } else { + inserts[end] = ')' + } + } + for (let i of range(start + 1, end)) { + inserts[i] = '|' + } + } + } + } + + // collect all actions format strings + let parts = [] + for (let [ i, action ] of Object.entries(actions)) { + + // suppressed arguments are marked with None + // remove | separators for suppressed arguments + if (action.help === SUPPRESS) { + parts.push(undefined) + if (inserts[+i] === '|') { + delete inserts[+i] + } else if (inserts[+i + 1] === '|') { + delete inserts[+i + 1] + } + + // produce all arg strings + } else if (!action.option_strings.length) { + let default_value = this._get_default_metavar_for_positional(action) + let part = this._format_args(action, default_value) + + // if it's in a group, strip the outer [] + if (group_actions.has(action)) { + if (part[0] === '[' && part[part.length - 1] === ']') { + part = part.slice(1, -1) + } + } + + // add the action string to the list + parts.push(part) + + // produce the first way to invoke the option in brackets + } else { + let option_string = action.option_strings[0] + let part + + // if the Optional doesn't take a value, format is: + // -s or --long + if (action.nargs === 0) { + part = action.format_usage() + + // if the Optional takes a value, format is: + // -s ARGS or --long ARGS + } else { + let default_value = this._get_default_metavar_for_optional(action) + let args_string = this._format_args(action, default_value) + part = sub('%s %s', option_string, args_string) + } + + // make it look optional if it's not required or in a group + if (!action.required && !group_actions.has(action)) { + part = sub('[%s]', part) + } + + // add the action string to the list + parts.push(part) + } + } + + // insert things at the necessary indices + for (let i of Object.keys(inserts).map(Number).sort((a, b) => b - a)) { + parts.splice(+i, 0, inserts[+i]) + } + + // join all the action items with spaces + let text = parts.filter(Boolean).join(' ') + + // clean up separators for mutually exclusive groups + text = text.replace(/([\[(]) /g, '$1') + text = text.replace(/ ([\])])/g, '$1') + text = text.replace(/[\[(] *[\])]/g, '') + text = text.replace(/\(([^|]*)\)/g, '$1', text) + text = text.trim() + + // return the text + return text + } + + _format_text(text) { + if (text.includes('%(prog)')) { + text = sub(text, { prog: this._prog }) + } + let text_width = Math.max(this._width - this._current_indent, 11) + let indent = ' '.repeat(this._current_indent) + return this._fill_text(text, text_width, indent) + '\n\n' + } + + _format_action(action) { + // determine the required width and the entry label + let help_position = Math.min(this._action_max_length + 2, + this._max_help_position) + let help_width = Math.max(this._width - help_position, 11) + let action_width = help_position - this._current_indent - 2 + let action_header = this._format_action_invocation(action) + let indent_first + + // no help; start on same line and add a final newline + if (!action.help) { + let tup = [ this._current_indent, '', action_header ] + action_header = sub('%*s%s\n', ...tup) + + // short action name; start on the same line and pad two spaces + } else if (action_header.length <= action_width) { + let tup = [ this._current_indent, '', action_width, action_header ] + action_header = sub('%*s%-*s ', ...tup) + indent_first = 0 + + // long action name; start on the next line + } else { + let tup = [ this._current_indent, '', action_header ] + action_header = sub('%*s%s\n', ...tup) + indent_first = help_position + } + + // collect the pieces of the action help + let parts = [action_header] + + // if there was help for the action, add lines of help text + if (action.help) { + let help_text = this._expand_help(action) + let help_lines = this._split_lines(help_text, help_width) + parts.push(sub('%*s%s\n', indent_first, '', help_lines[0])) + for (let line of help_lines.slice(1)) { + parts.push(sub('%*s%s\n', help_position, '', line)) + } + + // or add a newline if the description doesn't end with one + } else if (!action_header.endsWith('\n')) { + parts.push('\n') + } + + // if there are any sub-actions, add their help as well + for (let subaction of this._iter_indented_subactions(action)) { + parts.push(this._format_action(subaction)) + } + + // return a single string + return this._join_parts(parts) + } + + _format_action_invocation(action) { + if (!action.option_strings.length) { + let default_value = this._get_default_metavar_for_positional(action) + let metavar = this._metavar_formatter(action, default_value)(1)[0] + return metavar + + } else { + let parts = [] + + // if the Optional doesn't take a value, format is: + // -s, --long + if (action.nargs === 0) { + parts = parts.concat(action.option_strings) + + // if the Optional takes a value, format is: + // -s ARGS, --long ARGS + } else { + let default_value = this._get_default_metavar_for_optional(action) + let args_string = this._format_args(action, default_value) + for (let option_string of action.option_strings) { + parts.push(sub('%s %s', option_string, args_string)) + } + } + + return parts.join(', ') + } + } + + _metavar_formatter(action, default_metavar) { + let result + if (action.metavar !== undefined) { + result = action.metavar + } else if (action.choices !== undefined) { + let choice_strs = _choices_to_array(action.choices).map(String) + result = sub('{%s}', choice_strs.join(',')) + } else { + result = default_metavar + } + + function format(tuple_size) { + if (Array.isArray(result)) { + return result + } else { + return Array(tuple_size).fill(result) + } + } + return format + } + + _format_args(action, default_metavar) { + let get_metavar = this._metavar_formatter(action, default_metavar) + let result + if (action.nargs === undefined) { + result = sub('%s', ...get_metavar(1)) + } else if (action.nargs === OPTIONAL) { + result = sub('[%s]', ...get_metavar(1)) + } else if (action.nargs === ZERO_OR_MORE) { + let metavar = get_metavar(1) + if (metavar.length === 2) { + result = sub('[%s [%s ...]]', ...metavar) + } else { + result = sub('[%s ...]', ...metavar) + } + } else if (action.nargs === ONE_OR_MORE) { + result = sub('%s [%s ...]', ...get_metavar(2)) + } else if (action.nargs === REMAINDER) { + result = '...' + } else if (action.nargs === PARSER) { + result = sub('%s ...', ...get_metavar(1)) + } else if (action.nargs === SUPPRESS) { + result = '' + } else { + let formats + try { + formats = range(action.nargs).map(() => '%s') + } catch (err) { + throw new TypeError('invalid nargs value') + } + result = sub(formats.join(' '), ...get_metavar(action.nargs)) + } + return result + } + + _expand_help(action) { + let params = Object.assign({ prog: this._prog }, action) + for (let name of Object.keys(params)) { + if (params[name] === SUPPRESS) { + delete params[name] + } + } + for (let name of Object.keys(params)) { + if (params[name] && params[name].name) { + params[name] = params[name].name + } + } + if (params.choices !== undefined) { + let choices_str = _choices_to_array(params.choices).map(String).join(', ') + params.choices = choices_str + } + // LEGACY (v1 compatibility): camelcase + for (let key of Object.keys(params)) { + let old_name = _to_legacy_name(key) + if (old_name !== key) { + params[old_name] = params[key] + } + } + // end + return sub(this._get_help_string(action), params) + } + + * _iter_indented_subactions(action) { + if (typeof action._get_subactions === 'function') { + this._indent() + yield* action._get_subactions() + this._dedent() + } + } + + _split_lines(text, width) { + text = text.replace(this._whitespace_matcher, ' ').trim() + // The textwrap module is used only for formatting help. + // Delay its import for speeding up the common usage of argparse. + let textwrap = require('./lib/textwrap') + return textwrap.wrap(text, { width }) + } + + _fill_text(text, width, indent) { + text = text.replace(this._whitespace_matcher, ' ').trim() + let textwrap = require('./lib/textwrap') + return textwrap.fill(text, { width, + initial_indent: indent, + subsequent_indent: indent }) + } + + _get_help_string(action) { + return action.help + } + + _get_default_metavar_for_optional(action) { + return action.dest.toUpperCase() + } + + _get_default_metavar_for_positional(action) { + return action.dest + } +})) + +HelpFormatter.prototype._Section = _callable(class _Section { + + constructor(formatter, parent, heading = undefined) { + this.formatter = formatter + this.parent = parent + this.heading = heading + this.items = [] + } + + format_help() { + // format the indented section + if (this.parent !== undefined) { + this.formatter._indent() + } + let item_help = this.formatter._join_parts(this.items.map(([ func, args ]) => func.apply(null, args))) + if (this.parent !== undefined) { + this.formatter._dedent() + } + + // return nothing if the section was empty + if (!item_help) { + return '' + } + + // add the heading if the section was non-empty + let heading + if (this.heading !== SUPPRESS && this.heading !== undefined) { + let current_indent = this.formatter._current_indent + heading = sub('%*s%s:\n', current_indent, '', this.heading) + } else { + heading = '' + } + + // join the section-initial newline, the heading and the help + return this.formatter._join_parts(['\n', heading, item_help, '\n']) + } +}) + + +const RawDescriptionHelpFormatter = _camelcase_alias(_callable(class RawDescriptionHelpFormatter extends HelpFormatter { + /* + * Help message formatter which retains any formatting in descriptions. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + */ + + _fill_text(text, width, indent) { + return splitlines(text, true).map(line => indent + line).join('') + } +})) + + +const RawTextHelpFormatter = _camelcase_alias(_callable(class RawTextHelpFormatter extends RawDescriptionHelpFormatter { + /* + * Help message formatter which retains formatting of all help text. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + */ + + _split_lines(text/*, width*/) { + return splitlines(text) + } +})) + + +const ArgumentDefaultsHelpFormatter = _camelcase_alias(_callable(class ArgumentDefaultsHelpFormatter extends HelpFormatter { + /* + * Help message formatter which adds default values to argument help. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + */ + + _get_help_string(action) { + let help = action.help + // LEGACY (v1 compatibility): additional check for defaultValue needed + if (!action.help.includes('%(default)') && !action.help.includes('%(defaultValue)')) { + if (action.default !== SUPPRESS) { + let defaulting_nargs = [OPTIONAL, ZERO_OR_MORE] + if (action.option_strings.length || defaulting_nargs.includes(action.nargs)) { + help += ' (default: %(default)s)' + } + } + } + return help + } +})) + + +const MetavarTypeHelpFormatter = _camelcase_alias(_callable(class MetavarTypeHelpFormatter extends HelpFormatter { + /* + * Help message formatter which uses the argument 'type' as the default + * metavar value (instead of the argument 'dest') + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + */ + + _get_default_metavar_for_optional(action) { + return typeof action.type === 'function' ? action.type.name : action.type + } + + _get_default_metavar_for_positional(action) { + return typeof action.type === 'function' ? action.type.name : action.type + } +})) + + +// ===================== +// Options and Arguments +// ===================== +function _get_action_name(argument) { + if (argument === undefined) { + return undefined + } else if (argument.option_strings.length) { + return argument.option_strings.join('/') + } else if (![ undefined, SUPPRESS ].includes(argument.metavar)) { + return argument.metavar + } else if (![ undefined, SUPPRESS ].includes(argument.dest)) { + return argument.dest + } else { + return undefined + } +} + + +const ArgumentError = _callable(class ArgumentError extends Error { + /* + * An error from creating or using an argument (optional or positional). + * + * The string value of this exception is the message, augmented with + * information about the argument that caused it. + */ + + constructor(argument, message) { + super() + this.name = 'ArgumentError' + this._argument_name = _get_action_name(argument) + this._message = message + this.message = this.str() + } + + str() { + let format + if (this._argument_name === undefined) { + format = '%(message)s' + } else { + format = 'argument %(argument_name)s: %(message)s' + } + return sub(format, { message: this._message, + argument_name: this._argument_name }) + } +}) + + +const ArgumentTypeError = _callable(class ArgumentTypeError extends Error { + /* + * An error from trying to convert a command line string to a type. + */ + + constructor(message) { + super(message) + this.name = 'ArgumentTypeError' + } +}) + + +// ============== +// Action classes +// ============== +const Action = _camelcase_alias(_callable(class Action extends _AttributeHolder(Function) { + /* + * Information about how to convert command line strings to Python objects. + * + * Action objects are used by an ArgumentParser to represent the information + * needed to parse a single argument from one or more strings from the + * command line. The keyword arguments to the Action constructor are also + * all attributes of Action instances. + * + * Keyword Arguments: + * + * - option_strings -- A list of command-line option strings which + * should be associated with this action. + * + * - dest -- The name of the attribute to hold the created object(s) + * + * - nargs -- The number of command-line arguments that should be + * consumed. By default, one argument will be consumed and a single + * value will be produced. Other values include: + * - N (an integer) consumes N arguments (and produces a list) + * - '?' consumes zero or one arguments + * - '*' consumes zero or more arguments (and produces a list) + * - '+' consumes one or more arguments (and produces a list) + * Note that the difference between the default and nargs=1 is that + * with the default, a single value will be produced, while with + * nargs=1, a list containing a single value will be produced. + * + * - const -- The value to be produced if the option is specified and the + * option uses an action that takes no values. + * + * - default -- The value to be produced if the option is not specified. + * + * - type -- A callable that accepts a single string argument, and + * returns the converted value. The standard Python types str, int, + * float, and complex are useful examples of such callables. If None, + * str is used. + * + * - choices -- A container of values that should be allowed. If not None, + * after a command-line argument has been converted to the appropriate + * type, an exception will be raised if it is not a member of this + * collection. + * + * - required -- True if the action must always be specified at the + * command line. This is only meaningful for optional command-line + * arguments. + * + * - help -- The help string describing the argument. + * + * - metavar -- The name to be used for the option's argument with the + * help string. If None, the 'dest' value will be used as the name. + */ + + constructor() { + let [ + option_strings, + dest, + nargs, + const_value, + default_value, + type, + choices, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + nargs: undefined, + const: undefined, + default: undefined, + type: undefined, + choices: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + // when this class is called as a function, redirect it to .call() method of itself + super('return arguments.callee.call.apply(arguments.callee, arguments)') + + this.option_strings = option_strings + this.dest = dest + this.nargs = nargs + this.const = const_value + this.default = default_value + this.type = type + this.choices = choices + this.required = required + this.help = help + this.metavar = metavar + } + + _get_kwargs() { + let names = [ + 'option_strings', + 'dest', + 'nargs', + 'const', + 'default', + 'type', + 'choices', + 'help', + 'metavar' + ] + return names.map(name => [ name, getattr(this, name) ]) + } + + format_usage() { + return this.option_strings[0] + } + + call(/*parser, namespace, values, option_string = undefined*/) { + throw new Error('.call() not defined') + } +})) + + +const BooleanOptionalAction = _camelcase_alias(_callable(class BooleanOptionalAction extends Action { + + constructor() { + let [ + option_strings, + dest, + default_value, + type, + choices, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + default: undefined, + type: undefined, + choices: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + let _option_strings = [] + for (let option_string of option_strings) { + _option_strings.push(option_string) + + if (option_string.startsWith('--')) { + option_string = '--no-' + option_string.slice(2) + _option_strings.push(option_string) + } + } + + if (help !== undefined && default_value !== undefined) { + help += ` (default: ${default_value})` + } + + super({ + option_strings: _option_strings, + dest, + nargs: 0, + default: default_value, + type, + choices, + required, + help, + metavar + }) + } + + call(parser, namespace, values, option_string = undefined) { + if (this.option_strings.includes(option_string)) { + setattr(namespace, this.dest, !option_string.startsWith('--no-')) + } + } + + format_usage() { + return this.option_strings.join(' | ') + } +})) + + +const _StoreAction = _callable(class _StoreAction extends Action { + + constructor() { + let [ + option_strings, + dest, + nargs, + const_value, + default_value, + type, + choices, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + nargs: undefined, + const: undefined, + default: undefined, + type: undefined, + choices: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + if (nargs === 0) { + throw new TypeError('nargs for store actions must be != 0; if you ' + + 'have nothing to store, actions such as store ' + + 'true or store const may be more appropriate') + } + if (const_value !== undefined && nargs !== OPTIONAL) { + throw new TypeError(sub('nargs must be %r to supply const', OPTIONAL)) + } + super({ + option_strings, + dest, + nargs, + const: const_value, + default: default_value, + type, + choices, + required, + help, + metavar + }) + } + + call(parser, namespace, values/*, option_string = undefined*/) { + setattr(namespace, this.dest, values) + } +}) + + +const _StoreConstAction = _callable(class _StoreConstAction extends Action { + + constructor() { + let [ + option_strings, + dest, + const_value, + default_value, + required, + help + //, metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + const: no_default, + default: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + super({ + option_strings, + dest, + nargs: 0, + const: const_value, + default: default_value, + required, + help + }) + } + + call(parser, namespace/*, values, option_string = undefined*/) { + setattr(namespace, this.dest, this.const) + } +}) + + +const _StoreTrueAction = _callable(class _StoreTrueAction extends _StoreConstAction { + + constructor() { + let [ + option_strings, + dest, + default_value, + required, + help + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + default: false, + required: false, + help: undefined + }) + + super({ + option_strings, + dest, + const: true, + default: default_value, + required, + help + }) + } +}) + + +const _StoreFalseAction = _callable(class _StoreFalseAction extends _StoreConstAction { + + constructor() { + let [ + option_strings, + dest, + default_value, + required, + help + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + default: true, + required: false, + help: undefined + }) + + super({ + option_strings, + dest, + const: false, + default: default_value, + required, + help + }) + } +}) + + +const _AppendAction = _callable(class _AppendAction extends Action { + + constructor() { + let [ + option_strings, + dest, + nargs, + const_value, + default_value, + type, + choices, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + nargs: undefined, + const: undefined, + default: undefined, + type: undefined, + choices: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + if (nargs === 0) { + throw new TypeError('nargs for append actions must be != 0; if arg ' + + 'strings are not supplying the value to append, ' + + 'the append const action may be more appropriate') + } + if (const_value !== undefined && nargs !== OPTIONAL) { + throw new TypeError(sub('nargs must be %r to supply const', OPTIONAL)) + } + super({ + option_strings, + dest, + nargs, + const: const_value, + default: default_value, + type, + choices, + required, + help, + metavar + }) + } + + call(parser, namespace, values/*, option_string = undefined*/) { + let items = getattr(namespace, this.dest, undefined) + items = _copy_items(items) + items.push(values) + setattr(namespace, this.dest, items) + } +}) + + +const _AppendConstAction = _callable(class _AppendConstAction extends Action { + + constructor() { + let [ + option_strings, + dest, + const_value, + default_value, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + const: no_default, + default: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + super({ + option_strings, + dest, + nargs: 0, + const: const_value, + default: default_value, + required, + help, + metavar + }) + } + + call(parser, namespace/*, values, option_string = undefined*/) { + let items = getattr(namespace, this.dest, undefined) + items = _copy_items(items) + items.push(this.const) + setattr(namespace, this.dest, items) + } +}) + + +const _CountAction = _callable(class _CountAction extends Action { + + constructor() { + let [ + option_strings, + dest, + default_value, + required, + help + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + default: undefined, + required: false, + help: undefined + }) + + super({ + option_strings, + dest, + nargs: 0, + default: default_value, + required, + help + }) + } + + call(parser, namespace/*, values, option_string = undefined*/) { + let count = getattr(namespace, this.dest, undefined) + if (count === undefined) { + count = 0 + } + setattr(namespace, this.dest, count + 1) + } +}) + + +const _HelpAction = _callable(class _HelpAction extends Action { + + constructor() { + let [ + option_strings, + dest, + default_value, + help + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: SUPPRESS, + default: SUPPRESS, + help: undefined + }) + + super({ + option_strings, + dest, + default: default_value, + nargs: 0, + help + }) + } + + call(parser/*, namespace, values, option_string = undefined*/) { + parser.print_help() + parser.exit() + } +}) + + +const _VersionAction = _callable(class _VersionAction extends Action { + + constructor() { + let [ + option_strings, + version, + dest, + default_value, + help + ] = _parse_opts(arguments, { + option_strings: no_default, + version: undefined, + dest: SUPPRESS, + default: SUPPRESS, + help: "show program's version number and exit" + }) + + super({ + option_strings, + dest, + default: default_value, + nargs: 0, + help + }) + this.version = version + } + + call(parser/*, namespace, values, option_string = undefined*/) { + let version = this.version + if (version === undefined) { + version = parser.version + } + let formatter = parser._get_formatter() + formatter.add_text(version) + parser._print_message(formatter.format_help(), process.stdout) + parser.exit() + } +}) + + +const _SubParsersAction = _camelcase_alias(_callable(class _SubParsersAction extends Action { + + constructor() { + let [ + option_strings, + prog, + parser_class, + dest, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + prog: no_default, + parser_class: no_default, + dest: SUPPRESS, + required: false, + help: undefined, + metavar: undefined + }) + + let name_parser_map = {} + + super({ + option_strings, + dest, + nargs: PARSER, + choices: name_parser_map, + required, + help, + metavar + }) + + this._prog_prefix = prog + this._parser_class = parser_class + this._name_parser_map = name_parser_map + this._choices_actions = [] + } + + add_parser() { + let [ + name, + kwargs + ] = _parse_opts(arguments, { + name: no_default, + '**kwargs': no_default + }) + + // set prog from the existing prefix + if (kwargs.prog === undefined) { + kwargs.prog = sub('%s %s', this._prog_prefix, name) + } + + let aliases = getattr(kwargs, 'aliases', []) + delete kwargs.aliases + + // create a pseudo-action to hold the choice help + if ('help' in kwargs) { + let help = kwargs.help + delete kwargs.help + let choice_action = this._ChoicesPseudoAction(name, aliases, help) + this._choices_actions.push(choice_action) + } + + // create the parser and add it to the map + let parser = new this._parser_class(kwargs) + this._name_parser_map[name] = parser + + // make parser available under aliases also + for (let alias of aliases) { + this._name_parser_map[alias] = parser + } + + return parser + } + + _get_subactions() { + return this._choices_actions + } + + call(parser, namespace, values/*, option_string = undefined*/) { + let parser_name = values[0] + let arg_strings = values.slice(1) + + // set the parser name if requested + if (this.dest !== SUPPRESS) { + setattr(namespace, this.dest, parser_name) + } + + // select the parser + if (hasattr(this._name_parser_map, parser_name)) { + parser = this._name_parser_map[parser_name] + } else { + let args = {parser_name, + choices: this._name_parser_map.join(', ')} + let msg = sub('unknown parser %(parser_name)r (choices: %(choices)s)', args) + throw new ArgumentError(this, msg) + } + + // parse all the remaining options into the namespace + // store any unrecognized options on the object, so that the top + // level parser can decide what to do with them + + // In case this subparser defines new defaults, we parse them + // in a new namespace object and then update the original + // namespace for the relevant parts. + let subnamespace + [ subnamespace, arg_strings ] = parser.parse_known_args(arg_strings, undefined) + for (let [ key, value ] of Object.entries(subnamespace)) { + setattr(namespace, key, value) + } + + if (arg_strings.length) { + setdefault(namespace, _UNRECOGNIZED_ARGS_ATTR, []) + getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).push(...arg_strings) + } + } +})) + + +_SubParsersAction.prototype._ChoicesPseudoAction = _callable(class _ChoicesPseudoAction extends Action { + constructor(name, aliases, help) { + let metavar = name, dest = name + if (aliases.length) { + metavar += sub(' (%s)', aliases.join(', ')) + } + super({ option_strings: [], dest, help, metavar }) + } +}) + + +const _ExtendAction = _callable(class _ExtendAction extends _AppendAction { + call(parser, namespace, values/*, option_string = undefined*/) { + let items = getattr(namespace, this.dest, undefined) + items = _copy_items(items) + items = items.concat(values) + setattr(namespace, this.dest, items) + } +}) + + +// ============== +// Type classes +// ============== +const FileType = _callable(class FileType extends Function { + /* + * Factory for creating file object types + * + * Instances of FileType are typically passed as type= arguments to the + * ArgumentParser add_argument() method. + * + * Keyword Arguments: + * - mode -- A string indicating how the file is to be opened. Accepts the + * same values as the builtin open() function. + * - bufsize -- The file's desired buffer size. Accepts the same values as + * the builtin open() function. + * - encoding -- The file's encoding. Accepts the same values as the + * builtin open() function. + * - errors -- A string indicating how encoding and decoding errors are to + * be handled. Accepts the same value as the builtin open() function. + */ + + constructor() { + let [ + flags, + encoding, + mode, + autoClose, + emitClose, + start, + end, + highWaterMark, + fs + ] = _parse_opts(arguments, { + flags: 'r', + encoding: undefined, + mode: undefined, // 0o666 + autoClose: undefined, // true + emitClose: undefined, // false + start: undefined, // 0 + end: undefined, // Infinity + highWaterMark: undefined, // 64 * 1024 + fs: undefined + }) + + // when this class is called as a function, redirect it to .call() method of itself + super('return arguments.callee.call.apply(arguments.callee, arguments)') + + Object.defineProperty(this, 'name', { + get() { + return sub('FileType(%r)', flags) + } + }) + this._flags = flags + this._options = {} + if (encoding !== undefined) this._options.encoding = encoding + if (mode !== undefined) this._options.mode = mode + if (autoClose !== undefined) this._options.autoClose = autoClose + if (emitClose !== undefined) this._options.emitClose = emitClose + if (start !== undefined) this._options.start = start + if (end !== undefined) this._options.end = end + if (highWaterMark !== undefined) this._options.highWaterMark = highWaterMark + if (fs !== undefined) this._options.fs = fs + } + + call(string) { + // the special argument "-" means sys.std{in,out} + if (string === '-') { + if (this._flags.includes('r')) { + return process.stdin + } else if (this._flags.includes('w')) { + return process.stdout + } else { + let msg = sub('argument "-" with mode %r', this._flags) + throw new TypeError(msg) + } + } + + // all other arguments are used as file names + let fd + try { + fd = fs.openSync(string, this._flags, this._options.mode) + } catch (e) { + let args = { filename: string, error: e.message } + let message = "can't open '%(filename)s': %(error)s" + throw new ArgumentTypeError(sub(message, args)) + } + + let options = Object.assign({ fd, flags: this._flags }, this._options) + if (this._flags.includes('r')) { + return fs.createReadStream(undefined, options) + } else if (this._flags.includes('w')) { + return fs.createWriteStream(undefined, options) + } else { + let msg = sub('argument "%s" with mode %r', string, this._flags) + throw new TypeError(msg) + } + } + + [util.inspect.custom]() { + let args = [ this._flags ] + let kwargs = Object.entries(this._options).map(([ k, v ]) => { + if (k === 'mode') v = { value: v, [util.inspect.custom]() { return '0o' + this.value.toString(8) } } + return [ k, v ] + }) + let args_str = [] + .concat(args.filter(arg => arg !== -1).map(repr)) + .concat(kwargs.filter(([/*kw*/, arg]) => arg !== undefined) + .map(([kw, arg]) => sub('%s=%r', kw, arg))) + .join(', ') + return sub('%s(%s)', this.constructor.name, args_str) + } + + toString() { + return this[util.inspect.custom]() + } +}) + +// =========================== +// Optional and Positional Parsing +// =========================== +const Namespace = _callable(class Namespace extends _AttributeHolder() { + /* + * Simple object for storing attributes. + * + * Implements equality by attribute names and values, and provides a simple + * string representation. + */ + + constructor(options = {}) { + super() + Object.assign(this, options) + } +}) + +// unset string tag to mimic plain object +Namespace.prototype[Symbol.toStringTag] = undefined + + +const _ActionsContainer = _camelcase_alias(_callable(class _ActionsContainer { + + constructor() { + let [ + description, + prefix_chars, + argument_default, + conflict_handler + ] = _parse_opts(arguments, { + description: no_default, + prefix_chars: no_default, + argument_default: no_default, + conflict_handler: no_default + }) + + this.description = description + this.argument_default = argument_default + this.prefix_chars = prefix_chars + this.conflict_handler = conflict_handler + + // set up registries + this._registries = {} + + // register actions + this.register('action', undefined, _StoreAction) + this.register('action', 'store', _StoreAction) + this.register('action', 'store_const', _StoreConstAction) + this.register('action', 'store_true', _StoreTrueAction) + this.register('action', 'store_false', _StoreFalseAction) + this.register('action', 'append', _AppendAction) + this.register('action', 'append_const', _AppendConstAction) + this.register('action', 'count', _CountAction) + this.register('action', 'help', _HelpAction) + this.register('action', 'version', _VersionAction) + this.register('action', 'parsers', _SubParsersAction) + this.register('action', 'extend', _ExtendAction) + // LEGACY (v1 compatibility): camelcase variants + ;[ 'storeConst', 'storeTrue', 'storeFalse', 'appendConst' ].forEach(old_name => { + let new_name = _to_new_name(old_name) + this.register('action', old_name, util.deprecate(this._registry_get('action', new_name), + sub('{action: "%s"} is renamed to {action: "%s"}', old_name, new_name))) + }) + // end + + // raise an exception if the conflict handler is invalid + this._get_handler() + + // action storage + this._actions = [] + this._option_string_actions = {} + + // groups + this._action_groups = [] + this._mutually_exclusive_groups = [] + + // defaults storage + this._defaults = {} + + // determines whether an "option" looks like a negative number + this._negative_number_matcher = /^-\d+$|^-\d*\.\d+$/ + + // whether or not there are any optionals that look like negative + // numbers -- uses a list so it can be shared and edited + this._has_negative_number_optionals = [] + } + + // ==================== + // Registration methods + // ==================== + register(registry_name, value, object) { + let registry = setdefault(this._registries, registry_name, {}) + registry[value] = object + } + + _registry_get(registry_name, value, default_value = undefined) { + return getattr(this._registries[registry_name], value, default_value) + } + + // ================================== + // Namespace default accessor methods + // ================================== + set_defaults(kwargs) { + Object.assign(this._defaults, kwargs) + + // if these defaults match any existing arguments, replace + // the previous default on the object with the new one + for (let action of this._actions) { + if (action.dest in kwargs) { + action.default = kwargs[action.dest] + } + } + } + + get_default(dest) { + for (let action of this._actions) { + if (action.dest === dest && action.default !== undefined) { + return action.default + } + } + return this._defaults[dest] + } + + + // ======================= + // Adding argument actions + // ======================= + add_argument() { + /* + * add_argument(dest, ..., name=value, ...) + * add_argument(option_string, option_string, ..., name=value, ...) + */ + let [ + args, + kwargs + ] = _parse_opts(arguments, { + '*args': no_default, + '**kwargs': no_default + }) + // LEGACY (v1 compatibility), old-style add_argument([ args ], { options }) + if (args.length === 1 && Array.isArray(args[0])) { + args = args[0] + deprecate('argument-array', + sub('use add_argument(%(args)s, {...}) instead of add_argument([ %(args)s ], { ... })', { + args: args.map(repr).join(', ') + })) + } + // end + + // if no positional args are supplied or only one is supplied and + // it doesn't look like an option string, parse a positional + // argument + let chars = this.prefix_chars + if (!args.length || args.length === 1 && !chars.includes(args[0][0])) { + if (args.length && 'dest' in kwargs) { + throw new TypeError('dest supplied twice for positional argument') + } + kwargs = this._get_positional_kwargs(...args, kwargs) + + // otherwise, we're adding an optional argument + } else { + kwargs = this._get_optional_kwargs(...args, kwargs) + } + + // if no default was supplied, use the parser-level default + if (!('default' in kwargs)) { + let dest = kwargs.dest + if (dest in this._defaults) { + kwargs.default = this._defaults[dest] + } else if (this.argument_default !== undefined) { + kwargs.default = this.argument_default + } + } + + // create the action object, and add it to the parser + let action_class = this._pop_action_class(kwargs) + if (typeof action_class !== 'function') { + throw new TypeError(sub('unknown action "%s"', action_class)) + } + // eslint-disable-next-line new-cap + let action = new action_class(kwargs) + + // raise an error if the action type is not callable + let type_func = this._registry_get('type', action.type, action.type) + if (typeof type_func !== 'function') { + throw new TypeError(sub('%r is not callable', type_func)) + } + + if (type_func === FileType) { + throw new TypeError(sub('%r is a FileType class object, instance of it' + + ' must be passed', type_func)) + } + + // raise an error if the metavar does not match the type + if ('_get_formatter' in this) { + try { + this._get_formatter()._format_args(action, undefined) + } catch (err) { + // check for 'invalid nargs value' is an artifact of TypeError and ValueError in js being the same + if (err instanceof TypeError && err.message !== 'invalid nargs value') { + throw new TypeError('length of metavar tuple does not match nargs') + } else { + throw err + } + } + } + + return this._add_action(action) + } + + add_argument_group() { + let group = _ArgumentGroup(this, ...arguments) + this._action_groups.push(group) + return group + } + + add_mutually_exclusive_group() { + // eslint-disable-next-line no-use-before-define + let group = _MutuallyExclusiveGroup(this, ...arguments) + this._mutually_exclusive_groups.push(group) + return group + } + + _add_action(action) { + // resolve any conflicts + this._check_conflict(action) + + // add to actions list + this._actions.push(action) + action.container = this + + // index the action by any option strings it has + for (let option_string of action.option_strings) { + this._option_string_actions[option_string] = action + } + + // set the flag if any option strings look like negative numbers + for (let option_string of action.option_strings) { + if (this._negative_number_matcher.test(option_string)) { + if (!this._has_negative_number_optionals.length) { + this._has_negative_number_optionals.push(true) + } + } + } + + // return the created action + return action + } + + _remove_action(action) { + _array_remove(this._actions, action) + } + + _add_container_actions(container) { + // collect groups by titles + let title_group_map = {} + for (let group of this._action_groups) { + if (group.title in title_group_map) { + let msg = 'cannot merge actions - two groups are named %r' + throw new TypeError(sub(msg, group.title)) + } + title_group_map[group.title] = group + } + + // map each action to its group + let group_map = new Map() + for (let group of container._action_groups) { + + // if a group with the title exists, use that, otherwise + // create a new group matching the container's group + if (!(group.title in title_group_map)) { + title_group_map[group.title] = this.add_argument_group({ + title: group.title, + description: group.description, + conflict_handler: group.conflict_handler + }) + } + + // map the actions to their new group + for (let action of group._group_actions) { + group_map.set(action, title_group_map[group.title]) + } + } + + // add container's mutually exclusive groups + // NOTE: if add_mutually_exclusive_group ever gains title= and + // description= then this code will need to be expanded as above + for (let group of container._mutually_exclusive_groups) { + let mutex_group = this.add_mutually_exclusive_group({ + required: group.required + }) + + // map the actions to their new mutex group + for (let action of group._group_actions) { + group_map.set(action, mutex_group) + } + } + + // add all actions to this container or their group + for (let action of container._actions) { + group_map.get(action)._add_action(action) + } + } + + _get_positional_kwargs() { + let [ + dest, + kwargs + ] = _parse_opts(arguments, { + dest: no_default, + '**kwargs': no_default + }) + + // make sure required is not specified + if ('required' in kwargs) { + let msg = "'required' is an invalid argument for positionals" + throw new TypeError(msg) + } + + // mark positional arguments as required if at least one is + // always required + if (![OPTIONAL, ZERO_OR_MORE].includes(kwargs.nargs)) { + kwargs.required = true + } + if (kwargs.nargs === ZERO_OR_MORE && !('default' in kwargs)) { + kwargs.required = true + } + + // return the keyword arguments with no option strings + return Object.assign(kwargs, { dest, option_strings: [] }) + } + + _get_optional_kwargs() { + let [ + args, + kwargs + ] = _parse_opts(arguments, { + '*args': no_default, + '**kwargs': no_default + }) + + // determine short and long option strings + let option_strings = [] + let long_option_strings = [] + let option_string + for (option_string of args) { + // error on strings that don't start with an appropriate prefix + if (!this.prefix_chars.includes(option_string[0])) { + let args = {option: option_string, + prefix_chars: this.prefix_chars} + let msg = 'invalid option string %(option)r: ' + + 'must start with a character %(prefix_chars)r' + throw new TypeError(sub(msg, args)) + } + + // strings starting with two prefix characters are long options + option_strings.push(option_string) + if (option_string.length > 1 && this.prefix_chars.includes(option_string[1])) { + long_option_strings.push(option_string) + } + } + + // infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' + let dest = kwargs.dest + delete kwargs.dest + if (dest === undefined) { + let dest_option_string + if (long_option_strings.length) { + dest_option_string = long_option_strings[0] + } else { + dest_option_string = option_strings[0] + } + dest = _string_lstrip(dest_option_string, this.prefix_chars) + if (!dest) { + let msg = 'dest= is required for options like %r' + throw new TypeError(sub(msg, option_string)) + } + dest = dest.replace(/-/g, '_') + } + + // return the updated keyword arguments + return Object.assign(kwargs, { dest, option_strings }) + } + + _pop_action_class(kwargs, default_value = undefined) { + let action = getattr(kwargs, 'action', default_value) + delete kwargs.action + return this._registry_get('action', action, action) + } + + _get_handler() { + // determine function from conflict handler string + let handler_func_name = sub('_handle_conflict_%s', this.conflict_handler) + if (typeof this[handler_func_name] === 'function') { + return this[handler_func_name] + } else { + let msg = 'invalid conflict_resolution value: %r' + throw new TypeError(sub(msg, this.conflict_handler)) + } + } + + _check_conflict(action) { + + // find all options that conflict with this option + let confl_optionals = [] + for (let option_string of action.option_strings) { + if (hasattr(this._option_string_actions, option_string)) { + let confl_optional = this._option_string_actions[option_string] + confl_optionals.push([ option_string, confl_optional ]) + } + } + + // resolve any conflicts + if (confl_optionals.length) { + let conflict_handler = this._get_handler() + conflict_handler.call(this, action, confl_optionals) + } + } + + _handle_conflict_error(action, conflicting_actions) { + let message = conflicting_actions.length === 1 ? + 'conflicting option string: %s' : + 'conflicting option strings: %s' + let conflict_string = conflicting_actions.map(([ option_string/*, action*/ ]) => option_string).join(', ') + throw new ArgumentError(action, sub(message, conflict_string)) + } + + _handle_conflict_resolve(action, conflicting_actions) { + + // remove all conflicting options + for (let [ option_string, action ] of conflicting_actions) { + + // remove the conflicting option + _array_remove(action.option_strings, option_string) + delete this._option_string_actions[option_string] + + // if the option now has no option string, remove it from the + // container holding it + if (!action.option_strings.length) { + action.container._remove_action(action) + } + } + } +})) + + +const _ArgumentGroup = _callable(class _ArgumentGroup extends _ActionsContainer { + + constructor() { + let [ + container, + title, + description, + kwargs + ] = _parse_opts(arguments, { + container: no_default, + title: undefined, + description: undefined, + '**kwargs': no_default + }) + + // add any missing keyword arguments by checking the container + setdefault(kwargs, 'conflict_handler', container.conflict_handler) + setdefault(kwargs, 'prefix_chars', container.prefix_chars) + setdefault(kwargs, 'argument_default', container.argument_default) + super(Object.assign({ description }, kwargs)) + + // group attributes + this.title = title + this._group_actions = [] + + // share most attributes with the container + this._registries = container._registries + this._actions = container._actions + this._option_string_actions = container._option_string_actions + this._defaults = container._defaults + this._has_negative_number_optionals = + container._has_negative_number_optionals + this._mutually_exclusive_groups = container._mutually_exclusive_groups + } + + _add_action(action) { + action = super._add_action(action) + this._group_actions.push(action) + return action + } + + _remove_action(action) { + super._remove_action(action) + _array_remove(this._group_actions, action) + } +}) + + +const _MutuallyExclusiveGroup = _callable(class _MutuallyExclusiveGroup extends _ArgumentGroup { + + constructor() { + let [ + container, + required + ] = _parse_opts(arguments, { + container: no_default, + required: false + }) + + super(container) + this.required = required + this._container = container + } + + _add_action(action) { + if (action.required) { + let msg = 'mutually exclusive arguments must be optional' + throw new TypeError(msg) + } + action = this._container._add_action(action) + this._group_actions.push(action) + return action + } + + _remove_action(action) { + this._container._remove_action(action) + _array_remove(this._group_actions, action) + } +}) + + +const ArgumentParser = _camelcase_alias(_callable(class ArgumentParser extends _AttributeHolder(_ActionsContainer) { + /* + * Object for parsing command line strings into Python objects. + * + * Keyword Arguments: + * - prog -- The name of the program (default: sys.argv[0]) + * - usage -- A usage message (default: auto-generated from arguments) + * - description -- A description of what the program does + * - epilog -- Text following the argument descriptions + * - parents -- Parsers whose arguments should be copied into this one + * - formatter_class -- HelpFormatter class for printing help messages + * - prefix_chars -- Characters that prefix optional arguments + * - fromfile_prefix_chars -- Characters that prefix files containing + * additional arguments + * - argument_default -- The default value for all arguments + * - conflict_handler -- String indicating how to handle conflicts + * - add_help -- Add a -h/-help option + * - allow_abbrev -- Allow long options to be abbreviated unambiguously + * - exit_on_error -- Determines whether or not ArgumentParser exits with + * error info when an error occurs + */ + + constructor() { + let [ + prog, + usage, + description, + epilog, + parents, + formatter_class, + prefix_chars, + fromfile_prefix_chars, + argument_default, + conflict_handler, + add_help, + allow_abbrev, + exit_on_error, + debug, // LEGACY (v1 compatibility), debug mode + version // LEGACY (v1 compatibility), version + ] = _parse_opts(arguments, { + prog: undefined, + usage: undefined, + description: undefined, + epilog: undefined, + parents: [], + formatter_class: HelpFormatter, + prefix_chars: '-', + fromfile_prefix_chars: undefined, + argument_default: undefined, + conflict_handler: 'error', + add_help: true, + allow_abbrev: true, + exit_on_error: true, + debug: undefined, // LEGACY (v1 compatibility), debug mode + version: undefined // LEGACY (v1 compatibility), version + }) + + // LEGACY (v1 compatibility) + if (debug !== undefined) { + deprecate('debug', + 'The "debug" argument to ArgumentParser is deprecated. Please ' + + 'override ArgumentParser.exit function instead.' + ) + } + + if (version !== undefined) { + deprecate('version', + 'The "version" argument to ArgumentParser is deprecated. Please use ' + + "add_argument(..., { action: 'version', version: 'N', ... }) instead." + ) + } + // end + + super({ + description, + prefix_chars, + argument_default, + conflict_handler + }) + + // default setting for prog + if (prog === undefined) { + prog = path.basename(get_argv()[0] || '') + } + + this.prog = prog + this.usage = usage + this.epilog = epilog + this.formatter_class = formatter_class + this.fromfile_prefix_chars = fromfile_prefix_chars + this.add_help = add_help + this.allow_abbrev = allow_abbrev + this.exit_on_error = exit_on_error + // LEGACY (v1 compatibility), debug mode + this.debug = debug + // end + + this._positionals = this.add_argument_group('positional arguments') + this._optionals = this.add_argument_group('optional arguments') + this._subparsers = undefined + + // register types + function identity(string) { + return string + } + this.register('type', undefined, identity) + this.register('type', null, identity) + this.register('type', 'auto', identity) + this.register('type', 'int', function (x) { + let result = Number(x) + if (!Number.isInteger(result)) { + throw new TypeError(sub('could not convert string to int: %r', x)) + } + return result + }) + this.register('type', 'float', function (x) { + let result = Number(x) + if (isNaN(result)) { + throw new TypeError(sub('could not convert string to float: %r', x)) + } + return result + }) + this.register('type', 'str', String) + // LEGACY (v1 compatibility): custom types + this.register('type', 'string', + util.deprecate(String, 'use {type:"str"} or {type:String} instead of {type:"string"}')) + // end + + // add help argument if necessary + // (using explicit default to override global argument_default) + let default_prefix = prefix_chars.includes('-') ? '-' : prefix_chars[0] + if (this.add_help) { + this.add_argument( + default_prefix + 'h', + default_prefix.repeat(2) + 'help', + { + action: 'help', + default: SUPPRESS, + help: 'show this help message and exit' + } + ) + } + // LEGACY (v1 compatibility), version + if (version) { + this.add_argument( + default_prefix + 'v', + default_prefix.repeat(2) + 'version', + { + action: 'version', + default: SUPPRESS, + version: this.version, + help: "show program's version number and exit" + } + ) + } + // end + + // add parent arguments and defaults + for (let parent of parents) { + this._add_container_actions(parent) + Object.assign(this._defaults, parent._defaults) + } + } + + // ======================= + // Pretty __repr__ methods + // ======================= + _get_kwargs() { + let names = [ + 'prog', + 'usage', + 'description', + 'formatter_class', + 'conflict_handler', + 'add_help' + ] + return names.map(name => [ name, getattr(this, name) ]) + } + + // ================================== + // Optional/Positional adding methods + // ================================== + add_subparsers() { + let [ + kwargs + ] = _parse_opts(arguments, { + '**kwargs': no_default + }) + + if (this._subparsers !== undefined) { + this.error('cannot have multiple subparser arguments') + } + + // add the parser class to the arguments if it's not present + setdefault(kwargs, 'parser_class', this.constructor) + + if ('title' in kwargs || 'description' in kwargs) { + let title = getattr(kwargs, 'title', 'subcommands') + let description = getattr(kwargs, 'description', undefined) + delete kwargs.title + delete kwargs.description + this._subparsers = this.add_argument_group(title, description) + } else { + this._subparsers = this._positionals + } + + // prog defaults to the usage message of this parser, skipping + // optional arguments and with no "usage:" prefix + if (kwargs.prog === undefined) { + let formatter = this._get_formatter() + let positionals = this._get_positional_actions() + let groups = this._mutually_exclusive_groups + formatter.add_usage(this.usage, positionals, groups, '') + kwargs.prog = formatter.format_help().trim() + } + + // create the parsers action and add it to the positionals list + let parsers_class = this._pop_action_class(kwargs, 'parsers') + // eslint-disable-next-line new-cap + let action = new parsers_class(Object.assign({ option_strings: [] }, kwargs)) + this._subparsers._add_action(action) + + // return the created parsers action + return action + } + + _add_action(action) { + if (action.option_strings.length) { + this._optionals._add_action(action) + } else { + this._positionals._add_action(action) + } + return action + } + + _get_optional_actions() { + return this._actions.filter(action => action.option_strings.length) + } + + _get_positional_actions() { + return this._actions.filter(action => !action.option_strings.length) + } + + // ===================================== + // Command line argument parsing methods + // ===================================== + parse_args(args = undefined, namespace = undefined) { + let argv + [ args, argv ] = this.parse_known_args(args, namespace) + if (argv && argv.length > 0) { + let msg = 'unrecognized arguments: %s' + this.error(sub(msg, argv.join(' '))) + } + return args + } + + parse_known_args(args = undefined, namespace = undefined) { + if (args === undefined) { + args = get_argv().slice(1) + } + + // default Namespace built from parser defaults + if (namespace === undefined) { + namespace = new Namespace() + } + + // add any action defaults that aren't present + for (let action of this._actions) { + if (action.dest !== SUPPRESS) { + if (!hasattr(namespace, action.dest)) { + if (action.default !== SUPPRESS) { + setattr(namespace, action.dest, action.default) + } + } + } + } + + // add any parser defaults that aren't present + for (let dest of Object.keys(this._defaults)) { + if (!hasattr(namespace, dest)) { + setattr(namespace, dest, this._defaults[dest]) + } + } + + // parse the arguments and exit if there are any errors + if (this.exit_on_error) { + try { + [ namespace, args ] = this._parse_known_args(args, namespace) + } catch (err) { + if (err instanceof ArgumentError) { + this.error(err.message) + } else { + throw err + } + } + } else { + [ namespace, args ] = this._parse_known_args(args, namespace) + } + + if (hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) { + args = args.concat(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) + delattr(namespace, _UNRECOGNIZED_ARGS_ATTR) + } + + return [ namespace, args ] + } + + _parse_known_args(arg_strings, namespace) { + // replace arg strings that are file references + if (this.fromfile_prefix_chars !== undefined) { + arg_strings = this._read_args_from_files(arg_strings) + } + + // map all mutually exclusive arguments to the other arguments + // they can't occur with + let action_conflicts = new Map() + for (let mutex_group of this._mutually_exclusive_groups) { + let group_actions = mutex_group._group_actions + for (let [ i, mutex_action ] of Object.entries(mutex_group._group_actions)) { + let conflicts = action_conflicts.get(mutex_action) || [] + conflicts = conflicts.concat(group_actions.slice(0, +i)) + conflicts = conflicts.concat(group_actions.slice(+i + 1)) + action_conflicts.set(mutex_action, conflicts) + } + } + + // find all option indices, and determine the arg_string_pattern + // which has an 'O' if there is an option at an index, + // an 'A' if there is an argument, or a '-' if there is a '--' + let option_string_indices = {} + let arg_string_pattern_parts = [] + let arg_strings_iter = Object.entries(arg_strings)[Symbol.iterator]() + for (let [ i, arg_string ] of arg_strings_iter) { + + // all args after -- are non-options + if (arg_string === '--') { + arg_string_pattern_parts.push('-') + for ([ i, arg_string ] of arg_strings_iter) { + arg_string_pattern_parts.push('A') + } + + // otherwise, add the arg to the arg strings + // and note the index if it was an option + } else { + let option_tuple = this._parse_optional(arg_string) + let pattern + if (option_tuple === undefined) { + pattern = 'A' + } else { + option_string_indices[i] = option_tuple + pattern = 'O' + } + arg_string_pattern_parts.push(pattern) + } + } + + // join the pieces together to form the pattern + let arg_strings_pattern = arg_string_pattern_parts.join('') + + // converts arg strings to the appropriate and then takes the action + let seen_actions = new Set() + let seen_non_default_actions = new Set() + let extras + + let take_action = (action, argument_strings, option_string = undefined) => { + seen_actions.add(action) + let argument_values = this._get_values(action, argument_strings) + + // error if this argument is not allowed with other previously + // seen arguments, assuming that actions that use the default + // value don't really count as "present" + if (argument_values !== action.default) { + seen_non_default_actions.add(action) + for (let conflict_action of action_conflicts.get(action) || []) { + if (seen_non_default_actions.has(conflict_action)) { + let msg = 'not allowed with argument %s' + let action_name = _get_action_name(conflict_action) + throw new ArgumentError(action, sub(msg, action_name)) + } + } + } + + // take the action if we didn't receive a SUPPRESS value + // (e.g. from a default) + if (argument_values !== SUPPRESS) { + action(this, namespace, argument_values, option_string) + } + } + + // function to convert arg_strings into an optional action + let consume_optional = start_index => { + + // get the optional identified at this index + let option_tuple = option_string_indices[start_index] + let [ action, option_string, explicit_arg ] = option_tuple + + // identify additional optionals in the same arg string + // (e.g. -xyz is the same as -x -y -z if no args are required) + let action_tuples = [] + let stop + for (;;) { + + // if we found no optional action, skip it + if (action === undefined) { + extras.push(arg_strings[start_index]) + return start_index + 1 + } + + // if there is an explicit argument, try to match the + // optional's string arguments to only this + if (explicit_arg !== undefined) { + let arg_count = this._match_argument(action, 'A') + + // if the action is a single-dash option and takes no + // arguments, try to parse more single-dash options out + // of the tail of the option string + let chars = this.prefix_chars + if (arg_count === 0 && !chars.includes(option_string[1])) { + action_tuples.push([ action, [], option_string ]) + let char = option_string[0] + option_string = char + explicit_arg[0] + let new_explicit_arg = explicit_arg.slice(1) || undefined + let optionals_map = this._option_string_actions + if (hasattr(optionals_map, option_string)) { + action = optionals_map[option_string] + explicit_arg = new_explicit_arg + } else { + let msg = 'ignored explicit argument %r' + throw new ArgumentError(action, sub(msg, explicit_arg)) + } + + // if the action expect exactly one argument, we've + // successfully matched the option; exit the loop + } else if (arg_count === 1) { + stop = start_index + 1 + let args = [ explicit_arg ] + action_tuples.push([ action, args, option_string ]) + break + + // error if a double-dash option did not use the + // explicit argument + } else { + let msg = 'ignored explicit argument %r' + throw new ArgumentError(action, sub(msg, explicit_arg)) + } + + // if there is no explicit argument, try to match the + // optional's string arguments with the following strings + // if successful, exit the loop + } else { + let start = start_index + 1 + let selected_patterns = arg_strings_pattern.slice(start) + let arg_count = this._match_argument(action, selected_patterns) + stop = start + arg_count + let args = arg_strings.slice(start, stop) + action_tuples.push([ action, args, option_string ]) + break + } + } + + // add the Optional to the list and return the index at which + // the Optional's string args stopped + assert(action_tuples.length) + for (let [ action, args, option_string ] of action_tuples) { + take_action(action, args, option_string) + } + return stop + } + + // the list of Positionals left to be parsed; this is modified + // by consume_positionals() + let positionals = this._get_positional_actions() + + // function to convert arg_strings into positional actions + let consume_positionals = start_index => { + // match as many Positionals as possible + let selected_pattern = arg_strings_pattern.slice(start_index) + let arg_counts = this._match_arguments_partial(positionals, selected_pattern) + + // slice off the appropriate arg strings for each Positional + // and add the Positional and its args to the list + for (let i = 0; i < positionals.length && i < arg_counts.length; i++) { + let action = positionals[i] + let arg_count = arg_counts[i] + let args = arg_strings.slice(start_index, start_index + arg_count) + start_index += arg_count + take_action(action, args) + } + + // slice off the Positionals that we just parsed and return the + // index at which the Positionals' string args stopped + positionals = positionals.slice(arg_counts.length) + return start_index + } + + // consume Positionals and Optionals alternately, until we have + // passed the last option string + extras = [] + let start_index = 0 + let max_option_string_index = Math.max(-1, ...Object.keys(option_string_indices).map(Number)) + while (start_index <= max_option_string_index) { + + // consume any Positionals preceding the next option + let next_option_string_index = Math.min( + // eslint-disable-next-line no-loop-func + ...Object.keys(option_string_indices).map(Number).filter(index => index >= start_index) + ) + if (start_index !== next_option_string_index) { + let positionals_end_index = consume_positionals(start_index) + + // only try to parse the next optional if we didn't consume + // the option string during the positionals parsing + if (positionals_end_index > start_index) { + start_index = positionals_end_index + continue + } else { + start_index = positionals_end_index + } + } + + // if we consumed all the positionals we could and we're not + // at the index of an option string, there were extra arguments + if (!(start_index in option_string_indices)) { + let strings = arg_strings.slice(start_index, next_option_string_index) + extras = extras.concat(strings) + start_index = next_option_string_index + } + + // consume the next optional and any arguments for it + start_index = consume_optional(start_index) + } + + // consume any positionals following the last Optional + let stop_index = consume_positionals(start_index) + + // if we didn't consume all the argument strings, there were extras + extras = extras.concat(arg_strings.slice(stop_index)) + + // make sure all required actions were present and also convert + // action defaults which were not given as arguments + let required_actions = [] + for (let action of this._actions) { + if (!seen_actions.has(action)) { + if (action.required) { + required_actions.push(_get_action_name(action)) + } else { + // Convert action default now instead of doing it before + // parsing arguments to avoid calling convert functions + // twice (which may fail) if the argument was given, but + // only if it was defined already in the namespace + if (action.default !== undefined && + typeof action.default === 'string' && + hasattr(namespace, action.dest) && + action.default === getattr(namespace, action.dest)) { + setattr(namespace, action.dest, + this._get_value(action, action.default)) + } + } + } + } + + if (required_actions.length) { + this.error(sub('the following arguments are required: %s', + required_actions.join(', '))) + } + + // make sure all required groups had one option present + for (let group of this._mutually_exclusive_groups) { + if (group.required) { + let no_actions_used = true + for (let action of group._group_actions) { + if (seen_non_default_actions.has(action)) { + no_actions_used = false + break + } + } + + // if no actions were used, report the error + if (no_actions_used) { + let names = group._group_actions + .filter(action => action.help !== SUPPRESS) + .map(action => _get_action_name(action)) + let msg = 'one of the arguments %s is required' + this.error(sub(msg, names.join(' '))) + } + } + } + + // return the updated namespace and the extra arguments + return [ namespace, extras ] + } + + _read_args_from_files(arg_strings) { + // expand arguments referencing files + let new_arg_strings = [] + for (let arg_string of arg_strings) { + + // for regular arguments, just add them back into the list + if (!arg_string || !this.fromfile_prefix_chars.includes(arg_string[0])) { + new_arg_strings.push(arg_string) + + // replace arguments referencing files with the file content + } else { + try { + let args_file = fs.readFileSync(arg_string.slice(1), 'utf8') + let arg_strings = [] + for (let arg_line of splitlines(args_file)) { + for (let arg of this.convert_arg_line_to_args(arg_line)) { + arg_strings.push(arg) + } + } + arg_strings = this._read_args_from_files(arg_strings) + new_arg_strings = new_arg_strings.concat(arg_strings) + } catch (err) { + this.error(err.message) + } + } + } + + // return the modified argument list + return new_arg_strings + } + + convert_arg_line_to_args(arg_line) { + return [arg_line] + } + + _match_argument(action, arg_strings_pattern) { + // match the pattern for this action to the arg strings + let nargs_pattern = this._get_nargs_pattern(action) + let match = arg_strings_pattern.match(new RegExp('^' + nargs_pattern)) + + // raise an exception if we weren't able to find a match + if (match === null) { + let nargs_errors = { + undefined: 'expected one argument', + [OPTIONAL]: 'expected at most one argument', + [ONE_OR_MORE]: 'expected at least one argument' + } + let msg = nargs_errors[action.nargs] + if (msg === undefined) { + msg = sub(action.nargs === 1 ? 'expected %s argument' : 'expected %s arguments', action.nargs) + } + throw new ArgumentError(action, msg) + } + + // return the number of arguments matched + return match[1].length + } + + _match_arguments_partial(actions, arg_strings_pattern) { + // progressively shorten the actions list by slicing off the + // final actions until we find a match + let result = [] + for (let i of range(actions.length, 0, -1)) { + let actions_slice = actions.slice(0, i) + let pattern = actions_slice.map(action => this._get_nargs_pattern(action)).join('') + let match = arg_strings_pattern.match(new RegExp('^' + pattern)) + if (match !== null) { + result = result.concat(match.slice(1).map(string => string.length)) + break + } + } + + // return the list of arg string counts + return result + } + + _parse_optional(arg_string) { + // if it's an empty string, it was meant to be a positional + if (!arg_string) { + return undefined + } + + // if it doesn't start with a prefix, it was meant to be positional + if (!this.prefix_chars.includes(arg_string[0])) { + return undefined + } + + // if the option string is present in the parser, return the action + if (arg_string in this._option_string_actions) { + let action = this._option_string_actions[arg_string] + return [ action, arg_string, undefined ] + } + + // if it's just a single character, it was meant to be positional + if (arg_string.length === 1) { + return undefined + } + + // if the option string before the "=" is present, return the action + if (arg_string.includes('=')) { + let [ option_string, explicit_arg ] = _string_split(arg_string, '=', 1) + if (option_string in this._option_string_actions) { + let action = this._option_string_actions[option_string] + return [ action, option_string, explicit_arg ] + } + } + + // search through all possible prefixes of the option string + // and all actions in the parser for possible interpretations + let option_tuples = this._get_option_tuples(arg_string) + + // if multiple actions match, the option string was ambiguous + if (option_tuples.length > 1) { + let options = option_tuples.map(([ /*action*/, option_string/*, explicit_arg*/ ]) => option_string).join(', ') + let args = {option: arg_string, matches: options} + let msg = 'ambiguous option: %(option)s could match %(matches)s' + this.error(sub(msg, args)) + + // if exactly one action matched, this segmentation is good, + // so return the parsed action + } else if (option_tuples.length === 1) { + let [ option_tuple ] = option_tuples + return option_tuple + } + + // if it was not found as an option, but it looks like a negative + // number, it was meant to be positional + // unless there are negative-number-like options + if (this._negative_number_matcher.test(arg_string)) { + if (!this._has_negative_number_optionals.length) { + return undefined + } + } + + // if it contains a space, it was meant to be a positional + if (arg_string.includes(' ')) { + return undefined + } + + // it was meant to be an optional but there is no such option + // in this parser (though it might be a valid option in a subparser) + return [ undefined, arg_string, undefined ] + } + + _get_option_tuples(option_string) { + let result = [] + + // option strings starting with two prefix characters are only + // split at the '=' + let chars = this.prefix_chars + if (chars.includes(option_string[0]) && chars.includes(option_string[1])) { + if (this.allow_abbrev) { + let option_prefix, explicit_arg + if (option_string.includes('=')) { + [ option_prefix, explicit_arg ] = _string_split(option_string, '=', 1) + } else { + option_prefix = option_string + explicit_arg = undefined + } + for (let option_string of Object.keys(this._option_string_actions)) { + if (option_string.startsWith(option_prefix)) { + let action = this._option_string_actions[option_string] + let tup = [ action, option_string, explicit_arg ] + result.push(tup) + } + } + } + + // single character options can be concatenated with their arguments + // but multiple character options always have to have their argument + // separate + } else if (chars.includes(option_string[0]) && !chars.includes(option_string[1])) { + let option_prefix = option_string + let explicit_arg = undefined + let short_option_prefix = option_string.slice(0, 2) + let short_explicit_arg = option_string.slice(2) + + for (let option_string of Object.keys(this._option_string_actions)) { + if (option_string === short_option_prefix) { + let action = this._option_string_actions[option_string] + let tup = [ action, option_string, short_explicit_arg ] + result.push(tup) + } else if (option_string.startsWith(option_prefix)) { + let action = this._option_string_actions[option_string] + let tup = [ action, option_string, explicit_arg ] + result.push(tup) + } + } + + // shouldn't ever get here + } else { + this.error(sub('unexpected option string: %s', option_string)) + } + + // return the collected option tuples + return result + } + + _get_nargs_pattern(action) { + // in all examples below, we have to allow for '--' args + // which are represented as '-' in the pattern + let nargs = action.nargs + let nargs_pattern + + // the default (None) is assumed to be a single argument + if (nargs === undefined) { + nargs_pattern = '(-*A-*)' + + // allow zero or one arguments + } else if (nargs === OPTIONAL) { + nargs_pattern = '(-*A?-*)' + + // allow zero or more arguments + } else if (nargs === ZERO_OR_MORE) { + nargs_pattern = '(-*[A-]*)' + + // allow one or more arguments + } else if (nargs === ONE_OR_MORE) { + nargs_pattern = '(-*A[A-]*)' + + // allow any number of options or arguments + } else if (nargs === REMAINDER) { + nargs_pattern = '([-AO]*)' + + // allow one argument followed by any number of options or arguments + } else if (nargs === PARSER) { + nargs_pattern = '(-*A[-AO]*)' + + // suppress action, like nargs=0 + } else if (nargs === SUPPRESS) { + nargs_pattern = '(-*-*)' + + // all others should be integers + } else { + nargs_pattern = sub('(-*%s-*)', 'A'.repeat(nargs).split('').join('-*')) + } + + // if this is an optional action, -- is not allowed + if (action.option_strings.length) { + nargs_pattern = nargs_pattern.replace(/-\*/g, '') + nargs_pattern = nargs_pattern.replace(/-/g, '') + } + + // return the pattern + return nargs_pattern + } + + // ======================== + // Alt command line argument parsing, allowing free intermix + // ======================== + + parse_intermixed_args(args = undefined, namespace = undefined) { + let argv + [ args, argv ] = this.parse_known_intermixed_args(args, namespace) + if (argv.length) { + let msg = 'unrecognized arguments: %s' + this.error(sub(msg, argv.join(' '))) + } + return args + } + + parse_known_intermixed_args(args = undefined, namespace = undefined) { + // returns a namespace and list of extras + // + // positional can be freely intermixed with optionals. optionals are + // first parsed with all positional arguments deactivated. The 'extras' + // are then parsed. If the parser definition is incompatible with the + // intermixed assumptions (e.g. use of REMAINDER, subparsers) a + // TypeError is raised. + // + // positionals are 'deactivated' by setting nargs and default to + // SUPPRESS. This blocks the addition of that positional to the + // namespace + + let extras + let positionals = this._get_positional_actions() + let a = positionals.filter(action => [ PARSER, REMAINDER ].includes(action.nargs)) + if (a.length) { + throw new TypeError(sub('parse_intermixed_args: positional arg' + + ' with nargs=%s', a[0].nargs)) + } + + for (let group of this._mutually_exclusive_groups) { + for (let action of group._group_actions) { + if (positionals.includes(action)) { + throw new TypeError('parse_intermixed_args: positional in' + + ' mutuallyExclusiveGroup') + } + } + } + + let save_usage + try { + save_usage = this.usage + let remaining_args + try { + if (this.usage === undefined) { + // capture the full usage for use in error messages + this.usage = this.format_usage().slice(7) + } + for (let action of positionals) { + // deactivate positionals + action.save_nargs = action.nargs + // action.nargs = 0 + action.nargs = SUPPRESS + action.save_default = action.default + action.default = SUPPRESS + } + [ namespace, remaining_args ] = this.parse_known_args(args, + namespace) + for (let action of positionals) { + // remove the empty positional values from namespace + let attr = getattr(namespace, action.dest) + if (Array.isArray(attr) && attr.length === 0) { + // eslint-disable-next-line no-console + console.warn(sub('Do not expect %s in %s', action.dest, namespace)) + delattr(namespace, action.dest) + } + } + } finally { + // restore nargs and usage before exiting + for (let action of positionals) { + action.nargs = action.save_nargs + action.default = action.save_default + } + } + let optionals = this._get_optional_actions() + try { + // parse positionals. optionals aren't normally required, but + // they could be, so make sure they aren't. + for (let action of optionals) { + action.save_required = action.required + action.required = false + } + for (let group of this._mutually_exclusive_groups) { + group.save_required = group.required + group.required = false + } + [ namespace, extras ] = this.parse_known_args(remaining_args, + namespace) + } finally { + // restore parser values before exiting + for (let action of optionals) { + action.required = action.save_required + } + for (let group of this._mutually_exclusive_groups) { + group.required = group.save_required + } + } + } finally { + this.usage = save_usage + } + return [ namespace, extras ] + } + + // ======================== + // Value conversion methods + // ======================== + _get_values(action, arg_strings) { + // for everything but PARSER, REMAINDER args, strip out first '--' + if (![PARSER, REMAINDER].includes(action.nargs)) { + try { + _array_remove(arg_strings, '--') + } catch (err) {} + } + + let value + // optional argument produces a default when not present + if (!arg_strings.length && action.nargs === OPTIONAL) { + if (action.option_strings.length) { + value = action.const + } else { + value = action.default + } + if (typeof value === 'string') { + value = this._get_value(action, value) + this._check_value(action, value) + } + + // when nargs='*' on a positional, if there were no command-line + // args, use the default if it is anything other than None + } else if (!arg_strings.length && action.nargs === ZERO_OR_MORE && + !action.option_strings.length) { + if (action.default !== undefined) { + value = action.default + } else { + value = arg_strings + } + this._check_value(action, value) + + // single argument or optional argument produces a single value + } else if (arg_strings.length === 1 && [undefined, OPTIONAL].includes(action.nargs)) { + let arg_string = arg_strings[0] + value = this._get_value(action, arg_string) + this._check_value(action, value) + + // REMAINDER arguments convert all values, checking none + } else if (action.nargs === REMAINDER) { + value = arg_strings.map(v => this._get_value(action, v)) + + // PARSER arguments convert all values, but check only the first + } else if (action.nargs === PARSER) { + value = arg_strings.map(v => this._get_value(action, v)) + this._check_value(action, value[0]) + + // SUPPRESS argument does not put anything in the namespace + } else if (action.nargs === SUPPRESS) { + value = SUPPRESS + + // all other types of nargs produce a list + } else { + value = arg_strings.map(v => this._get_value(action, v)) + for (let v of value) { + this._check_value(action, v) + } + } + + // return the converted value + return value + } + + _get_value(action, arg_string) { + let type_func = this._registry_get('type', action.type, action.type) + if (typeof type_func !== 'function') { + let msg = '%r is not callable' + throw new ArgumentError(action, sub(msg, type_func)) + } + + // convert the value to the appropriate type + let result + try { + try { + result = type_func(arg_string) + } catch (err) { + // Dear TC39, why would you ever consider making es6 classes not callable? + // We had one universal interface, [[Call]], which worked for anything + // (with familiar this-instanceof guard for classes). Now we have two. + if (err instanceof TypeError && + /Class constructor .* cannot be invoked without 'new'/.test(err.message)) { + // eslint-disable-next-line new-cap + result = new type_func(arg_string) + } else { + throw err + } + } + + } catch (err) { + // ArgumentTypeErrors indicate errors + if (err instanceof ArgumentTypeError) { + //let name = getattr(action.type, 'name', repr(action.type)) + let msg = err.message + throw new ArgumentError(action, msg) + + // TypeErrors or ValueErrors also indicate errors + } else if (err instanceof TypeError) { + let name = getattr(action.type, 'name', repr(action.type)) + let args = {type: name, value: arg_string} + let msg = 'invalid %(type)s value: %(value)r' + throw new ArgumentError(action, sub(msg, args)) + } else { + throw err + } + } + + // return the converted value + return result + } + + _check_value(action, value) { + // converted value must be one of the choices (if specified) + if (action.choices !== undefined && !_choices_to_array(action.choices).includes(value)) { + let args = {value, + choices: _choices_to_array(action.choices).map(repr).join(', ')} + let msg = 'invalid choice: %(value)r (choose from %(choices)s)' + throw new ArgumentError(action, sub(msg, args)) + } + } + + // ======================= + // Help-formatting methods + // ======================= + format_usage() { + let formatter = this._get_formatter() + formatter.add_usage(this.usage, this._actions, + this._mutually_exclusive_groups) + return formatter.format_help() + } + + format_help() { + let formatter = this._get_formatter() + + // usage + formatter.add_usage(this.usage, this._actions, + this._mutually_exclusive_groups) + + // description + formatter.add_text(this.description) + + // positionals, optionals and user-defined groups + for (let action_group of this._action_groups) { + formatter.start_section(action_group.title) + formatter.add_text(action_group.description) + formatter.add_arguments(action_group._group_actions) + formatter.end_section() + } + + // epilog + formatter.add_text(this.epilog) + + // determine help from format above + return formatter.format_help() + } + + _get_formatter() { + // eslint-disable-next-line new-cap + return new this.formatter_class({ prog: this.prog }) + } + + // ===================== + // Help-printing methods + // ===================== + print_usage(file = undefined) { + if (file === undefined) file = process.stdout + this._print_message(this.format_usage(), file) + } + + print_help(file = undefined) { + if (file === undefined) file = process.stdout + this._print_message(this.format_help(), file) + } + + _print_message(message, file = undefined) { + if (message) { + if (file === undefined) file = process.stderr + file.write(message) + } + } + + // =============== + // Exiting methods + // =============== + exit(status = 0, message = undefined) { + if (message) { + this._print_message(message, process.stderr) + } + process.exit(status) + } + + error(message) { + /* + * error(message: string) + * + * Prints a usage message incorporating the message to stderr and + * exits. + * + * If you override this in a subclass, it should not return -- it + * should either exit or raise an exception. + */ + + // LEGACY (v1 compatibility), debug mode + if (this.debug === true) throw new Error(message) + // end + this.print_usage(process.stderr) + let args = {prog: this.prog, message: message} + this.exit(2, sub('%(prog)s: error: %(message)s\n', args)) + } +})) + + +module.exports = { + ArgumentParser, + ArgumentError, + ArgumentTypeError, + BooleanOptionalAction, + FileType, + HelpFormatter, + ArgumentDefaultsHelpFormatter, + RawDescriptionHelpFormatter, + RawTextHelpFormatter, + MetavarTypeHelpFormatter, + Namespace, + Action, + ONE_OR_MORE, + OPTIONAL, + PARSER, + REMAINDER, + SUPPRESS, + ZERO_OR_MORE +} + +// LEGACY (v1 compatibility), Const alias +Object.defineProperty(module.exports, 'Const', { + get() { + let result = {} + Object.entries({ ONE_OR_MORE, OPTIONAL, PARSER, REMAINDER, SUPPRESS, ZERO_OR_MORE }).forEach(([ n, v ]) => { + Object.defineProperty(result, n, { + get() { + deprecate(n, sub('use argparse.%s instead of argparse.Const.%s', n, n)) + return v + } + }) + }) + Object.entries({ _UNRECOGNIZED_ARGS_ATTR }).forEach(([ n, v ]) => { + Object.defineProperty(result, n, { + get() { + deprecate(n, sub('argparse.Const.%s is an internal symbol and will no longer be available', n)) + return v + } + }) + }) + return result + }, + enumerable: false +}) +// end diff --git a/node_modules/argparse/lib/sub.js b/node_modules/argparse/lib/sub.js new file mode 100644 index 0000000000000000000000000000000000000000..e3eb3215fc171cec44a2a1e290cc7deb19bcca74 --- /dev/null +++ b/node_modules/argparse/lib/sub.js @@ -0,0 +1,67 @@ +// Limited implementation of python % string operator, supports only %s and %r for now +// (other formats are not used here, but may appear in custom templates) + +'use strict' + +const { inspect } = require('util') + + +module.exports = function sub(pattern, ...values) { + let regex = /%(?:(%)|(-)?(\*)?(?:\((\w+)\))?([A-Za-z]))/g + + let result = pattern.replace(regex, function (_, is_literal, is_left_align, is_padded, name, format) { + if (is_literal) return '%' + + let padded_count = 0 + if (is_padded) { + if (values.length === 0) throw new TypeError('not enough arguments for format string') + padded_count = values.shift() + if (!Number.isInteger(padded_count)) throw new TypeError('* wants int') + } + + let str + if (name !== undefined) { + let dict = values[0] + if (typeof dict !== 'object' || dict === null) throw new TypeError('format requires a mapping') + if (!(name in dict)) throw new TypeError(`no such key: '${name}'`) + str = dict[name] + } else { + if (values.length === 0) throw new TypeError('not enough arguments for format string') + str = values.shift() + } + + switch (format) { + case 's': + str = String(str) + break + case 'r': + str = inspect(str) + break + case 'd': + case 'i': + if (typeof str !== 'number') { + throw new TypeError(`%${format} format: a number is required, not ${typeof str}`) + } + str = String(str.toFixed(0)) + break + default: + throw new TypeError(`unsupported format character '${format}'`) + } + + if (padded_count > 0) { + return is_left_align ? str.padEnd(padded_count) : str.padStart(padded_count) + } else { + return str + } + }) + + if (values.length) { + if (values.length === 1 && typeof values[0] === 'object' && values[0] !== null) { + // mapping + } else { + throw new TypeError('not all arguments converted during string formatting') + } + } + + return result +} diff --git a/node_modules/argparse/lib/textwrap.js b/node_modules/argparse/lib/textwrap.js new file mode 100644 index 0000000000000000000000000000000000000000..23d51cdb95ccc8591fb6ade3f7e07943071559fe --- /dev/null +++ b/node_modules/argparse/lib/textwrap.js @@ -0,0 +1,440 @@ +// Partial port of python's argparse module, version 3.9.0 (only wrap and fill functions): +// https://github.com/python/cpython/blob/v3.9.0b4/Lib/textwrap.py + +'use strict' + +/* + * Text wrapping and filling. + */ + +// Copyright (C) 1999-2001 Gregory P. Ward. +// Copyright (C) 2002, 2003 Python Software Foundation. +// Copyright (C) 2020 argparse.js authors +// Originally written by Greg Ward + +// Hardcode the recognized whitespace characters to the US-ASCII +// whitespace characters. The main reason for doing this is that +// some Unicode spaces (like \u00a0) are non-breaking whitespaces. +// +// This less funky little regex just split on recognized spaces. E.g. +// "Hello there -- you goof-ball, use the -b option!" +// splits into +// Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/ +const wordsep_simple_re = /([\t\n\x0b\x0c\r ]+)/ + +class TextWrapper { + /* + * Object for wrapping/filling text. The public interface consists of + * the wrap() and fill() methods; the other methods are just there for + * subclasses to override in order to tweak the default behaviour. + * If you want to completely replace the main wrapping algorithm, + * you'll probably have to override _wrap_chunks(). + * + * Several instance attributes control various aspects of wrapping: + * width (default: 70) + * the maximum width of wrapped lines (unless break_long_words + * is false) + * initial_indent (default: "") + * string that will be prepended to the first line of wrapped + * output. Counts towards the line's width. + * subsequent_indent (default: "") + * string that will be prepended to all lines save the first + * of wrapped output; also counts towards each line's width. + * expand_tabs (default: true) + * Expand tabs in input text to spaces before further processing. + * Each tab will become 0 .. 'tabsize' spaces, depending on its position + * in its line. If false, each tab is treated as a single character. + * tabsize (default: 8) + * Expand tabs in input text to 0 .. 'tabsize' spaces, unless + * 'expand_tabs' is false. + * replace_whitespace (default: true) + * Replace all whitespace characters in the input text by spaces + * after tab expansion. Note that if expand_tabs is false and + * replace_whitespace is true, every tab will be converted to a + * single space! + * fix_sentence_endings (default: false) + * Ensure that sentence-ending punctuation is always followed + * by two spaces. Off by default because the algorithm is + * (unavoidably) imperfect. + * break_long_words (default: true) + * Break words longer than 'width'. If false, those words will not + * be broken, and some lines might be longer than 'width'. + * break_on_hyphens (default: true) + * Allow breaking hyphenated words. If true, wrapping will occur + * preferably on whitespaces and right after hyphens part of + * compound words. + * drop_whitespace (default: true) + * Drop leading and trailing whitespace from lines. + * max_lines (default: None) + * Truncate wrapped lines. + * placeholder (default: ' [...]') + * Append to the last line of truncated text. + */ + + constructor(options = {}) { + let { + width = 70, + initial_indent = '', + subsequent_indent = '', + expand_tabs = true, + replace_whitespace = true, + fix_sentence_endings = false, + break_long_words = true, + drop_whitespace = true, + break_on_hyphens = true, + tabsize = 8, + max_lines = undefined, + placeholder=' [...]' + } = options + + this.width = width + this.initial_indent = initial_indent + this.subsequent_indent = subsequent_indent + this.expand_tabs = expand_tabs + this.replace_whitespace = replace_whitespace + this.fix_sentence_endings = fix_sentence_endings + this.break_long_words = break_long_words + this.drop_whitespace = drop_whitespace + this.break_on_hyphens = break_on_hyphens + this.tabsize = tabsize + this.max_lines = max_lines + this.placeholder = placeholder + } + + + // -- Private methods ----------------------------------------------- + // (possibly useful for subclasses to override) + + _munge_whitespace(text) { + /* + * _munge_whitespace(text : string) -> string + * + * Munge whitespace in text: expand tabs and convert all other + * whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz" + * becomes " foo bar baz". + */ + if (this.expand_tabs) { + text = text.replace(/\t/g, ' '.repeat(this.tabsize)) // not strictly correct in js + } + if (this.replace_whitespace) { + text = text.replace(/[\t\n\x0b\x0c\r]/g, ' ') + } + return text + } + + _split(text) { + /* + * _split(text : string) -> [string] + * + * Split the text to wrap into indivisible chunks. Chunks are + * not quite the same as words; see _wrap_chunks() for full + * details. As an example, the text + * Look, goof-ball -- use the -b option! + * breaks into the following chunks: + * 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', + * 'use', ' ', 'the', ' ', '-b', ' ', 'option!' + * if break_on_hyphens is True, or in: + * 'Look,', ' ', 'goof-ball', ' ', '--', ' ', + * 'use', ' ', 'the', ' ', '-b', ' ', option!' + * otherwise. + */ + let chunks = text.split(wordsep_simple_re) + chunks = chunks.filter(Boolean) + return chunks + } + + _handle_long_word(reversed_chunks, cur_line, cur_len, width) { + /* + * _handle_long_word(chunks : [string], + * cur_line : [string], + * cur_len : int, width : int) + * + * Handle a chunk of text (most likely a word, not whitespace) that + * is too long to fit in any line. + */ + // Figure out when indent is larger than the specified width, and make + // sure at least one character is stripped off on every pass + let space_left + if (width < 1) { + space_left = 1 + } else { + space_left = width - cur_len + } + + // If we're allowed to break long words, then do so: put as much + // of the next chunk onto the current line as will fit. + if (this.break_long_words) { + cur_line.push(reversed_chunks[reversed_chunks.length - 1].slice(0, space_left)) + reversed_chunks[reversed_chunks.length - 1] = reversed_chunks[reversed_chunks.length - 1].slice(space_left) + + // Otherwise, we have to preserve the long word intact. Only add + // it to the current line if there's nothing already there -- + // that minimizes how much we violate the width constraint. + } else if (!cur_line) { + cur_line.push(...reversed_chunks.pop()) + } + + // If we're not allowed to break long words, and there's already + // text on the current line, do nothing. Next time through the + // main loop of _wrap_chunks(), we'll wind up here again, but + // cur_len will be zero, so the next line will be entirely + // devoted to the long word that we can't handle right now. + } + + _wrap_chunks(chunks) { + /* + * _wrap_chunks(chunks : [string]) -> [string] + * + * Wrap a sequence of text chunks and return a list of lines of + * length 'self.width' or less. (If 'break_long_words' is false, + * some lines may be longer than this.) Chunks correspond roughly + * to words and the whitespace between them: each chunk is + * indivisible (modulo 'break_long_words'), but a line break can + * come between any two chunks. Chunks should not have internal + * whitespace; ie. a chunk is either all whitespace or a "word". + * Whitespace chunks will be removed from the beginning and end of + * lines, but apart from that whitespace is preserved. + */ + let lines = [] + let indent + if (this.width <= 0) { + throw Error(`invalid width ${this.width} (must be > 0)`) + } + if (this.max_lines !== undefined) { + if (this.max_lines > 1) { + indent = this.subsequent_indent + } else { + indent = this.initial_indent + } + if (indent.length + this.placeholder.trimStart().length > this.width) { + throw Error('placeholder too large for max width') + } + } + + // Arrange in reverse order so items can be efficiently popped + // from a stack of chucks. + chunks = chunks.reverse() + + while (chunks.length > 0) { + + // Start the list of chunks that will make up the current line. + // cur_len is just the length of all the chunks in cur_line. + let cur_line = [] + let cur_len = 0 + + // Figure out which static string will prefix this line. + let indent + if (lines) { + indent = this.subsequent_indent + } else { + indent = this.initial_indent + } + + // Maximum width for this line. + let width = this.width - indent.length + + // First chunk on line is whitespace -- drop it, unless this + // is the very beginning of the text (ie. no lines started yet). + if (this.drop_whitespace && chunks[chunks.length - 1].trim() === '' && lines.length > 0) { + chunks.pop() + } + + while (chunks.length > 0) { + let l = chunks[chunks.length - 1].length + + // Can at least squeeze this chunk onto the current line. + if (cur_len + l <= width) { + cur_line.push(chunks.pop()) + cur_len += l + + // Nope, this line is full. + } else { + break + } + } + + // The current line is full, and the next chunk is too big to + // fit on *any* line (not just this one). + if (chunks.length && chunks[chunks.length - 1].length > width) { + this._handle_long_word(chunks, cur_line, cur_len, width) + cur_len = cur_line.map(l => l.length).reduce((a, b) => a + b, 0) + } + + // If the last chunk on this line is all whitespace, drop it. + if (this.drop_whitespace && cur_line.length > 0 && cur_line[cur_line.length - 1].trim() === '') { + cur_len -= cur_line[cur_line.length - 1].length + cur_line.pop() + } + + if (cur_line) { + if (this.max_lines === undefined || + lines.length + 1 < this.max_lines || + (chunks.length === 0 || + this.drop_whitespace && + chunks.length === 1 && + !chunks[0].trim()) && cur_len <= width) { + // Convert current line back to a string and store it in + // list of all lines (return value). + lines.push(indent + cur_line.join('')) + } else { + let had_break = false + while (cur_line) { + if (cur_line[cur_line.length - 1].trim() && + cur_len + this.placeholder.length <= width) { + cur_line.push(this.placeholder) + lines.push(indent + cur_line.join('')) + had_break = true + break + } + cur_len -= cur_line[-1].length + cur_line.pop() + } + if (!had_break) { + if (lines) { + let prev_line = lines[lines.length - 1].trimEnd() + if (prev_line.length + this.placeholder.length <= + this.width) { + lines[lines.length - 1] = prev_line + this.placeholder + break + } + } + lines.push(indent + this.placeholder.lstrip()) + } + break + } + } + } + + return lines + } + + _split_chunks(text) { + text = this._munge_whitespace(text) + return this._split(text) + } + + // -- Public interface ---------------------------------------------- + + wrap(text) { + /* + * wrap(text : string) -> [string] + * + * Reformat the single paragraph in 'text' so it fits in lines of + * no more than 'self.width' columns, and return a list of wrapped + * lines. Tabs in 'text' are expanded with string.expandtabs(), + * and all other whitespace characters (including newline) are + * converted to space. + */ + let chunks = this._split_chunks(text) + // not implemented in js + //if (this.fix_sentence_endings) { + // this._fix_sentence_endings(chunks) + //} + return this._wrap_chunks(chunks) + } + + fill(text) { + /* + * fill(text : string) -> string + * + * Reformat the single paragraph in 'text' to fit in lines of no + * more than 'self.width' columns, and return a new string + * containing the entire wrapped paragraph. + */ + return this.wrap(text).join('\n') + } +} + + +// -- Convenience interface --------------------------------------------- + +function wrap(text, options = {}) { + /* + * Wrap a single paragraph of text, returning a list of wrapped lines. + * + * Reformat the single paragraph in 'text' so it fits in lines of no + * more than 'width' columns, and return a list of wrapped lines. By + * default, tabs in 'text' are expanded with string.expandtabs(), and + * all other whitespace characters (including newline) are converted to + * space. See TextWrapper class for available keyword args to customize + * wrapping behaviour. + */ + let { width = 70, ...kwargs } = options + let w = new TextWrapper(Object.assign({ width }, kwargs)) + return w.wrap(text) +} + +function fill(text, options = {}) { + /* + * Fill a single paragraph of text, returning a new string. + * + * Reformat the single paragraph in 'text' to fit in lines of no more + * than 'width' columns, and return a new string containing the entire + * wrapped paragraph. As with wrap(), tabs are expanded and other + * whitespace characters converted to space. See TextWrapper class for + * available keyword args to customize wrapping behaviour. + */ + let { width = 70, ...kwargs } = options + let w = new TextWrapper(Object.assign({ width }, kwargs)) + return w.fill(text) +} + +// -- Loosely related functionality ------------------------------------- + +let _whitespace_only_re = /^[ \t]+$/mg +let _leading_whitespace_re = /(^[ \t]*)(?:[^ \t\n])/mg + +function dedent(text) { + /* + * Remove any common leading whitespace from every line in `text`. + * + * This can be used to make triple-quoted strings line up with the left + * edge of the display, while still presenting them in the source code + * in indented form. + * + * Note that tabs and spaces are both treated as whitespace, but they + * are not equal: the lines " hello" and "\\thello" are + * considered to have no common leading whitespace. + * + * Entirely blank lines are normalized to a newline character. + */ + // Look for the longest leading string of spaces and tabs common to + // all lines. + let margin = undefined + text = text.replace(_whitespace_only_re, '') + let indents = text.match(_leading_whitespace_re) || [] + for (let indent of indents) { + indent = indent.slice(0, -1) + + if (margin === undefined) { + margin = indent + + // Current line more deeply indented than previous winner: + // no change (previous winner is still on top). + } else if (indent.startsWith(margin)) { + // pass + + // Current line consistent with and no deeper than previous winner: + // it's the new winner. + } else if (margin.startsWith(indent)) { + margin = indent + + // Find the largest common whitespace between current line and previous + // winner. + } else { + for (let i = 0; i < margin.length && i < indent.length; i++) { + if (margin[i] !== indent[i]) { + margin = margin.slice(0, i) + break + } + } + } + } + + if (margin) { + text = text.replace(new RegExp('^' + margin, 'mg'), '') + } + return text +} + +module.exports = { wrap, fill, dedent } diff --git a/node_modules/argparse/package.json b/node_modules/argparse/package.json new file mode 100644 index 0000000000000000000000000000000000000000..647d2aff18d2ac0bc73c4618e09a2a220bf7b36a --- /dev/null +++ b/node_modules/argparse/package.json @@ -0,0 +1,31 @@ +{ + "name": "argparse", + "description": "CLI arguments parser. Native port of python's argparse.", + "version": "2.0.1", + "keywords": [ + "cli", + "parser", + "argparse", + "option", + "args" + ], + "main": "argparse.js", + "files": [ + "argparse.js", + "lib/" + ], + "license": "Python-2.0", + "repository": "nodeca/argparse", + "scripts": { + "lint": "eslint .", + "test": "npm run lint && nyc mocha", + "coverage": "npm run test && nyc report --reporter html" + }, + "devDependencies": { + "@babel/eslint-parser": "^7.11.0", + "@babel/plugin-syntax-class-properties": "^7.10.4", + "eslint": "^7.5.0", + "mocha": "^8.0.1", + "nyc": "^15.1.0" + } +} diff --git a/node_modules/aria-query/CHANGELOG.md b/node_modules/aria-query/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..3d70e2899330d62e075bd1ad35196a3c9a5ab4b1 --- /dev/null +++ b/node_modules/aria-query/CHANGELOG.md @@ -0,0 +1,258 @@ +# aria-query Change Log + +## 1.0.0 + +- Updated values of aria-haspopup to include ARIA 1.1 role values +- Added the CHANGELOG file + +## 2.0.0 + +- Remove package-lock file. +- Add Watchman config file. + +## 2.0.1 + +- Added aria-errormessage to the ARIA Props Map. + +## 3.0.0 + +- Bumping to a major version because of a previous breaking change. + +## 4.0.0 + +- 912e515 (origin/fix-travis, fix-travis) Move allowed failures to excludes in Travis. The current failures are simply version incompatibilities. +- 17f4203 (origin/fixe-all-roles-html-mappings, fixe-all-roles-html-mappings) Fix all inherent ARIA role to HTML mappings +- 4ce2a9e (origin/fix-textbox, fix-textbox) Fix HTML relatedConcepts for textbox and combobox +- 8cbdf1d (origin/fix-select-mapping, fix-select-mapping) Remove baseConcepts as a prop. +- c3c510d Fix mapping for the HTML select element +- 52f2535 (origin/deprecate-requireContextRole, deprecate-requireContextRole) Deprecate the mispelled requireContextRole. Replace with requiredContextRole. +- fff3783 (origin/kurosawa-takeshi-add-double-check-tests, kurosawa-takeshi-add-double-check-tests) Update package lock file +- b90a99b (origin/kurosawa-takeshi-update-dpub-aria, kurosawa-takeshi-update-dpub-aria) Update breakUpAriaJSON script to include MapOfRoleDefinitions type on roll-up role classes-takeshi-update-dpub-aria +- 59c3199 (origin/eps1lon-fix/ie11, eps1lon-fix/ie11) Undo the eslintrc changes +- 3152480 (origin/dependabot/npm_and_yarn/eslint-6.6.0, dependabot/npm_and_yarn/eslint-6.6.0) Fix duplicate peer dependencies +- 8a661f2 Updating allowed failures for odd versions of node +- 0c85fd6 Update Travis and eslint peer dependencies +- 99df7da Bump eslint from 3.19.0 to 6.6.0 + +## 4.0.1 + +- Fix the incorrect ARIA designation of the region role to an HTML designation + +## 4.0.2 + +- a3e2f1e Added the Copyright year (2020) for A11yance +- 3173a07 Remove Peer Dependency to ESLint + +## 4.2.0 + +Upgrade support of ARIA from 1.1 to 1.2 + +- f1b8f11 Add aria-level as a required prop for the heading role +- 5beb07b Fix babelrc and update package lock +- 32256c7 Update dependencies and babelrc +- 132ebca test: Verify that role.json is synced (#52) +- d2c7b1b test: Narrow test matrix +- f4d115c fix: manual add aria-valuetext to range +- fb8fcf8 fix: Update with latest parser script +- 7dae700 fix: Superclass of generic is structure +- 5ea8353 Adding a license line +- 48cc635 fix: input type is text by default +- b50587e Revert relatedConcepts changes +- 1aa562f fix flowtype of prohibitedProps +- 8b81b14 Run node scripts/breakUpAriaJSON +- f65c156 chore: sort roles.json keys alphanumerically +- 3c2f213 chore: format role.json +- 38694f3 fix: input type is text by default (#42) + +## 4.2.1 + +- bdd6082 Change master branch main in Travis +- 0b2d4ed Handle header element as banner role (#47) + +## 4.2.2 + +- 7819fe4 Fix the allowed props of the heading role (jsx-eslint/eslint-plugin-jsx-a11y#704) + +## 5.0.0 + +This major release removes the runtime Babel dependencies that were necessary because of Map and Set usage. Map and Set usages are now replaced with object and array literals. + +These are the changes in usage you might need to account for: + +- The module exports are no longer Maps, so you cannot spread them directly into an array to access their items. Use the `entries` method to get access to the items. +- Some values used to be Sets; these are now Arrays. +- The `keys` and `values` methods now return arrays, not iterators. +- There is no `forEach` method. One could be added in the future, but at present, it does not exist on the exports. + +### Commits of note + +- 92cecd2 chore(deps-dev): bump flow-bin from 0.160.2 to 0.161.0 (#261) +- b10e864 Remove the usage of Maps and Sets, along with the Babel Runtime - dependency (#250) +- 1953885 chore(deps-dev): bump jest from 27.2.1 to 27.2.2 (#252) +- 1dfb98f chore(deps): bump actions/setup-node from 2.4.0 to 2.4.1 (#254) +- f4fd458 chore(deps-dev): bump expect from 27.2.1 to 27.2.2 (#253) +- f85ecec chore(deps-dev): bump babel-jest from 27.2.1 to 27.2.2 (#251) +- b03b46a chore(deps-dev): bump flow-bin from 0.154.0 to 0.160.2 (#249) +- 4f9c5f0 Update Flow bin version (#248) +- cd57f86 Add aria-valuenow prop to the separator role +- 144aca0 Use block for instead of iterable for +- ef49ee8 Remove spread operator from roleElementMap +- bac9501 Update the test for roleElementMap to include specific items +- 8094edf Remove spread operator from elementRoleMap +- 980ceea Add a test for the specific items in elementRoleMap +- 5b477bc chore(deps-dev): bump eslint-plugin-flowtype from 5.10.0 to 6.1.0 (#246) +- d28d7c1 chore(deps-dev): bump commander from 8.0.0 to 8.2.0 (#245) +- 57b38d1 chore(deps-dev): bump @babel/plugin-transform-runtime (#237) +- 1519ec1 chore(deps): bump @babel/runtime-corejs3 from 7.14.7 to 7.15.4 (#241) +- 691e51b chore(deps-dev): bump eslint-plugin-import from 2.23.4 to 2.24.2 (#243) +- 9e1711c chore(deps-dev): bump eslint from 7.28.0 to 7.32.0 (#244) +- 589d97a chore(deps-dev): bump @babel/preset-env from 7.14.7 to 7.15.6 (#239) +- 1c48278 chore(deps-dev): bump expect from 27.0.2 to 27.2.1 (#242) +- 71c2f61 chore(deps): bump @babel/runtime from 7.14.0 to 7.15.4 (#240) +- 73c2339 chore(deps-dev): bump eslint-plugin-flowtype from 5.7.2 to 5.10.0 (#238) +- 85d983c chore(deps-dev): bump babel-jest from 27.0.2 to 27.2.1 (#232) +- dc91b47 chore(deps): bump tmpl from 1.0.4 to 1.0.5 (#235) +- 53fa58c chore(deps-dev): bump jest from 27.0.4 to 27.2.1 (#233) +- 8affde6 chore(deps-dev): bump @babel/cli from 7.14.3 to 7.15.7 (#231) +- 5f8369c chore(deps): bump path-parse from 1.0.6 to 1.0.7 (#220) +- 7051091 chore(deps): bump actions/setup-node from 2.3.0 to 2.4.0 (#219) +- 4a1ac48 chore(deps): bump coverallsapp/github-action from 1.1.2 to 1.1.3 (#213) +- 5ebf3e7 chore(deps-dev): bump @babel/core from 7.14.3 to 7.15.5 (#225) +- e2be68b Account for nosync file paths in the ignore files (#236) +- 5adca2f chore(deps): bump actions/setup-node from 2.2.0 to 2.3.0 (#214) +- 2bf4afa Fixing the package-lock.json file +- a325a23 chore(deps-dev): bump @babel/core from 7.12.10 to 7.14.2 +- b6c7e7d chore(deps-dev): bump jest from 27.0.4 to 27.0.6 (#208) +- fe8255b chore(deps-dev): bump eslint-plugin-flowtype from 5.7.2 to 5.8.0 (#201) +- e005fa9 chore(deps-dev): bump @babel/core from 7.14.3 to 7.14.6 (#202) +- b7800bd chore(deps-dev): bump babel-jest from 27.0.2 to 27.0.6 (#207) +- 388fcf8 chore(deps-dev): bump eslint from 7.28.0 to 7.30.0 (#206) +- 9dc75ec chore(deps-dev): bump commander from 7.2.0 to 8.0.0 (#205) +- f808394 chore(deps-dev): bump expect from 27.0.2 to 27.0.6 (#204) +- fdbc963 chore(deps-dev): bump @babel/cli from 7.14.3 to 7.14.5 (#203) +- 823c292 Updating package-lock which only added an fsevents reference +- 61fe8b7 chore(deps-dev): bump @babel/plugin-transform-runtime (#200) +- 2ef3e93 chore(deps-dev): bump @babel/preset-flow from 7.13.13 to 7.14.5 (#188) +- d68a04a chore(deps): bump actions/setup-node from 2.1.5 to 2.2.0 +- b0f6437 chore(deps-dev): bump @babel/preset-env from 7.12.11 to 7.14.7 +- 18725dd chore(deps): bump @babel/runtime-corejs3 from 7.12.5 to 7.14.7 +- d7b6389 chore(deps-dev): bump eslint from 7.19.0 to 7.28.0 (#183) +- a4aa09b chore(deps-dev): bump expect from 26.6.2 to 27.0.2 (#184) +- b861ba8 chore(deps-dev): bump babel-jest from 26.6.3 to 27.0.2 (#176) +- 2fa3a72 chore(deps-dev): bump eslint-plugin-import from 2.22.1 to 2.23.4 (#177) +- 7e0d575 chore(deps-dev): bump eslint-plugin-flowtype from 5.2.0 to 5.7.2 (#179) +- 48e1737 chore(deps-dev): bump jest from 26.6.3 to 27.0.4 (#182) +- 925ed16 chore(deps-dev): bump commander from 7.0.0 to 7.2.0 (#174) +- c545b74 chore(deps-dev): bump @babel/* to 7.14.3 (#168) +- 4ed066b chore(deps): bump actions/cache from 2.1.5 to 2.1.6 (#172) +- ca72279 chore(deps): bump ws from 7.4.2 to 7.4.6 (#173) +- 638027d chore(deps): bump browserslist from 4.16.0 to 4.16.6 (#171) +- 9392447 test: Ignore build output when linting (#167) +- 38f1759 chore(deps): bump actions/cache from 2 to 2.1.5 (#161) +- 5ec0f9a chore(deps): bump actions/setup-node from 2 to 2.1.5 (#159) +- 687461f chore(deps): bump actions/checkout from 2 to 2.3.4 (#160) +- 80e4bd6 chore(deps): bump hosted-git-info from 2.8.8 to 2.8.9 (#157) +- e4e7114 chore(deps): bump lodash from 4.17.20 to 4.17.21 (#156) +- 87abf49 chore(deps-dev): bump eslint from 7.18.0 to 7.19.0 (#112) +- 24467e7 chore(deps-dev): bump commander from 6.2.1 to 7.0.0 (#108) +- afe23cb chore(deps-dev): bump flow-bin from 0.143.0 to 0.143.1 (#111) +- 2e6a301 chore(deps-dev): bump flow-bin from 0.142.0 to 0.143.0 (#110) +- 947cff3 chore(deps-dev): bump eslint from 7.17.0 to 7.18.0 (#109) +- 3c5399c chore(deps-dev): bump @babel/plugin-transform-runtime (#106) +- 633fc3c chore(deps-dev): bump @babel/cli from 7.10.1 to 7.12.10 (#107) +- ed738a3 chore(deps-dev): bump eslint from 7.16.0 to 7.17.0 (#104) +- 3e45d3c chore(deps-dev): bump commander from 2.20.3 to 6.2.1 (#105) +- f6b049d chore(deps): bump @babel/runtime from 7.10.2 to 7.12.5 (#98) +- 894ee58 chore(deps-dev): bump @babel/preset-flow from 7.10.1 to 7.12.1 (#97) +- a494ed1 chore(deps-dev): bump rimraf from 2.7.1 to 3.0.2 (#99) +- 7d3297d chore(deps-dev): bump flow-bin from 0.141.0 to 0.142.0 (#103) +- 9eed1f5 chore(deps-dev): bump @babel/core from 7.10.2 to 7.12.10 (#100) +- 5f20ae0 chore(deps): bump @babel/runtime-corejs3 from 7.10.2 to 7.12.5 (#101) +- e803d94 chore: Turn on eslint:recommended and address new rules (#96) +- 5a68aa1 fix: Remove bash-like command in flow NPM script (#95) +- a7506ad chore: Expand ESLint glob to all files (#93) +- cf56e0c chore: Cleanup README (#94) +- dd958db chore: Use NPM CI for CI (#90) +- e604a6e chore: Remove coveralls NPM config (#91) +- e4b6d28 Update coveralls, expect and flow-bin (#92) +- 0e7ccdf Bump babel-jest from 24.9.0 to 26.6.3 (#84) +- 76b7a41 chore: Remove Travis-CI config (#89) +- bc1a437 Only diff the src dir in the CI Diff check (#87) +- e466929 Bump lodash from 4.17.15 to 4.17.20 (#86) +- a7429ee Bump eslint from 6.8.0 to 7.16.0 (#85) +- 83ec474 fix: type sig for ARIAPropertyDefinition (#74) +- f3b4e83 chore: Remove npmrc (#78) +- 717d76c chore: Add Depependabot config (#79) +- 50e05b1 Update test.yml (#76) +- b9ee176 Update test.yml (#75) +- a8cd23a Create test.yml +- 25fbc40 fix: Sync with stable editor's draft (#69) +- 7df56ba docs: fix CDN url (#71) +- 74009cf fix: definition/term roles (#70) +- 2a5dafb feat: Sync with stable editor's draft +- 1241efe chore: Seal AriaPropertMap type (#67) +- 0b6fcc4 "that there is no maximum value" > no default value +- e6dd042 Keep required props in sync with props +- 995b6b9 Remove deprecated props +- d99d54e Update ariaPropsMap +- eb123ce Update types +- 1284970 Update roles.json +- 1d9840c docs(readme): Add tracked aria version +- 971679a fix: Normalize required props (#64) + +## 5.1.0 / 5.1.1 + +This minor release introduces iteration support to the primary objects of the module, through the `Symbol.iterator` property. This reintroduces a native-like `Map` iteration support that was lost in the v3 update. A `forEach` method is also introduced in this update. The common interface of all objects exposed by this module is now: + +``` +type TAriaQueryMap = { + entries: () => E, + forEach: ((V, K, E) => void) => void, + get: (key: K) => ?V, + has: (key: K) => boolean, + keys: () => Array, + values: () => Array, + @@iterator?: () => Iterator, +}; +``` + +### Commits of note + + - 6f3f54b Update dependencies to current minor releases (#437) + - 855eedc Introduce iteration support to the Maps in the module (#425) + - 38a2bbc Remove Node 12 as a target for Jest unit testing (#397) + - 8a0f588 Update out of date packages to latest major versions (#396) + - 8522117 Ran npm up --dev --save (#395) + - a21d1ed feat: Add graphics-* roles (#338) + + ## 5.1.2 + + - 8361a27 Plumb the graphics roles through to rolesMap (#444) + + ## 5.1.3 + + No changes, just trying to get the NPM build to reflect the changes in v5.1.2 + + ## 5.2.0 + + [Update] The 5.2.x minor version contains breaking changes and should be skipped. + + Commit f7f6120 contains a substantial audit and update of the project to match the ARIA spec. Testing coverage was substantially improved. It really locks down the project's output. + + - e2e3eff docs: update README to WAI-ARIA 1.2 spec (#499) + - 5ef740f Switch to dequal to remove 45 transitive dependencies (#497) + - 58da9d5 fix: install command for codesandbox ci (#500) + - 1160138 test: Publish canaries via CodeSandbox CI (#486) + - 2d04e29 Add test case to elementRoleMap-test for td element + - f7f6120 Audited and updated roles source of truth to HTML Accessibility API Mapping 1.0 (#447) + +## 5.2.1 + + - c995082 Run npm i to update package-lock.json + +## 5.3.0 + +Reverts some API data shape changes from 5.2.x. Also reverts some changes to the representation of the ARIA spec. + + - fda2c97 fix: amend breaking changes and reinstate constraints (#515) + - f9f9ea6 Add prepublishOnly step to package.json (#506) \ No newline at end of file diff --git a/node_modules/aria-query/LICENSE b/node_modules/aria-query/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3a8ae7c335078c0327bdb23e0d09024e15f1d1f2 --- /dev/null +++ b/node_modules/aria-query/LICENSE @@ -0,0 +1,201 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, +and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by +the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all +other entities that control, are controlled by, or are under common +control with that entity. For the purposes of this definition, +"control" means (i) the power, direct or indirect, to cause the +direction or management of such entity, whether by contract or +otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity +exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, +including but not limited to software source code, documentation +source, and configuration files. + +"Object" form shall mean any form resulting from mechanical +transformation or translation of a Source form, including but +not limited to compiled object code, generated documentation, +and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or +Object form, made available under the License, as indicated by a +copyright notice that is included in or attached to the work +(an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object +form, that is based on (or derived from) the Work and for which the +editorial revisions, annotations, elaborations, or other modifications +represent, as a whole, an original work of authorship. For the purposes +of this License, Derivative Works shall not include works that remain +separable from, or merely link (or bind by name) to the interfaces of, +the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including +the original version of the Work and any modifications or additions +to that Work or Derivative Works thereof, that is intentionally +submitted to Licensor for inclusion in the Work by the copyright owner +or by an individual or Legal Entity authorized to submit on behalf of +the copyright owner. For the purposes of this definition, "submitted" +means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, +and issue tracking systems that are managed by, or on behalf of, the +Licensor for the purpose of discussing and improving the Work, but +excluding communication that is conspicuously marked or otherwise +designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity +on behalf of whom a Contribution has been received by Licensor and +subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the +Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +(except as stated in this section) patent license to make, have made, +use, offer to sell, sell, import, and otherwise transfer the Work, +where such license applies only to those patent claims licensable +by such Contributor that are necessarily infringed by their +Contribution(s) alone or by combination of their Contribution(s) +with the Work to which such Contribution(s) was submitted. If You +institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work +or a Contribution incorporated within the Work constitutes direct +or contributory patent infringement, then any patent licenses +granted to You under this License for that Work shall terminate +as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the +Work or Derivative Works thereof in any medium, with or without +modifications, and in Source or Object form, provided that You +meet the following conditions: + +(a) You must give any other recipients of the Work or +Derivative Works a copy of this License; and + +(b) You must cause any modified files to carry prominent notices +stating that You changed the files; and + +(c) You must retain, in the Source form of any Derivative Works +that You distribute, all copyright, patent, trademark, and +attribution notices from the Source form of the Work, +excluding those notices that do not pertain to any part of +the Derivative Works; and + +(d) If the Work includes a "NOTICE" text file as part of its +distribution, then any Derivative Works that You distribute must +include a readable copy of the attribution notices contained +within such NOTICE file, excluding those notices that do not +pertain to any part of the Derivative Works, in at least one +of the following places: within a NOTICE text file distributed +as part of the Derivative Works; within the Source form or +documentation, if provided along with the Derivative Works; or, +within a display generated by the Derivative Works, if and +wherever such third-party notices normally appear. The contents +of the NOTICE file are for informational purposes only and +do not modify the License. You may add Your own attribution +notices within Derivative Works that You distribute, alongside +or as an addendum to the NOTICE text from the Work, provided +that such additional attribution notices cannot be construed +as modifying the License. + +You may add Your own copyright statement to Your modifications and +may provide additional or different license terms and conditions +for use, reproduction, or distribution of Your modifications, or +for any such Derivative Works as a whole, provided Your use, +reproduction, and distribution of the Work otherwise complies with +the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, +any Contribution intentionally submitted for inclusion in the Work +by You to the Licensor shall be under the terms and conditions of +this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify +the terms of any separate license agreement you may have executed +with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade +names, trademarks, service marks, or product names of the Licensor, +except as required for reasonable and customary use in describing the +origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or +agreed to in writing, Licensor provides the Work (and each +Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +implied, including, without limitation, any warranties or conditions +of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +PARTICULAR PURPOSE. You are solely responsible for determining the +appropriateness of using or redistributing the Work and assume any +risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, +whether in tort (including negligence), contract, or otherwise, +unless required by applicable law (such as deliberate and grossly +negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, +incidental, or consequential damages of any character arising as a +result of this License or out of the use or inability to use the +Work (including but not limited to damages for loss of goodwill, +work stoppage, computer failure or malfunction, or any and all +other commercial damages or losses), even if such Contributor +has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing +the Work or Derivative Works thereof, You may choose to offer, +and charge a fee for, acceptance of support, warranty, indemnity, +or other liability obligations and/or rights consistent with this +License. However, in accepting such obligations, You may act only +on Your own behalf and on Your sole responsibility, not on behalf +of any other Contributor, and only if You agree to indemnify, +defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason +of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following +boilerplate notice, with the fields enclosed by brackets "{}" +replaced with your own identifying information. (Don't include +the brackets!) The text should be enclosed in the appropriate +comment syntax for the file format. We also recommend that a +file or class name and description of purpose be included on the +same "printed page" as the copyright notice for easier +identification within third-party archives. + +Copyright 2020 A11yance + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/node_modules/aria-query/README.md b/node_modules/aria-query/README.md new file mode 100644 index 0000000000000000000000000000000000000000..53a1b7b89e2443fec01fd00ab1d519c65847d718 --- /dev/null +++ b/node_modules/aria-query/README.md @@ -0,0 +1,195 @@ +# ARIA Query + +![CI](https://github.com/A11yance/aria-query/workflows/CI/badge.svg) + +Programmatic access to the [WAI-ARIA 1.2 Roles Model](https://www.w3.org/TR/wai-aria-1.2/#roles). +This package tracks the W3C Recommendation (last update: 6 June 2023). + +CDN URL: + +## Building the `src/etc` files + +The files under `src/etc` are generated by the `breakUpAriaJSON` script. + +To change them, edit the file `scripts/roles.json` then run: + +```bash +node ./scripts/breakUpAriaJSON.js +git add scripts/roles.json src/etc +``` + +It should work with Node version 6.11.2 or later. + +## Utilities + +### Interface + +These methods are available on each export from the module. The typing here in the documentation is pseudo-typed. Each export will have its own specific types for each method signature. + +```javascript +{| + entries: () => Array<$Item>, + get: (key: $Key) => ?$Value, + has: (key: $Key) => boolean, + keys: () => Array<$Key>, + values: () => Array<$Value>, +|}; +``` + +### Roles + +```javascript +import { roles } from 'aria-query'; +``` + +A map of role names to the role definition. For example: + +```javascript +let alertRole = roles.get('alert'); +/** + * Value of alertRole + * { + * "requiredProps": {}, + * "props": { + * "aria-atomic": "true", + * "aria-busy": null, + * "aria-controls": null, + * "aria-current": null, + * "aria-describedby": null, + * "aria-details": null, + * "aria-disabled": null, + * "aria-dropeffect": null, + * "aria-errormessage": null, + * "aria-expanded": null, + * "aria-flowto": null, + * "aria-grabbed": null, + * "aria-haspopup": null, + * "aria-hidden": null, + * "aria-invalid": null, + * "aria-keyshortcuts": null, + * "aria-label": null, + * "aria-labelledby": null, + * "aria-live": "assertive", + * "aria-owns": null, + * "aria-relevant": null, + * "aria-roledescription": null + * }, + * "abstract": false, + * "childrenPresentational": false, + * "baseConcepts": [], + * "relatedConcepts": [ { + * "module": "XForms", + * "concept": { + * "name": "alert" + * } + * }], + * "superClass": [["roletype", "structure", "section"]] + * } +``` + +### Elements to Roles + +```javascript +import { elementRoles } from 'aria-query'; +``` + +HTML Elements with inherent roles are mapped to those roles. In the case of an element like ``, the element often requires a `type` attribute to map to an ARIA role. + +```javascript +[ + [ '{"name": "article"}', [ 'article' ] ], + [ '{"name": "button"}', [ 'button' ] ], + [ '{"name": "td"}', [ 'cell', 'gridcell' ] ], + [ '{"name": "input", "attributes": [ {"name": "type", "value": "checkbox"}] }', [ 'checkbox' ] ], + [ '{"name": "th"}', [ 'columnheader' ] ], + [ '{"name": "select"}', [ 'combobox', 'listbox' ] ], + [ '{"name": "menuitem"}', [ 'command', 'menuitem' ] ], + [ '{"name": "dd"}', [ 'definition' ] ], + [ '{"name": "figure"}', [ 'figure' ] ], + [ '{"name": "form"}', [ 'form' ] ], + [ '{"name": "table"}', [ 'grid', 'table' ] ], + [ '{"name": "fieldset"}', [ 'group' ] ], + [ '{"name": "h1"}', [ 'heading' ] ], + [ '{"name": "h2"}', [ 'heading' ] ], + [ '{"name": "h3"}', [ 'heading' ] ], + [ '{"name": "h4"}', [ 'heading' ] ], + [ '{"name": "h5"}', [ 'heading' ] ], + [ '{"name": "h6"}', [ 'heading' ] ], + [ '{"name": "img"}', [ 'img' ] ], + [ '{"name": "a"}', [ 'link' ] ], + [ '{"name": "link"}', [ 'link' ] ], + [ '{"name": "ol"}', [ 'list' ] ], + [ '{"name": "ul"}', [ 'list' ] ], + [ '{"name": "li"}', [ 'listitem' ] ], + [ '{"name": "nav"}', [ 'navigation' ] ], + [ '{"name": "option"}', [ 'option' ] ], + [ '{"name": "input", "attributes": [ {"name": "type", "value": "radio"}] }', [ 'radio' ] ], + [ '{"name": "frame"}', [ 'region' ] ], + [ '{"name": "rel"}', [ 'roletype' ] ], + [ '{"name": "tr"}', [ 'row' ] ], + [ '{"name": "tbody"}', [ 'rowgroup' ] ], + [ '{"name": "tfoot"}', [ 'rowgroup' ] ], + [ '{"name": "thead"}', [ 'rowgroup' ] ], + [ '{"name": "th", "attributes": [ {"name": "scope", "value": "row"}] }', [ 'rowheader' ] ], + [ '{"name": "input", "attributes": [ {"name": "type", "value": "search"}] }', [ 'searchbox' ] ], + [ '{"name": "hr"}', [ 'separator' ] ], + [ '{"name": "dt"}', [ 'term' ] ], + [ '{"name": "dfn"}', [ 'term' ] ], + [ '{"name": "textarea"}', [ 'textbox' ] ], + [ '{"name": "input", "attributes": [ {"name": "type", "value": "text"}] }', [ 'textbox' ] ], +] +``` + +The map of elements to roles is keyed by an HTML concept. An HTML concept corresponds to the `baseConcepts` and `relatedConcepts` of an ARIA role. Concepts exist in the context of a `module`: HTML, XForms, Dublin Core, for example. The concept representation is an object literal with a name property (the element name) and an optional attributes array. + +The roles are provided in a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set). + +### Role to element + +```javascript +import { roleElements } from 'aria-query'; +``` + +ARIA roles are mapped to the HTML Elements with the same inherent role. Some roles, such as `columnheader` are only mapped to an HTML element that expresses specific attributes. In the case of ``, the element often requires a `type` attribute to map to an ARIA role. + +```javascript +[ + [ 'article', [ {"name": "article"} ] ], + [ 'button', [ {"name": "button"} ] ], + [ 'cell', [ {"name": "td"} ] ], + [ 'checkbox', [ {"name": "input", "attributes": [ {"name": "type", "value": "checkbox"}] } ] ], + [ 'columnheader', [ {"name": "th"} ] ], + [ 'combobox', [ {"name": "select"} ] ], + [ 'command', [ {"name": "menuitem"} ] ], + [ 'definition', [ {"name": "dd"}', '{"name": "dfn"} ] ], + [ 'figure', [ {"name": "figure"} ] ], + [ 'form', [ {"name": "form"} ] ], + [ 'grid', [ {"name": "table"} ] ], + [ 'gridcell', [ {"name": "td"} ] ], + [ 'group', [ {"name": "fieldset"} ] ], + [ 'heading', [ {"name": "h1"}', '{"name": "h2"}', '{"name": "h3"}', '{"name": "h4"}', '{"name": "h5"}', '{"name": "h6"} ] ], + [ 'img', [ {"name": "img"} ] ], + [ 'link', [ {"name": "a"}', '{"name": "link"} ] ], + [ 'list', [ {"name": "ol"}', '{"name": "ul"} ] ], + [ 'listbox', [ {"name": "select"} ] ], + [ 'listitem', [ {"name": "li"} ] ], + [ 'menuitem', [ {"name": "menuitem"} ] ], + [ 'navigation', [ {"name": "nav"} ] ], + [ 'option', [ {"name": "option"} ] ], + [ 'radio', [ {"name": "input", "attributes": [ {"name": "type", "value": "radio"}] } ] ], + [ 'region', [ {"name": "frame"} ] ], + [ 'roletype', [ {"name": "rel"} ] ], + [ 'row', [ {"name": "tr"} ] ], + [ 'rowgroup', [ {"name": "tbody"}', '{"name": "tfoot"}', '{"name": "thead"} ] ], + [ 'rowheader', [ {"name": "th", "attributes": [ {"name": "scope", "value": "row"}] }, {"name": "th", "attributes": [ {"name": "scope", "value": "rowgroup"}] } ] ], + [ 'searchbox', [ {"name": "input", "attributes": [ {"name": "type", "value": "search"}] } ] ], + [ 'separator', [ {"name": "hr"} ] ], + [ 'table', [ {"name": "table"} ] ], + [ 'term', [ {"name": "dt"} ] ], + [ 'textbox', [ {"name": "textarea"}', '{"name": "input", "attributes": [ {"name": "type", "value": "text"}] } ] ], +] +``` + +## License + +Copyright (c) 2021 A11yance diff --git a/node_modules/aria-query/lib/ariaPropsMap.js b/node_modules/aria-query/lib/ariaPropsMap.js new file mode 100644 index 0000000000000000000000000000000000000000..7ab28134bbcd75a668490cf4143abe2b22c5be5c --- /dev/null +++ b/node_modules/aria-query/lib/ariaPropsMap.js @@ -0,0 +1,178 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _iterationDecorator = _interopRequireDefault(require("./util/iterationDecorator")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } +var properties = [['aria-activedescendant', { + 'type': 'id' +}], ['aria-atomic', { + 'type': 'boolean' +}], ['aria-autocomplete', { + 'type': 'token', + 'values': ['inline', 'list', 'both', 'none'] +}], ['aria-braillelabel', { + 'type': 'string' +}], ['aria-brailleroledescription', { + 'type': 'string' +}], ['aria-busy', { + 'type': 'boolean' +}], ['aria-checked', { + 'type': 'tristate' +}], ['aria-colcount', { + type: 'integer' +}], ['aria-colindex', { + type: 'integer' +}], ['aria-colspan', { + type: 'integer' +}], ['aria-controls', { + 'type': 'idlist' +}], ['aria-current', { + type: 'token', + values: ['page', 'step', 'location', 'date', 'time', true, false] +}], ['aria-describedby', { + 'type': 'idlist' +}], ['aria-description', { + 'type': 'string' +}], ['aria-details', { + 'type': 'id' +}], ['aria-disabled', { + 'type': 'boolean' +}], ['aria-dropeffect', { + 'type': 'tokenlist', + 'values': ['copy', 'execute', 'link', 'move', 'none', 'popup'] +}], ['aria-errormessage', { + 'type': 'id' +}], ['aria-expanded', { + 'type': 'boolean', + 'allowundefined': true +}], ['aria-flowto', { + 'type': 'idlist' +}], ['aria-grabbed', { + 'type': 'boolean', + 'allowundefined': true +}], ['aria-haspopup', { + 'type': 'token', + 'values': [false, true, 'menu', 'listbox', 'tree', 'grid', 'dialog'] +}], ['aria-hidden', { + 'type': 'boolean', + 'allowundefined': true +}], ['aria-invalid', { + 'type': 'token', + 'values': ['grammar', false, 'spelling', true] +}], ['aria-keyshortcuts', { + type: 'string' +}], ['aria-label', { + 'type': 'string' +}], ['aria-labelledby', { + 'type': 'idlist' +}], ['aria-level', { + 'type': 'integer' +}], ['aria-live', { + 'type': 'token', + 'values': ['assertive', 'off', 'polite'] +}], ['aria-modal', { + type: 'boolean' +}], ['aria-multiline', { + 'type': 'boolean' +}], ['aria-multiselectable', { + 'type': 'boolean' +}], ['aria-orientation', { + 'type': 'token', + 'values': ['vertical', 'undefined', 'horizontal'] +}], ['aria-owns', { + 'type': 'idlist' +}], ['aria-placeholder', { + type: 'string' +}], ['aria-posinset', { + 'type': 'integer' +}], ['aria-pressed', { + 'type': 'tristate' +}], ['aria-readonly', { + 'type': 'boolean' +}], ['aria-relevant', { + 'type': 'tokenlist', + 'values': ['additions', 'all', 'removals', 'text'] +}], ['aria-required', { + 'type': 'boolean' +}], ['aria-roledescription', { + type: 'string' +}], ['aria-rowcount', { + type: 'integer' +}], ['aria-rowindex', { + type: 'integer' +}], ['aria-rowspan', { + type: 'integer' +}], ['aria-selected', { + 'type': 'boolean', + 'allowundefined': true +}], ['aria-setsize', { + 'type': 'integer' +}], ['aria-sort', { + 'type': 'token', + 'values': ['ascending', 'descending', 'none', 'other'] +}], ['aria-valuemax', { + 'type': 'number' +}], ['aria-valuemin', { + 'type': 'number' +}], ['aria-valuenow', { + 'type': 'number' +}], ['aria-valuetext', { + 'type': 'string' +}]]; +var ariaPropsMap = { + entries: function entries() { + return properties; + }, + forEach: function forEach(fn) { + var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var _iterator = _createForOfIteratorHelper(properties), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var _step$value = _slicedToArray(_step.value, 2), + key = _step$value[0], + values = _step$value[1]; + fn.call(thisArg, values, key, properties); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + }, + get: function get(key) { + var item = properties.find(function (tuple) { + return tuple[0] === key ? true : false; + }); + return item && item[1]; + }, + has: function has(key) { + return !!ariaPropsMap.get(key); + }, + keys: function keys() { + return properties.map(function (_ref) { + var _ref2 = _slicedToArray(_ref, 1), + key = _ref2[0]; + return key; + }); + }, + values: function values() { + return properties.map(function (_ref3) { + var _ref4 = _slicedToArray(_ref3, 2), + values = _ref4[1]; + return values; + }); + } +}; +var _default = (0, _iterationDecorator.default)(ariaPropsMap, ariaPropsMap.entries()); +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/domMap.js b/node_modules/aria-query/lib/domMap.js new file mode 100644 index 0000000000000000000000000000000000000000..6fae5849f558aa192f22dc3b0f222f5d66a5a4f5 --- /dev/null +++ b/node_modules/aria-query/lib/domMap.js @@ -0,0 +1,321 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _iterationDecorator = _interopRequireDefault(require("./util/iterationDecorator")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } +var dom = [['a', { + reserved: false +}], ['abbr', { + reserved: false +}], ['acronym', { + reserved: false +}], ['address', { + reserved: false +}], ['applet', { + reserved: false +}], ['area', { + reserved: false +}], ['article', { + reserved: false +}], ['aside', { + reserved: false +}], ['audio', { + reserved: false +}], ['b', { + reserved: false +}], ['base', { + reserved: true +}], ['bdi', { + reserved: false +}], ['bdo', { + reserved: false +}], ['big', { + reserved: false +}], ['blink', { + reserved: false +}], ['blockquote', { + reserved: false +}], ['body', { + reserved: false +}], ['br', { + reserved: false +}], ['button', { + reserved: false +}], ['canvas', { + reserved: false +}], ['caption', { + reserved: false +}], ['center', { + reserved: false +}], ['cite', { + reserved: false +}], ['code', { + reserved: false +}], ['col', { + reserved: true +}], ['colgroup', { + reserved: true +}], ['content', { + reserved: false +}], ['data', { + reserved: false +}], ['datalist', { + reserved: false +}], ['dd', { + reserved: false +}], ['del', { + reserved: false +}], ['details', { + reserved: false +}], ['dfn', { + reserved: false +}], ['dialog', { + reserved: false +}], ['dir', { + reserved: false +}], ['div', { + reserved: false +}], ['dl', { + reserved: false +}], ['dt', { + reserved: false +}], ['em', { + reserved: false +}], ['embed', { + reserved: false +}], ['fieldset', { + reserved: false +}], ['figcaption', { + reserved: false +}], ['figure', { + reserved: false +}], ['font', { + reserved: false +}], ['footer', { + reserved: false +}], ['form', { + reserved: false +}], ['frame', { + reserved: false +}], ['frameset', { + reserved: false +}], ['h1', { + reserved: false +}], ['h2', { + reserved: false +}], ['h3', { + reserved: false +}], ['h4', { + reserved: false +}], ['h5', { + reserved: false +}], ['h6', { + reserved: false +}], ['head', { + reserved: true +}], ['header', { + reserved: false +}], ['hgroup', { + reserved: false +}], ['hr', { + reserved: false +}], ['html', { + reserved: true +}], ['i', { + reserved: false +}], ['iframe', { + reserved: false +}], ['img', { + reserved: false +}], ['input', { + reserved: false +}], ['ins', { + reserved: false +}], ['kbd', { + reserved: false +}], ['keygen', { + reserved: false +}], ['label', { + reserved: false +}], ['legend', { + reserved: false +}], ['li', { + reserved: false +}], ['link', { + reserved: true +}], ['main', { + reserved: false +}], ['map', { + reserved: false +}], ['mark', { + reserved: false +}], ['marquee', { + reserved: false +}], ['menu', { + reserved: false +}], ['menuitem', { + reserved: false +}], ['meta', { + reserved: true +}], ['meter', { + reserved: false +}], ['nav', { + reserved: false +}], ['noembed', { + reserved: true +}], ['noscript', { + reserved: true +}], ['object', { + reserved: false +}], ['ol', { + reserved: false +}], ['optgroup', { + reserved: false +}], ['option', { + reserved: false +}], ['output', { + reserved: false +}], ['p', { + reserved: false +}], ['param', { + reserved: true +}], ['picture', { + reserved: true +}], ['pre', { + reserved: false +}], ['progress', { + reserved: false +}], ['q', { + reserved: false +}], ['rp', { + reserved: false +}], ['rt', { + reserved: false +}], ['rtc', { + reserved: false +}], ['ruby', { + reserved: false +}], ['s', { + reserved: false +}], ['samp', { + reserved: false +}], ['script', { + reserved: true +}], ['section', { + reserved: false +}], ['select', { + reserved: false +}], ['small', { + reserved: false +}], ['source', { + reserved: true +}], ['spacer', { + reserved: false +}], ['span', { + reserved: false +}], ['strike', { + reserved: false +}], ['strong', { + reserved: false +}], ['style', { + reserved: true +}], ['sub', { + reserved: false +}], ['summary', { + reserved: false +}], ['sup', { + reserved: false +}], ['table', { + reserved: false +}], ['tbody', { + reserved: false +}], ['td', { + reserved: false +}], ['textarea', { + reserved: false +}], ['tfoot', { + reserved: false +}], ['th', { + reserved: false +}], ['thead', { + reserved: false +}], ['time', { + reserved: false +}], ['title', { + reserved: true +}], ['tr', { + reserved: false +}], ['track', { + reserved: true +}], ['tt', { + reserved: false +}], ['u', { + reserved: false +}], ['ul', { + reserved: false +}], ['var', { + reserved: false +}], ['video', { + reserved: false +}], ['wbr', { + reserved: false +}], ['xmp', { + reserved: false +}]]; +var domMap = { + entries: function entries() { + return dom; + }, + forEach: function forEach(fn) { + var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var _iterator = _createForOfIteratorHelper(dom), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var _step$value = _slicedToArray(_step.value, 2), + key = _step$value[0], + values = _step$value[1]; + fn.call(thisArg, values, key, dom); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + }, + get: function get(key) { + var item = dom.find(function (tuple) { + return tuple[0] === key ? true : false; + }); + return item && item[1]; + }, + has: function has(key) { + return !!domMap.get(key); + }, + keys: function keys() { + return dom.map(function (_ref) { + var _ref2 = _slicedToArray(_ref, 1), + key = _ref2[0]; + return key; + }); + }, + values: function values() { + return dom.map(function (_ref3) { + var _ref4 = _slicedToArray(_ref3, 2), + values = _ref4[1]; + return values; + }); + } +}; +var _default = (0, _iterationDecorator.default)(domMap, domMap.entries()); +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/elementRoleMap.js b/node_modules/aria-query/lib/elementRoleMap.js new file mode 100644 index 0000000000000000000000000000000000000000..4ede6ae64602db756da93e3d274d15050d8c6736 --- /dev/null +++ b/node_modules/aria-query/lib/elementRoleMap.js @@ -0,0 +1,103 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _lite = require("dequal/lite"); +var _iterationDecorator = _interopRequireDefault(require("./util/iterationDecorator")); +var _rolesMap = _interopRequireDefault(require("./rolesMap")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } +var elementRoles = []; +var keys = _rolesMap.default.keys(); +for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var role = _rolesMap.default.get(key); + if (role) { + var concepts = [].concat(role.baseConcepts, role.relatedConcepts); + for (var k = 0; k < concepts.length; k++) { + var relation = concepts[k]; + if (relation.module === 'HTML') { + (function () { + var concept = relation.concept; + if (concept) { + var elementRoleRelation = elementRoles.find(function (relation) { + return (0, _lite.dequal)(relation, concept); + }); + var roles; + if (elementRoleRelation) { + roles = elementRoleRelation[1]; + } else { + roles = []; + } + var isUnique = true; + for (var _i = 0; _i < roles.length; _i++) { + if (roles[_i] === key) { + isUnique = false; + break; + } + } + if (isUnique) { + roles.push(key); + } + elementRoles.push([concept, roles]); + } + })(); + } + } + } +} +var elementRoleMap = { + entries: function entries() { + return elementRoles; + }, + forEach: function forEach(fn) { + var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var _iterator = _createForOfIteratorHelper(elementRoles), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var _step$value = _slicedToArray(_step.value, 2), + _key = _step$value[0], + values = _step$value[1]; + fn.call(thisArg, values, _key, elementRoles); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + }, + get: function get(key) { + var item = elementRoles.find(function (tuple) { + return key.name === tuple[0].name && (0, _lite.dequal)(key.attributes, tuple[0].attributes); + }); + return item && item[1]; + }, + has: function has(key) { + return !!elementRoleMap.get(key); + }, + keys: function keys() { + return elementRoles.map(function (_ref) { + var _ref2 = _slicedToArray(_ref, 1), + key = _ref2[0]; + return key; + }); + }, + values: function values() { + return elementRoles.map(function (_ref3) { + var _ref4 = _slicedToArray(_ref3, 2), + values = _ref4[1]; + return values; + }); + } +}; +var _default = (0, _iterationDecorator.default)(elementRoleMap, elementRoleMap.entries()); +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/abstract/commandRole.js b/node_modules/aria-query/lib/etc/roles/abstract/commandRole.js new file mode 100644 index 0000000000000000000000000000000000000000..015315583e062a9f97eccb30b2620ace3cb60a1d --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/abstract/commandRole.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var commandRole = { + abstract: true, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'widget']] +}; +var _default = commandRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/abstract/compositeRole.js b/node_modules/aria-query/lib/etc/roles/abstract/compositeRole.js new file mode 100644 index 0000000000000000000000000000000000000000..e53cc3c27d8efc58776780b690f644264d37e9d6 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/abstract/compositeRole.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var compositeRole = { + abstract: true, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-activedescendant': null, + 'aria-disabled': null + }, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'widget']] +}; +var _default = compositeRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/abstract/inputRole.js b/node_modules/aria-query/lib/etc/roles/abstract/inputRole.js new file mode 100644 index 0000000000000000000000000000000000000000..a8249b9d476e6edf21e9cf932ade0189fef8a22b --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/abstract/inputRole.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var inputRole = { + abstract: true, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null + }, + relatedConcepts: [{ + concept: { + name: 'input' + }, + module: 'XForms' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'widget']] +}; +var _default = inputRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/abstract/landmarkRole.js b/node_modules/aria-query/lib/etc/roles/abstract/landmarkRole.js new file mode 100644 index 0000000000000000000000000000000000000000..180ee6e12ed8e2db04e3bd6e7ae78e18ecb6b13f --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/abstract/landmarkRole.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var landmarkRole = { + abstract: true, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = landmarkRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/abstract/rangeRole.js b/node_modules/aria-query/lib/etc/roles/abstract/rangeRole.js new file mode 100644 index 0000000000000000000000000000000000000000..7e9e878fb14d75a072911533dfad159154c5f8c2 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/abstract/rangeRole.js @@ -0,0 +1,27 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var rangeRole = { + abstract: true, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-valuemax': null, + 'aria-valuemin': null, + 'aria-valuenow': null + }, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure']] +}; +var _default = rangeRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/abstract/roletypeRole.js b/node_modules/aria-query/lib/etc/roles/abstract/roletypeRole.js new file mode 100644 index 0000000000000000000000000000000000000000..90af180a2dedda6df36d4642f453ee6610a5ba09 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/abstract/roletypeRole.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var roletypeRole = { + abstract: true, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: [], + prohibitedProps: [], + props: { + 'aria-atomic': null, + 'aria-busy': null, + 'aria-controls': null, + 'aria-current': null, + 'aria-describedby': null, + 'aria-details': null, + 'aria-dropeffect': null, + 'aria-flowto': null, + 'aria-grabbed': null, + 'aria-hidden': null, + 'aria-keyshortcuts': null, + 'aria-label': null, + 'aria-labelledby': null, + 'aria-live': null, + 'aria-owns': null, + 'aria-relevant': null, + 'aria-roledescription': null + }, + relatedConcepts: [{ + concept: { + name: 'role' + }, + module: 'XHTML' + }, { + concept: { + name: 'type' + }, + module: 'Dublin Core' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [] +}; +var _default = roletypeRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/abstract/sectionRole.js b/node_modules/aria-query/lib/etc/roles/abstract/sectionRole.js new file mode 100644 index 0000000000000000000000000000000000000000..06643bf6a22ad3fdc97bc5f93533280c281ecb5c --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/abstract/sectionRole.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var sectionRole = { + abstract: true, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: [], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'frontmatter' + }, + module: 'DTB' + }, { + concept: { + name: 'level' + }, + module: 'DTB' + }, { + concept: { + name: 'level' + }, + module: 'SMIL' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure']] +}; +var _default = sectionRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/abstract/sectionheadRole.js b/node_modules/aria-query/lib/etc/roles/abstract/sectionheadRole.js new file mode 100644 index 0000000000000000000000000000000000000000..1ea8df00f8d528fd8643638b7a9434801d04639a --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/abstract/sectionheadRole.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var sectionheadRole = { + abstract: true, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: {}, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure']] +}; +var _default = sectionheadRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/abstract/selectRole.js b/node_modules/aria-query/lib/etc/roles/abstract/selectRole.js new file mode 100644 index 0000000000000000000000000000000000000000..e2a14c26b1d8e72f7c94339e5f1bbd2672c4b6be --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/abstract/selectRole.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var selectRole = { + abstract: true, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-orientation': null + }, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'widget', 'composite'], ['roletype', 'structure', 'section', 'group']] +}; +var _default = selectRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/abstract/structureRole.js b/node_modules/aria-query/lib/etc/roles/abstract/structureRole.js new file mode 100644 index 0000000000000000000000000000000000000000..127859c507d4030acaf3767d566c98faf8983420 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/abstract/structureRole.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var structureRole = { + abstract: true, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: [], + prohibitedProps: [], + props: {}, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype']] +}; +var _default = structureRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/abstract/widgetRole.js b/node_modules/aria-query/lib/etc/roles/abstract/widgetRole.js new file mode 100644 index 0000000000000000000000000000000000000000..ce504e531828e3dc8a5eb08ed022a3d4056f7b3e --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/abstract/widgetRole.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var widgetRole = { + abstract: true, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: [], + prohibitedProps: [], + props: {}, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype']] +}; +var _default = widgetRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/abstract/windowRole.js b/node_modules/aria-query/lib/etc/roles/abstract/windowRole.js new file mode 100644 index 0000000000000000000000000000000000000000..6d98a459685160a589977a1ab180bf6e16f61bfd --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/abstract/windowRole.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var windowRole = { + abstract: true, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-modal': null + }, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype']] +}; +var _default = windowRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/ariaAbstractRoles.js b/node_modules/aria-query/lib/etc/roles/ariaAbstractRoles.js new file mode 100644 index 0000000000000000000000000000000000000000..4714776e233781e4d364aa8c0d8771efdb13231a --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/ariaAbstractRoles.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _commandRole = _interopRequireDefault(require("./abstract/commandRole")); +var _compositeRole = _interopRequireDefault(require("./abstract/compositeRole")); +var _inputRole = _interopRequireDefault(require("./abstract/inputRole")); +var _landmarkRole = _interopRequireDefault(require("./abstract/landmarkRole")); +var _rangeRole = _interopRequireDefault(require("./abstract/rangeRole")); +var _roletypeRole = _interopRequireDefault(require("./abstract/roletypeRole")); +var _sectionRole = _interopRequireDefault(require("./abstract/sectionRole")); +var _sectionheadRole = _interopRequireDefault(require("./abstract/sectionheadRole")); +var _selectRole = _interopRequireDefault(require("./abstract/selectRole")); +var _structureRole = _interopRequireDefault(require("./abstract/structureRole")); +var _widgetRole = _interopRequireDefault(require("./abstract/widgetRole")); +var _windowRole = _interopRequireDefault(require("./abstract/windowRole")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ariaAbstractRoles = [['command', _commandRole.default], ['composite', _compositeRole.default], ['input', _inputRole.default], ['landmark', _landmarkRole.default], ['range', _rangeRole.default], ['roletype', _roletypeRole.default], ['section', _sectionRole.default], ['sectionhead', _sectionheadRole.default], ['select', _selectRole.default], ['structure', _structureRole.default], ['widget', _widgetRole.default], ['window', _windowRole.default]]; +var _default = ariaAbstractRoles; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/ariaDpubRoles.js b/node_modules/aria-query/lib/etc/roles/ariaDpubRoles.js new file mode 100644 index 0000000000000000000000000000000000000000..d873f4054045e7178a395125e588f05e421a895f --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/ariaDpubRoles.js @@ -0,0 +1,50 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _docAbstractRole = _interopRequireDefault(require("./dpub/docAbstractRole")); +var _docAcknowledgmentsRole = _interopRequireDefault(require("./dpub/docAcknowledgmentsRole")); +var _docAfterwordRole = _interopRequireDefault(require("./dpub/docAfterwordRole")); +var _docAppendixRole = _interopRequireDefault(require("./dpub/docAppendixRole")); +var _docBacklinkRole = _interopRequireDefault(require("./dpub/docBacklinkRole")); +var _docBiblioentryRole = _interopRequireDefault(require("./dpub/docBiblioentryRole")); +var _docBibliographyRole = _interopRequireDefault(require("./dpub/docBibliographyRole")); +var _docBibliorefRole = _interopRequireDefault(require("./dpub/docBibliorefRole")); +var _docChapterRole = _interopRequireDefault(require("./dpub/docChapterRole")); +var _docColophonRole = _interopRequireDefault(require("./dpub/docColophonRole")); +var _docConclusionRole = _interopRequireDefault(require("./dpub/docConclusionRole")); +var _docCoverRole = _interopRequireDefault(require("./dpub/docCoverRole")); +var _docCreditRole = _interopRequireDefault(require("./dpub/docCreditRole")); +var _docCreditsRole = _interopRequireDefault(require("./dpub/docCreditsRole")); +var _docDedicationRole = _interopRequireDefault(require("./dpub/docDedicationRole")); +var _docEndnoteRole = _interopRequireDefault(require("./dpub/docEndnoteRole")); +var _docEndnotesRole = _interopRequireDefault(require("./dpub/docEndnotesRole")); +var _docEpigraphRole = _interopRequireDefault(require("./dpub/docEpigraphRole")); +var _docEpilogueRole = _interopRequireDefault(require("./dpub/docEpilogueRole")); +var _docErrataRole = _interopRequireDefault(require("./dpub/docErrataRole")); +var _docExampleRole = _interopRequireDefault(require("./dpub/docExampleRole")); +var _docFootnoteRole = _interopRequireDefault(require("./dpub/docFootnoteRole")); +var _docForewordRole = _interopRequireDefault(require("./dpub/docForewordRole")); +var _docGlossaryRole = _interopRequireDefault(require("./dpub/docGlossaryRole")); +var _docGlossrefRole = _interopRequireDefault(require("./dpub/docGlossrefRole")); +var _docIndexRole = _interopRequireDefault(require("./dpub/docIndexRole")); +var _docIntroductionRole = _interopRequireDefault(require("./dpub/docIntroductionRole")); +var _docNoterefRole = _interopRequireDefault(require("./dpub/docNoterefRole")); +var _docNoticeRole = _interopRequireDefault(require("./dpub/docNoticeRole")); +var _docPagebreakRole = _interopRequireDefault(require("./dpub/docPagebreakRole")); +var _docPagelistRole = _interopRequireDefault(require("./dpub/docPagelistRole")); +var _docPartRole = _interopRequireDefault(require("./dpub/docPartRole")); +var _docPrefaceRole = _interopRequireDefault(require("./dpub/docPrefaceRole")); +var _docPrologueRole = _interopRequireDefault(require("./dpub/docPrologueRole")); +var _docPullquoteRole = _interopRequireDefault(require("./dpub/docPullquoteRole")); +var _docQnaRole = _interopRequireDefault(require("./dpub/docQnaRole")); +var _docSubtitleRole = _interopRequireDefault(require("./dpub/docSubtitleRole")); +var _docTipRole = _interopRequireDefault(require("./dpub/docTipRole")); +var _docTocRole = _interopRequireDefault(require("./dpub/docTocRole")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ariaDpubRoles = [['doc-abstract', _docAbstractRole.default], ['doc-acknowledgments', _docAcknowledgmentsRole.default], ['doc-afterword', _docAfterwordRole.default], ['doc-appendix', _docAppendixRole.default], ['doc-backlink', _docBacklinkRole.default], ['doc-biblioentry', _docBiblioentryRole.default], ['doc-bibliography', _docBibliographyRole.default], ['doc-biblioref', _docBibliorefRole.default], ['doc-chapter', _docChapterRole.default], ['doc-colophon', _docColophonRole.default], ['doc-conclusion', _docConclusionRole.default], ['doc-cover', _docCoverRole.default], ['doc-credit', _docCreditRole.default], ['doc-credits', _docCreditsRole.default], ['doc-dedication', _docDedicationRole.default], ['doc-endnote', _docEndnoteRole.default], ['doc-endnotes', _docEndnotesRole.default], ['doc-epigraph', _docEpigraphRole.default], ['doc-epilogue', _docEpilogueRole.default], ['doc-errata', _docErrataRole.default], ['doc-example', _docExampleRole.default], ['doc-footnote', _docFootnoteRole.default], ['doc-foreword', _docForewordRole.default], ['doc-glossary', _docGlossaryRole.default], ['doc-glossref', _docGlossrefRole.default], ['doc-index', _docIndexRole.default], ['doc-introduction', _docIntroductionRole.default], ['doc-noteref', _docNoterefRole.default], ['doc-notice', _docNoticeRole.default], ['doc-pagebreak', _docPagebreakRole.default], ['doc-pagelist', _docPagelistRole.default], ['doc-part', _docPartRole.default], ['doc-preface', _docPrefaceRole.default], ['doc-prologue', _docPrologueRole.default], ['doc-pullquote', _docPullquoteRole.default], ['doc-qna', _docQnaRole.default], ['doc-subtitle', _docSubtitleRole.default], ['doc-tip', _docTipRole.default], ['doc-toc', _docTocRole.default]]; +var _default = ariaDpubRoles; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/ariaGraphicsRoles.js b/node_modules/aria-query/lib/etc/roles/ariaGraphicsRoles.js new file mode 100644 index 0000000000000000000000000000000000000000..891d42c04668bb18ec4691643fd5121370bac8c5 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/ariaGraphicsRoles.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _graphicsDocumentRole = _interopRequireDefault(require("./graphics/graphicsDocumentRole")); +var _graphicsObjectRole = _interopRequireDefault(require("./graphics/graphicsObjectRole")); +var _graphicsSymbolRole = _interopRequireDefault(require("./graphics/graphicsSymbolRole")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ariaGraphicsRoles = [['graphics-document', _graphicsDocumentRole.default], ['graphics-object', _graphicsObjectRole.default], ['graphics-symbol', _graphicsSymbolRole.default]]; +var _default = ariaGraphicsRoles; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/ariaLiteralRoles.js b/node_modules/aria-query/lib/etc/roles/ariaLiteralRoles.js new file mode 100644 index 0000000000000000000000000000000000000000..7e7d38976113ddb877cdcbfd560b44ed0dc1ab20 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/ariaLiteralRoles.js @@ -0,0 +1,94 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _alertRole = _interopRequireDefault(require("./literal/alertRole")); +var _alertdialogRole = _interopRequireDefault(require("./literal/alertdialogRole")); +var _applicationRole = _interopRequireDefault(require("./literal/applicationRole")); +var _articleRole = _interopRequireDefault(require("./literal/articleRole")); +var _bannerRole = _interopRequireDefault(require("./literal/bannerRole")); +var _blockquoteRole = _interopRequireDefault(require("./literal/blockquoteRole")); +var _buttonRole = _interopRequireDefault(require("./literal/buttonRole")); +var _captionRole = _interopRequireDefault(require("./literal/captionRole")); +var _cellRole = _interopRequireDefault(require("./literal/cellRole")); +var _checkboxRole = _interopRequireDefault(require("./literal/checkboxRole")); +var _codeRole = _interopRequireDefault(require("./literal/codeRole")); +var _columnheaderRole = _interopRequireDefault(require("./literal/columnheaderRole")); +var _comboboxRole = _interopRequireDefault(require("./literal/comboboxRole")); +var _complementaryRole = _interopRequireDefault(require("./literal/complementaryRole")); +var _contentinfoRole = _interopRequireDefault(require("./literal/contentinfoRole")); +var _definitionRole = _interopRequireDefault(require("./literal/definitionRole")); +var _deletionRole = _interopRequireDefault(require("./literal/deletionRole")); +var _dialogRole = _interopRequireDefault(require("./literal/dialogRole")); +var _directoryRole = _interopRequireDefault(require("./literal/directoryRole")); +var _documentRole = _interopRequireDefault(require("./literal/documentRole")); +var _emphasisRole = _interopRequireDefault(require("./literal/emphasisRole")); +var _feedRole = _interopRequireDefault(require("./literal/feedRole")); +var _figureRole = _interopRequireDefault(require("./literal/figureRole")); +var _formRole = _interopRequireDefault(require("./literal/formRole")); +var _genericRole = _interopRequireDefault(require("./literal/genericRole")); +var _gridRole = _interopRequireDefault(require("./literal/gridRole")); +var _gridcellRole = _interopRequireDefault(require("./literal/gridcellRole")); +var _groupRole = _interopRequireDefault(require("./literal/groupRole")); +var _headingRole = _interopRequireDefault(require("./literal/headingRole")); +var _imgRole = _interopRequireDefault(require("./literal/imgRole")); +var _insertionRole = _interopRequireDefault(require("./literal/insertionRole")); +var _linkRole = _interopRequireDefault(require("./literal/linkRole")); +var _listRole = _interopRequireDefault(require("./literal/listRole")); +var _listboxRole = _interopRequireDefault(require("./literal/listboxRole")); +var _listitemRole = _interopRequireDefault(require("./literal/listitemRole")); +var _logRole = _interopRequireDefault(require("./literal/logRole")); +var _mainRole = _interopRequireDefault(require("./literal/mainRole")); +var _markRole = _interopRequireDefault(require("./literal/markRole")); +var _marqueeRole = _interopRequireDefault(require("./literal/marqueeRole")); +var _mathRole = _interopRequireDefault(require("./literal/mathRole")); +var _menuRole = _interopRequireDefault(require("./literal/menuRole")); +var _menubarRole = _interopRequireDefault(require("./literal/menubarRole")); +var _menuitemRole = _interopRequireDefault(require("./literal/menuitemRole")); +var _menuitemcheckboxRole = _interopRequireDefault(require("./literal/menuitemcheckboxRole")); +var _menuitemradioRole = _interopRequireDefault(require("./literal/menuitemradioRole")); +var _meterRole = _interopRequireDefault(require("./literal/meterRole")); +var _navigationRole = _interopRequireDefault(require("./literal/navigationRole")); +var _noneRole = _interopRequireDefault(require("./literal/noneRole")); +var _noteRole = _interopRequireDefault(require("./literal/noteRole")); +var _optionRole = _interopRequireDefault(require("./literal/optionRole")); +var _paragraphRole = _interopRequireDefault(require("./literal/paragraphRole")); +var _presentationRole = _interopRequireDefault(require("./literal/presentationRole")); +var _progressbarRole = _interopRequireDefault(require("./literal/progressbarRole")); +var _radioRole = _interopRequireDefault(require("./literal/radioRole")); +var _radiogroupRole = _interopRequireDefault(require("./literal/radiogroupRole")); +var _regionRole = _interopRequireDefault(require("./literal/regionRole")); +var _rowRole = _interopRequireDefault(require("./literal/rowRole")); +var _rowgroupRole = _interopRequireDefault(require("./literal/rowgroupRole")); +var _rowheaderRole = _interopRequireDefault(require("./literal/rowheaderRole")); +var _scrollbarRole = _interopRequireDefault(require("./literal/scrollbarRole")); +var _searchRole = _interopRequireDefault(require("./literal/searchRole")); +var _searchboxRole = _interopRequireDefault(require("./literal/searchboxRole")); +var _separatorRole = _interopRequireDefault(require("./literal/separatorRole")); +var _sliderRole = _interopRequireDefault(require("./literal/sliderRole")); +var _spinbuttonRole = _interopRequireDefault(require("./literal/spinbuttonRole")); +var _statusRole = _interopRequireDefault(require("./literal/statusRole")); +var _strongRole = _interopRequireDefault(require("./literal/strongRole")); +var _subscriptRole = _interopRequireDefault(require("./literal/subscriptRole")); +var _superscriptRole = _interopRequireDefault(require("./literal/superscriptRole")); +var _switchRole = _interopRequireDefault(require("./literal/switchRole")); +var _tabRole = _interopRequireDefault(require("./literal/tabRole")); +var _tableRole = _interopRequireDefault(require("./literal/tableRole")); +var _tablistRole = _interopRequireDefault(require("./literal/tablistRole")); +var _tabpanelRole = _interopRequireDefault(require("./literal/tabpanelRole")); +var _termRole = _interopRequireDefault(require("./literal/termRole")); +var _textboxRole = _interopRequireDefault(require("./literal/textboxRole")); +var _timeRole = _interopRequireDefault(require("./literal/timeRole")); +var _timerRole = _interopRequireDefault(require("./literal/timerRole")); +var _toolbarRole = _interopRequireDefault(require("./literal/toolbarRole")); +var _tooltipRole = _interopRequireDefault(require("./literal/tooltipRole")); +var _treeRole = _interopRequireDefault(require("./literal/treeRole")); +var _treegridRole = _interopRequireDefault(require("./literal/treegridRole")); +var _treeitemRole = _interopRequireDefault(require("./literal/treeitemRole")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ariaLiteralRoles = [['alert', _alertRole.default], ['alertdialog', _alertdialogRole.default], ['application', _applicationRole.default], ['article', _articleRole.default], ['banner', _bannerRole.default], ['blockquote', _blockquoteRole.default], ['button', _buttonRole.default], ['caption', _captionRole.default], ['cell', _cellRole.default], ['checkbox', _checkboxRole.default], ['code', _codeRole.default], ['columnheader', _columnheaderRole.default], ['combobox', _comboboxRole.default], ['complementary', _complementaryRole.default], ['contentinfo', _contentinfoRole.default], ['definition', _definitionRole.default], ['deletion', _deletionRole.default], ['dialog', _dialogRole.default], ['directory', _directoryRole.default], ['document', _documentRole.default], ['emphasis', _emphasisRole.default], ['feed', _feedRole.default], ['figure', _figureRole.default], ['form', _formRole.default], ['generic', _genericRole.default], ['grid', _gridRole.default], ['gridcell', _gridcellRole.default], ['group', _groupRole.default], ['heading', _headingRole.default], ['img', _imgRole.default], ['insertion', _insertionRole.default], ['link', _linkRole.default], ['list', _listRole.default], ['listbox', _listboxRole.default], ['listitem', _listitemRole.default], ['log', _logRole.default], ['main', _mainRole.default], ['mark', _markRole.default], ['marquee', _marqueeRole.default], ['math', _mathRole.default], ['menu', _menuRole.default], ['menubar', _menubarRole.default], ['menuitem', _menuitemRole.default], ['menuitemcheckbox', _menuitemcheckboxRole.default], ['menuitemradio', _menuitemradioRole.default], ['meter', _meterRole.default], ['navigation', _navigationRole.default], ['none', _noneRole.default], ['note', _noteRole.default], ['option', _optionRole.default], ['paragraph', _paragraphRole.default], ['presentation', _presentationRole.default], ['progressbar', _progressbarRole.default], ['radio', _radioRole.default], ['radiogroup', _radiogroupRole.default], ['region', _regionRole.default], ['row', _rowRole.default], ['rowgroup', _rowgroupRole.default], ['rowheader', _rowheaderRole.default], ['scrollbar', _scrollbarRole.default], ['search', _searchRole.default], ['searchbox', _searchboxRole.default], ['separator', _separatorRole.default], ['slider', _sliderRole.default], ['spinbutton', _spinbuttonRole.default], ['status', _statusRole.default], ['strong', _strongRole.default], ['subscript', _subscriptRole.default], ['superscript', _superscriptRole.default], ['switch', _switchRole.default], ['tab', _tabRole.default], ['table', _tableRole.default], ['tablist', _tablistRole.default], ['tabpanel', _tabpanelRole.default], ['term', _termRole.default], ['textbox', _textboxRole.default], ['time', _timeRole.default], ['timer', _timerRole.default], ['toolbar', _toolbarRole.default], ['tooltip', _tooltipRole.default], ['tree', _treeRole.default], ['treegrid', _treegridRole.default], ['treeitem', _treeitemRole.default]]; +var _default = ariaLiteralRoles; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docAbstractRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docAbstractRole.js new file mode 100644 index 0000000000000000000000000000000000000000..925a00a1506732d46ea4d0188419fd7f03dbe31f --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docAbstractRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docAbstractRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'abstract [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = docAbstractRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docAcknowledgmentsRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docAcknowledgmentsRole.js new file mode 100644 index 0000000000000000000000000000000000000000..1f35b4bad58fb320629aa13d395fa5d94915e283 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docAcknowledgmentsRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docAcknowledgmentsRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'acknowledgments [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = docAcknowledgmentsRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docAfterwordRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docAfterwordRole.js new file mode 100644 index 0000000000000000000000000000000000000000..f89cb45f106672e7b8aec3e2100d4d399152bf7f --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docAfterwordRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docAfterwordRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'afterword [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = docAfterwordRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docAppendixRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docAppendixRole.js new file mode 100644 index 0000000000000000000000000000000000000000..b8b40bb565f934b775730337242696818b5e9401 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docAppendixRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docAppendixRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'appendix [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = docAppendixRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docBacklinkRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docBacklinkRole.js new file mode 100644 index 0000000000000000000000000000000000000000..fb987347108b89917db5a0695d67941a890468ab --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docBacklinkRole.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docBacklinkRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-errormessage': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'referrer [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'widget', 'command', 'link']] +}; +var _default = docBacklinkRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docBiblioentryRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docBiblioentryRole.js new file mode 100644 index 0000000000000000000000000000000000000000..caf881cc602d1ffdd613d1a5f988a99b7fab73f8 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docBiblioentryRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docBiblioentryRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'EPUB biblioentry [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: ['doc-bibliography'], + requiredContextRole: ['doc-bibliography'], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'listitem']] +}; +var _default = docBiblioentryRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docBibliographyRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docBibliographyRole.js new file mode 100644 index 0000000000000000000000000000000000000000..d40c2426bf3cb135e253855590da60d9fea8726e --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docBibliographyRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docBibliographyRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'bibliography [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [['doc-biblioentry']], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = docBibliographyRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docBibliorefRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docBibliorefRole.js new file mode 100644 index 0000000000000000000000000000000000000000..9d101ff08845ffe1722ec339ce011701a91c402f --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docBibliorefRole.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docBibliorefRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-errormessage': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'biblioref [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'widget', 'command', 'link']] +}; +var _default = docBibliorefRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docChapterRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docChapterRole.js new file mode 100644 index 0000000000000000000000000000000000000000..969ed2b8f78b4411d25e8115bfbdf899895607a7 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docChapterRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docChapterRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'chapter [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = docChapterRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docColophonRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docColophonRole.js new file mode 100644 index 0000000000000000000000000000000000000000..0e2f3a54bd72cd9bbd8bba655d3ab25b66cd94bb --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docColophonRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docColophonRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'colophon [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = docColophonRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docConclusionRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docConclusionRole.js new file mode 100644 index 0000000000000000000000000000000000000000..d902350c5d98007befab70df02f16c7700bae8a9 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docConclusionRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docConclusionRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'conclusion [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = docConclusionRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docCoverRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docCoverRole.js new file mode 100644 index 0000000000000000000000000000000000000000..fd58fec14891f341daf51cc41cc5c687dda73f61 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docCoverRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docCoverRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'cover [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'img']] +}; +var _default = docCoverRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docCreditRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docCreditRole.js new file mode 100644 index 0000000000000000000000000000000000000000..3e58a9e0a42811ae19e58bfcdbec4489e4a3de33 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docCreditRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docCreditRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'credit [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = docCreditRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docCreditsRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docCreditsRole.js new file mode 100644 index 0000000000000000000000000000000000000000..17a197fa791fb2c834c9eb5ec700cfcbf50ddd77 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docCreditsRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docCreditsRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'credits [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = docCreditsRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docDedicationRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docDedicationRole.js new file mode 100644 index 0000000000000000000000000000000000000000..797229e641438ed937de4ae29a35b2324a71281b --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docDedicationRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docDedicationRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'dedication [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = docDedicationRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docEndnoteRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docEndnoteRole.js new file mode 100644 index 0000000000000000000000000000000000000000..79b68854921e70cfb021b428a7829c3e67b45c8d --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docEndnoteRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docEndnoteRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'rearnote [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: ['doc-endnotes'], + requiredContextRole: ['doc-endnotes'], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'listitem']] +}; +var _default = docEndnoteRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docEndnotesRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docEndnotesRole.js new file mode 100644 index 0000000000000000000000000000000000000000..76e8a643f1f150c2f37b662f9c4b58bc5fab96ce --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docEndnotesRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docEndnotesRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'rearnotes [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [['doc-endnote']], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = docEndnotesRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docEpigraphRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docEpigraphRole.js new file mode 100644 index 0000000000000000000000000000000000000000..0199428fdad060d352f6417aeab1fe8e40f37209 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docEpigraphRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docEpigraphRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'epigraph [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = docEpigraphRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docEpilogueRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docEpilogueRole.js new file mode 100644 index 0000000000000000000000000000000000000000..3ba1f60922972b967fcceaf4cced8ed9a7211344 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docEpilogueRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docEpilogueRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'epilogue [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = docEpilogueRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docErrataRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docErrataRole.js new file mode 100644 index 0000000000000000000000000000000000000000..7677499437528c1f0803822cb9d5b0ebb03efa0a --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docErrataRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docErrataRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'errata [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = docErrataRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docExampleRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docExampleRole.js new file mode 100644 index 0000000000000000000000000000000000000000..e0428c73ae24421230e7c40b85f0d2bf1fdf46ec --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docExampleRole.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docExampleRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = docExampleRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docFootnoteRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docFootnoteRole.js new file mode 100644 index 0000000000000000000000000000000000000000..de4045cb072b01c0898281116e59b91c18d24854 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docFootnoteRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docFootnoteRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'footnote [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = docFootnoteRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docForewordRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docForewordRole.js new file mode 100644 index 0000000000000000000000000000000000000000..7be3990b9b101bb94f2d2e622b3df57f7b497172 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docForewordRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docForewordRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'foreword [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = docForewordRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docGlossaryRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docGlossaryRole.js new file mode 100644 index 0000000000000000000000000000000000000000..657da230ce69da95ffd6a855f141562865cd6334 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docGlossaryRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docGlossaryRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'glossary [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [['definition'], ['term']], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = docGlossaryRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docGlossrefRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docGlossrefRole.js new file mode 100644 index 0000000000000000000000000000000000000000..c66b0975f43344804b1daa318f2db8a56804770f --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docGlossrefRole.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docGlossrefRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-errormessage': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'glossref [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'widget', 'command', 'link']] +}; +var _default = docGlossrefRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docIndexRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docIndexRole.js new file mode 100644 index 0000000000000000000000000000000000000000..a579a39e5e2c6beb109f385230f8847bfa16f1d5 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docIndexRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docIndexRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'index [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark', 'navigation']] +}; +var _default = docIndexRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docIntroductionRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docIntroductionRole.js new file mode 100644 index 0000000000000000000000000000000000000000..7a224ebc1e94ffef79270a3521375c8c02551f41 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docIntroductionRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docIntroductionRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'introduction [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = docIntroductionRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docNoterefRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docNoterefRole.js new file mode 100644 index 0000000000000000000000000000000000000000..3a39d1d9b96fefa6842e7c8aaa438ed57844db0c --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docNoterefRole.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docNoterefRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-errormessage': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'noteref [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'widget', 'command', 'link']] +}; +var _default = docNoterefRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docNoticeRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docNoticeRole.js new file mode 100644 index 0000000000000000000000000000000000000000..817183d9d7c5b12b920637b05061e3c6e6f3c353 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docNoticeRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docNoticeRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'notice [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'note']] +}; +var _default = docNoticeRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docPagebreakRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docPagebreakRole.js new file mode 100644 index 0000000000000000000000000000000000000000..2468e7b2241eb29bacf84bab0c2667ca973412bb --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docPagebreakRole.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docPagebreakRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: true, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'pagebreak [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'separator']] +}; +var _default = docPagebreakRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docPagelistRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docPagelistRole.js new file mode 100644 index 0000000000000000000000000000000000000000..93dd6833f98f9c52a5b54f66bf4c8187ad2cdb81 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docPagelistRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docPagelistRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'page-list [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark', 'navigation']] +}; +var _default = docPagelistRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docPartRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docPartRole.js new file mode 100644 index 0000000000000000000000000000000000000000..0a1f96734d87bcc0428906048e7e5098db1b7f3a --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docPartRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docPartRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'part [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = docPartRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docPrefaceRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docPrefaceRole.js new file mode 100644 index 0000000000000000000000000000000000000000..4224228fcc6888f97c58416a3e6af55a36be654a --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docPrefaceRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docPrefaceRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'preface [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = docPrefaceRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docPrologueRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docPrologueRole.js new file mode 100644 index 0000000000000000000000000000000000000000..074b86eac15937d9ac325dae7dc24a41220c77d0 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docPrologueRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docPrologueRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'prologue [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = docPrologueRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docPullquoteRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docPullquoteRole.js new file mode 100644 index 0000000000000000000000000000000000000000..ee07800e7abad2943c1bfa7fe2142fc07e95c010 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docPullquoteRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docPullquoteRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'pullquote [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['none']] +}; +var _default = docPullquoteRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docQnaRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docQnaRole.js new file mode 100644 index 0000000000000000000000000000000000000000..9a1b7625a993f8e2457ad123dc507ac4e71103af --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docQnaRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docQnaRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'qna [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = docQnaRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docSubtitleRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docSubtitleRole.js new file mode 100644 index 0000000000000000000000000000000000000000..32bdf25801ef1106a02b8217ba00089b9cc95ceb --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docSubtitleRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docSubtitleRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'subtitle [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'sectionhead']] +}; +var _default = docSubtitleRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docTipRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docTipRole.js new file mode 100644 index 0000000000000000000000000000000000000000..1179ff64347a99d73a7aa0c3fe3873d10033508e --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docTipRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docTipRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'help [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'note']] +}; +var _default = docTipRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/dpub/docTocRole.js b/node_modules/aria-query/lib/etc/roles/dpub/docTocRole.js new file mode 100644 index 0000000000000000000000000000000000000000..0a86bb1ee41d6372495039bf71c6dd27ca28252f --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/dpub/docTocRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var docTocRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'toc [EPUB-SSV]' + }, + module: 'EPUB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark', 'navigation']] +}; +var _default = docTocRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/graphics/graphicsDocumentRole.js b/node_modules/aria-query/lib/etc/roles/graphics/graphicsDocumentRole.js new file mode 100644 index 0000000000000000000000000000000000000000..a115606102b5defd00c22c68b8190e08dbbf9e1b --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/graphics/graphicsDocumentRole.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var graphicsDocumentRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + module: 'GRAPHICS', + concept: { + name: 'graphics-object' + } + }, { + module: 'ARIA', + concept: { + name: 'img' + } + }, { + module: 'ARIA', + concept: { + name: 'article' + } + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'document']] +}; +var _default = graphicsDocumentRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/graphics/graphicsObjectRole.js b/node_modules/aria-query/lib/etc/roles/graphics/graphicsObjectRole.js new file mode 100644 index 0000000000000000000000000000000000000000..2d24a09f8ff44fac2d259c440bc61b956ce11e37 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/graphics/graphicsObjectRole.js @@ -0,0 +1,48 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var graphicsObjectRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + module: 'GRAPHICS', + concept: { + name: 'graphics-document' + } + }, { + module: 'ARIA', + concept: { + name: 'group' + } + }, { + module: 'ARIA', + concept: { + name: 'img' + } + }, { + module: 'GRAPHICS', + concept: { + name: 'graphics-symbol' + } + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'group']] +}; +var _default = graphicsObjectRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/graphics/graphicsSymbolRole.js b/node_modules/aria-query/lib/etc/roles/graphics/graphicsSymbolRole.js new file mode 100644 index 0000000000000000000000000000000000000000..79d02b68942ea30983e7fc3819c2e8932659de66 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/graphics/graphicsSymbolRole.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var graphicsSymbolRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: true, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'img']] +}; +var _default = graphicsSymbolRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/alertRole.js b/node_modules/aria-query/lib/etc/roles/literal/alertRole.js new file mode 100644 index 0000000000000000000000000000000000000000..2fdcfd5268cde6c8759a0cc3c92ed8e6b7b433e8 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/alertRole.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var alertRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-atomic': 'true', + 'aria-live': 'assertive' + }, + relatedConcepts: [{ + concept: { + name: 'alert' + }, + module: 'XForms' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = alertRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/alertdialogRole.js b/node_modules/aria-query/lib/etc/roles/literal/alertdialogRole.js new file mode 100644 index 0000000000000000000000000000000000000000..dc046c4073f08a62c9adc89d85df1c940a2e630b --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/alertdialogRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var alertdialogRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'alert' + }, + module: 'XForms' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'alert'], ['roletype', 'window', 'dialog']] +}; +var _default = alertdialogRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/applicationRole.js b/node_modules/aria-query/lib/etc/roles/literal/applicationRole.js new file mode 100644 index 0000000000000000000000000000000000000000..d4a1f9f5ff9a040c40ec628ac4b6bede7e7e023f --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/applicationRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var applicationRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-activedescendant': null, + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + concept: { + name: 'Device Independence Delivery Unit' + } + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure']] +}; +var _default = applicationRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/articleRole.js b/node_modules/aria-query/lib/etc/roles/literal/articleRole.js new file mode 100644 index 0000000000000000000000000000000000000000..64aceb8b4591386223597e99b8c706da90def0f2 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/articleRole.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var articleRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-posinset': null, + 'aria-setsize': null + }, + relatedConcepts: [{ + concept: { + name: 'article' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'document']] +}; +var _default = articleRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/bannerRole.js b/node_modules/aria-query/lib/etc/roles/literal/bannerRole.js new file mode 100644 index 0000000000000000000000000000000000000000..c53c6b27b7d6e7cde1a4a7c3f87848b77e5cab26 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/bannerRole.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var bannerRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + constraints: ['scoped to the body element'], + name: 'header' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = bannerRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/blockquoteRole.js b/node_modules/aria-query/lib/etc/roles/literal/blockquoteRole.js new file mode 100644 index 0000000000000000000000000000000000000000..bce16360801ee30c798aea93b6bb89cda93e3627 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/blockquoteRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var blockquoteRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'blockquote' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = blockquoteRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/buttonRole.js b/node_modules/aria-query/lib/etc/roles/literal/buttonRole.js new file mode 100644 index 0000000000000000000000000000000000000000..e4f71aa13e0d9cb92d3cb3cc3bd91a36564fb301 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/buttonRole.js @@ -0,0 +1,74 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var buttonRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: true, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-pressed': null + }, + relatedConcepts: [{ + concept: { + attributes: [{ + name: 'type', + value: 'button' + }], + name: 'input' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + name: 'type', + value: 'image' + }], + name: 'input' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + name: 'type', + value: 'reset' + }], + name: 'input' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + name: 'type', + value: 'submit' + }], + name: 'input' + }, + module: 'HTML' + }, { + concept: { + name: 'button' + }, + module: 'HTML' + }, { + concept: { + name: 'trigger' + }, + module: 'XForms' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'widget', 'command']] +}; +var _default = buttonRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/captionRole.js b/node_modules/aria-query/lib/etc/roles/literal/captionRole.js new file mode 100644 index 0000000000000000000000000000000000000000..a9e32b45b9b4eb53db27729e4300bc5a2ba2ecc3 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/captionRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var captionRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['prohibited'], + prohibitedProps: ['aria-label', 'aria-labelledby'], + props: {}, + relatedConcepts: [{ + concept: { + name: 'caption' + }, + module: 'HTML' + }], + requireContextRole: ['figure', 'grid', 'table'], + requiredContextRole: ['figure', 'grid', 'table'], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = captionRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/cellRole.js b/node_modules/aria-query/lib/etc/roles/literal/cellRole.js new file mode 100644 index 0000000000000000000000000000000000000000..294ad6bdbd9e3744ae72394f12304ef47c0fa412 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/cellRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var cellRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-colindex': null, + 'aria-colspan': null, + 'aria-rowindex': null, + 'aria-rowspan': null + }, + relatedConcepts: [{ + concept: { + constraints: ['ancestor table element has table role'], + name: 'td' + }, + module: 'HTML' + }], + requireContextRole: ['row'], + requiredContextRole: ['row'], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = cellRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/checkboxRole.js b/node_modules/aria-query/lib/etc/roles/literal/checkboxRole.js new file mode 100644 index 0000000000000000000000000000000000000000..5f152c7622289ed172644c2d945849838c4c59e9 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/checkboxRole.js @@ -0,0 +1,46 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var checkboxRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: true, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-checked': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-invalid': null, + 'aria-readonly': null, + 'aria-required': null + }, + relatedConcepts: [{ + concept: { + attributes: [{ + name: 'type', + value: 'checkbox' + }], + name: 'input' + }, + module: 'HTML' + }, { + concept: { + name: 'option' + }, + module: 'ARIA' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: { + 'aria-checked': null + }, + superClass: [['roletype', 'widget', 'input']] +}; +var _default = checkboxRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/codeRole.js b/node_modules/aria-query/lib/etc/roles/literal/codeRole.js new file mode 100644 index 0000000000000000000000000000000000000000..c78bd7a97ade85889fdac5b8323662f786eade3c --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/codeRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var codeRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['prohibited'], + prohibitedProps: ['aria-label', 'aria-labelledby'], + props: {}, + relatedConcepts: [{ + concept: { + name: 'code' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = codeRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/columnheaderRole.js b/node_modules/aria-query/lib/etc/roles/literal/columnheaderRole.js new file mode 100644 index 0000000000000000000000000000000000000000..6c40199d8216a9d17ea05990491dfaf2a23c3665 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/columnheaderRole.js @@ -0,0 +1,48 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var columnheaderRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-sort': null + }, + relatedConcepts: [{ + concept: { + name: 'th' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + name: 'scope', + value: 'col' + }], + name: 'th' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + name: 'scope', + value: 'colgroup' + }], + name: 'th' + }, + module: 'HTML' + }], + requireContextRole: ['row'], + requiredContextRole: ['row'], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'cell'], ['roletype', 'structure', 'section', 'cell', 'gridcell'], ['roletype', 'widget', 'gridcell'], ['roletype', 'structure', 'sectionhead']] +}; +var _default = columnheaderRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/comboboxRole.js b/node_modules/aria-query/lib/etc/roles/literal/comboboxRole.js new file mode 100644 index 0000000000000000000000000000000000000000..2540905229e0742aeea70e8c01b134ad10fc92b5 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/comboboxRole.js @@ -0,0 +1,125 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var comboboxRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-activedescendant': null, + 'aria-autocomplete': null, + 'aria-errormessage': null, + 'aria-invalid': null, + 'aria-readonly': null, + 'aria-required': null, + 'aria-expanded': 'false', + 'aria-haspopup': 'listbox' + }, + relatedConcepts: [{ + concept: { + attributes: [{ + constraints: ['set'], + name: 'list' + }, { + name: 'type', + value: 'email' + }], + name: 'input' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + constraints: ['set'], + name: 'list' + }, { + name: 'type', + value: 'search' + }], + name: 'input' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + constraints: ['set'], + name: 'list' + }, { + name: 'type', + value: 'tel' + }], + name: 'input' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + constraints: ['set'], + name: 'list' + }, { + name: 'type', + value: 'text' + }], + name: 'input' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + constraints: ['set'], + name: 'list' + }, { + name: 'type', + value: 'url' + }], + name: 'input' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + constraints: ['set'], + name: 'list' + }, { + name: 'type', + value: 'url' + }], + name: 'input' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + constraints: ['undefined'], + name: 'multiple' + }, { + constraints: ['undefined'], + name: 'size' + }], + constraints: ['the multiple attribute is not set and the size attribute does not have a value greater than 1'], + name: 'select' + }, + module: 'HTML' + }, { + concept: { + name: 'select' + }, + module: 'XForms' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: { + 'aria-controls': null, + 'aria-expanded': 'false' + }, + superClass: [['roletype', 'widget', 'input']] +}; +var _default = comboboxRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/complementaryRole.js b/node_modules/aria-query/lib/etc/roles/literal/complementaryRole.js new file mode 100644 index 0000000000000000000000000000000000000000..4124e25d3a10c03ffa505f7599781c0bdf07d175 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/complementaryRole.js @@ -0,0 +1,48 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var complementaryRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'aside' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + constraints: ['set'], + name: 'aria-label' + }], + constraints: ['scoped to a sectioning content element', 'scoped to a sectioning root element other than body'], + name: 'aside' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + constraints: ['set'], + name: 'aria-labelledby' + }], + constraints: ['scoped to a sectioning content element', 'scoped to a sectioning root element other than body'], + name: 'aside' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = complementaryRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/contentinfoRole.js b/node_modules/aria-query/lib/etc/roles/literal/contentinfoRole.js new file mode 100644 index 0000000000000000000000000000000000000000..babcd925b7e40622791f6dc2018e689f501ba83f --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/contentinfoRole.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var contentinfoRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + constraints: ['scoped to the body element'], + name: 'footer' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = contentinfoRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/definitionRole.js b/node_modules/aria-query/lib/etc/roles/literal/definitionRole.js new file mode 100644 index 0000000000000000000000000000000000000000..9165ccb2803b69a3cbfbfbc469f9f5706e8d4724 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/definitionRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var definitionRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'dd' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = definitionRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/deletionRole.js b/node_modules/aria-query/lib/etc/roles/literal/deletionRole.js new file mode 100644 index 0000000000000000000000000000000000000000..6343e1b0d54ab97f07524c940169f0c0acb37fd8 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/deletionRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var deletionRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['prohibited'], + prohibitedProps: ['aria-label', 'aria-labelledby'], + props: {}, + relatedConcepts: [{ + concept: { + name: 'del' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = deletionRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/dialogRole.js b/node_modules/aria-query/lib/etc/roles/literal/dialogRole.js new file mode 100644 index 0000000000000000000000000000000000000000..c9391d9a7c51b63456b814fe227f890d7cf4afa1 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/dialogRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var dialogRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'dialog' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'window']] +}; +var _default = dialogRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/directoryRole.js b/node_modules/aria-query/lib/etc/roles/literal/directoryRole.js new file mode 100644 index 0000000000000000000000000000000000000000..061f8dafa5019c91b9eb219b6e9d1c2218c5d9c1 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/directoryRole.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var directoryRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + module: 'DAISY Guide' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'list']] +}; +var _default = directoryRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/documentRole.js b/node_modules/aria-query/lib/etc/roles/literal/documentRole.js new file mode 100644 index 0000000000000000000000000000000000000000..6602a417e2be22e78a4cace62e68a1562111b214 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/documentRole.js @@ -0,0 +1,32 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var documentRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'Device Independence Delivery Unit' + } + }, { + concept: { + name: 'html' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure']] +}; +var _default = documentRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/emphasisRole.js b/node_modules/aria-query/lib/etc/roles/literal/emphasisRole.js new file mode 100644 index 0000000000000000000000000000000000000000..08d8f9d12d53232f7865ab0c57814df7939e84ab --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/emphasisRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var emphasisRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['prohibited'], + prohibitedProps: ['aria-label', 'aria-labelledby'], + props: {}, + relatedConcepts: [{ + concept: { + name: 'em' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = emphasisRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/feedRole.js b/node_modules/aria-query/lib/etc/roles/literal/feedRole.js new file mode 100644 index 0000000000000000000000000000000000000000..7cec9c5d9a13620383aacab6cc60fd0111ce0749 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/feedRole.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var feedRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [['article']], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'list']] +}; +var _default = feedRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/figureRole.js b/node_modules/aria-query/lib/etc/roles/literal/figureRole.js new file mode 100644 index 0000000000000000000000000000000000000000..75ec37500c6d06a9b6c1714f6bbfab026750fdb2 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/figureRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var figureRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'figure' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = figureRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/formRole.js b/node_modules/aria-query/lib/etc/roles/literal/formRole.js new file mode 100644 index 0000000000000000000000000000000000000000..76d0ff4fed1b8af406f38fc3a1abe017ea44f12a --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/formRole.js @@ -0,0 +1,50 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var formRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + attributes: [{ + constraints: ['set'], + name: 'aria-label' + }], + name: 'form' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + constraints: ['set'], + name: 'aria-labelledby' + }], + name: 'form' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + constraints: ['set'], + name: 'name' + }], + name: 'form' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = formRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/genericRole.js b/node_modules/aria-query/lib/etc/roles/literal/genericRole.js new file mode 100644 index 0000000000000000000000000000000000000000..ca9997df333956830daf41b32de2be405a4d915c --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/genericRole.js @@ -0,0 +1,120 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var genericRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['prohibited'], + prohibitedProps: ['aria-label', 'aria-labelledby'], + props: {}, + relatedConcepts: [{ + concept: { + name: 'a' + }, + module: 'HTML' + }, { + concept: { + name: 'area' + }, + module: 'HTML' + }, { + concept: { + name: 'aside' + }, + module: 'HTML' + }, { + concept: { + name: 'b' + }, + module: 'HTML' + }, { + concept: { + name: 'bdo' + }, + module: 'HTML' + }, { + concept: { + name: 'body' + }, + module: 'HTML' + }, { + concept: { + name: 'data' + }, + module: 'HTML' + }, { + concept: { + name: 'div' + }, + module: 'HTML' + }, { + concept: { + constraints: ['scoped to the main element', 'scoped to a sectioning content element', 'scoped to a sectioning root element other than body'], + name: 'footer' + }, + module: 'HTML' + }, { + concept: { + constraints: ['scoped to the main element', 'scoped to a sectioning content element', 'scoped to a sectioning root element other than body'], + name: 'header' + }, + module: 'HTML' + }, { + concept: { + name: 'hgroup' + }, + module: 'HTML' + }, { + concept: { + name: 'i' + }, + module: 'HTML' + }, { + concept: { + name: 'pre' + }, + module: 'HTML' + }, { + concept: { + name: 'q' + }, + module: 'HTML' + }, { + concept: { + name: 'samp' + }, + module: 'HTML' + }, { + concept: { + name: 'section' + }, + module: 'HTML' + }, { + concept: { + name: 'small' + }, + module: 'HTML' + }, { + concept: { + name: 'span' + }, + module: 'HTML' + }, { + concept: { + name: 'u' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure']] +}; +var _default = genericRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/graphicsDocumentRole.js b/node_modules/aria-query/lib/etc/roles/literal/graphicsDocumentRole.js new file mode 100644 index 0000000000000000000000000000000000000000..a115606102b5defd00c22c68b8190e08dbbf9e1b --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/graphicsDocumentRole.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var graphicsDocumentRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + module: 'GRAPHICS', + concept: { + name: 'graphics-object' + } + }, { + module: 'ARIA', + concept: { + name: 'img' + } + }, { + module: 'ARIA', + concept: { + name: 'article' + } + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'document']] +}; +var _default = graphicsDocumentRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/graphicsObjectRole.js b/node_modules/aria-query/lib/etc/roles/literal/graphicsObjectRole.js new file mode 100644 index 0000000000000000000000000000000000000000..2d24a09f8ff44fac2d259c440bc61b956ce11e37 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/graphicsObjectRole.js @@ -0,0 +1,48 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var graphicsObjectRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [{ + module: 'GRAPHICS', + concept: { + name: 'graphics-document' + } + }, { + module: 'ARIA', + concept: { + name: 'group' + } + }, { + module: 'ARIA', + concept: { + name: 'img' + } + }, { + module: 'GRAPHICS', + concept: { + name: 'graphics-symbol' + } + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'group']] +}; +var _default = graphicsObjectRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/graphicsSymbolRole.js b/node_modules/aria-query/lib/etc/roles/literal/graphicsSymbolRole.js new file mode 100644 index 0000000000000000000000000000000000000000..79d02b68942ea30983e7fc3819c2e8932659de66 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/graphicsSymbolRole.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var graphicsSymbolRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: true, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null + }, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'img']] +}; +var _default = graphicsSymbolRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/gridRole.js b/node_modules/aria-query/lib/etc/roles/literal/gridRole.js new file mode 100644 index 0000000000000000000000000000000000000000..0a35cd5955af9fac23dd999136e334c11f2f4b6b --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/gridRole.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var gridRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-multiselectable': null, + 'aria-readonly': null + }, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [['row'], ['row', 'rowgroup']], + requiredProps: {}, + superClass: [['roletype', 'widget', 'composite'], ['roletype', 'structure', 'section', 'table']] +}; +var _default = gridRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/gridcellRole.js b/node_modules/aria-query/lib/etc/roles/literal/gridcellRole.js new file mode 100644 index 0000000000000000000000000000000000000000..a4dea3c52d64b4c13aad78ee8d107f0717b5c3fc --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/gridcellRole.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var gridcellRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-invalid': null, + 'aria-readonly': null, + 'aria-required': null, + 'aria-selected': null + }, + relatedConcepts: [{ + concept: { + constraints: ['ancestor table element has grid role', 'ancestor table element has treegrid role'], + name: 'td' + }, + module: 'HTML' + }], + requireContextRole: ['row'], + requiredContextRole: ['row'], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'cell'], ['roletype', 'widget']] +}; +var _default = gridcellRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/groupRole.js b/node_modules/aria-query/lib/etc/roles/literal/groupRole.js new file mode 100644 index 0000000000000000000000000000000000000000..08b137ce480bed57c5933691bfa8b49727c3b471 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/groupRole.js @@ -0,0 +1,46 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var groupRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-activedescendant': null, + 'aria-disabled': null + }, + relatedConcepts: [{ + concept: { + name: 'details' + }, + module: 'HTML' + }, { + concept: { + name: 'fieldset' + }, + module: 'HTML' + }, { + concept: { + name: 'optgroup' + }, + module: 'HTML' + }, { + concept: { + name: 'address' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = groupRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/headingRole.js b/node_modules/aria-query/lib/etc/roles/literal/headingRole.js new file mode 100644 index 0000000000000000000000000000000000000000..9c53a4d10f9bbbaf4ba73618c3f198eb325126e0 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/headingRole.js @@ -0,0 +1,57 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var headingRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-level': '2' + }, + relatedConcepts: [{ + concept: { + name: 'h1' + }, + module: 'HTML' + }, { + concept: { + name: 'h2' + }, + module: 'HTML' + }, { + concept: { + name: 'h3' + }, + module: 'HTML' + }, { + concept: { + name: 'h4' + }, + module: 'HTML' + }, { + concept: { + name: 'h5' + }, + module: 'HTML' + }, { + concept: { + name: 'h6' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: { + 'aria-level': '2' + }, + superClass: [['roletype', 'structure', 'sectionhead']] +}; +var _default = headingRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/imgRole.js b/node_modules/aria-query/lib/etc/roles/literal/imgRole.js new file mode 100644 index 0000000000000000000000000000000000000000..6dcebd7c52fe8c0e51b887304f696f2d4f8b1d21 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/imgRole.js @@ -0,0 +1,46 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var imgRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: true, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + attributes: [{ + constraints: ['set'], + name: 'alt' + }], + name: 'img' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + constraints: ['undefined'], + name: 'alt' + }], + name: 'img' + }, + module: 'HTML' + }, { + concept: { + name: 'imggroup' + }, + module: 'DTB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = imgRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/insertionRole.js b/node_modules/aria-query/lib/etc/roles/literal/insertionRole.js new file mode 100644 index 0000000000000000000000000000000000000000..a0059a6e4a294f7498364c9eddf2ae15cd75c544 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/insertionRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var insertionRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['prohibited'], + prohibitedProps: ['aria-label', 'aria-labelledby'], + props: {}, + relatedConcepts: [{ + concept: { + name: 'ins' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = insertionRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/linkRole.js b/node_modules/aria-query/lib/etc/roles/literal/linkRole.js new file mode 100644 index 0000000000000000000000000000000000000000..52a06b53398d6c58d3d68c336e33a60b59f8641c --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/linkRole.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var linkRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-expanded': null, + 'aria-haspopup': null + }, + relatedConcepts: [{ + concept: { + attributes: [{ + constraints: ['set'], + name: 'href' + }], + name: 'a' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + constraints: ['set'], + name: 'href' + }], + name: 'area' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'widget', 'command']] +}; +var _default = linkRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/listRole.js b/node_modules/aria-query/lib/etc/roles/literal/listRole.js new file mode 100644 index 0000000000000000000000000000000000000000..0ac17d25b6a4c4f2a71eb2d5a50abbea2e0e75e6 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/listRole.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var listRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'menu' + }, + module: 'HTML' + }, { + concept: { + name: 'ol' + }, + module: 'HTML' + }, { + concept: { + name: 'ul' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [['listitem']], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = listRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/listboxRole.js b/node_modules/aria-query/lib/etc/roles/literal/listboxRole.js new file mode 100644 index 0000000000000000000000000000000000000000..372a653bcf78a4efb898dfc4eddac1d67d39c08a --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/listboxRole.js @@ -0,0 +1,64 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var listboxRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-errormessage': null, + 'aria-expanded': null, + 'aria-invalid': null, + 'aria-multiselectable': null, + 'aria-readonly': null, + 'aria-required': null, + 'aria-orientation': 'vertical' + }, + relatedConcepts: [{ + concept: { + attributes: [{ + constraints: ['>1'], + name: 'size' + }], + constraints: ['the size attribute value is greater than 1'], + name: 'select' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + name: 'multiple' + }], + name: 'select' + }, + module: 'HTML' + }, { + concept: { + name: 'datalist' + }, + module: 'HTML' + }, { + concept: { + name: 'list' + }, + module: 'ARIA' + }, { + concept: { + name: 'select' + }, + module: 'XForms' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [['option', 'group'], ['option']], + requiredProps: {}, + superClass: [['roletype', 'widget', 'composite', 'select'], ['roletype', 'structure', 'section', 'group', 'select']] +}; +var _default = listboxRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/listitemRole.js b/node_modules/aria-query/lib/etc/roles/literal/listitemRole.js new file mode 100644 index 0000000000000000000000000000000000000000..e50ab1d2c28588eb09d554fe1aa7dbaf40dcd3fd --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/listitemRole.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var listitemRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-level': null, + 'aria-posinset': null, + 'aria-setsize': null + }, + relatedConcepts: [{ + concept: { + constraints: ['direct descendant of ol', 'direct descendant of ul', 'direct descendant of menu'], + name: 'li' + }, + module: 'HTML' + }, { + concept: { + name: 'item' + }, + module: 'XForms' + }], + requireContextRole: ['directory', 'list'], + requiredContextRole: ['directory', 'list'], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = listitemRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/logRole.js b/node_modules/aria-query/lib/etc/roles/literal/logRole.js new file mode 100644 index 0000000000000000000000000000000000000000..c1b8f82b92ead72561ce428a64ddb14b631439cc --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/logRole.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var logRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-live': 'polite' + }, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = logRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/mainRole.js b/node_modules/aria-query/lib/etc/roles/literal/mainRole.js new file mode 100644 index 0000000000000000000000000000000000000000..9349503ea0223a187e4b028b7eb089e980e0964f --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/mainRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var mainRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'main' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = mainRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/markRole.js b/node_modules/aria-query/lib/etc/roles/literal/markRole.js new file mode 100644 index 0000000000000000000000000000000000000000..9b00e7220b9a32d7195b97e8b2415691af23f7fe --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/markRole.js @@ -0,0 +1,32 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var markRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['prohibited'], + prohibitedProps: [], + props: { + 'aria-braillelabel': null, + 'aria-brailleroledescription': null, + 'aria-description': null + }, + relatedConcepts: [{ + concept: { + name: 'mark' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = markRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/marqueeRole.js b/node_modules/aria-query/lib/etc/roles/literal/marqueeRole.js new file mode 100644 index 0000000000000000000000000000000000000000..228c8e2562cdbaf78daf8a5eb6e59fa580ef6948 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/marqueeRole.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var marqueeRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = marqueeRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/mathRole.js b/node_modules/aria-query/lib/etc/roles/literal/mathRole.js new file mode 100644 index 0000000000000000000000000000000000000000..bee382d1bad530d6649ebafcc75bccca7ceeea4a --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/mathRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var mathRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'math' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = mathRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/menuRole.js b/node_modules/aria-query/lib/etc/roles/literal/menuRole.js new file mode 100644 index 0000000000000000000000000000000000000000..f69e87b0bee70f9eba54308b21653c6abe2949e4 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/menuRole.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var menuRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-orientation': 'vertical' + }, + relatedConcepts: [{ + concept: { + name: 'MENU' + }, + module: 'JAPI' + }, { + concept: { + name: 'list' + }, + module: 'ARIA' + }, { + concept: { + name: 'select' + }, + module: 'XForms' + }, { + concept: { + name: 'sidebar' + }, + module: 'DTB' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [['menuitem', 'group'], ['menuitemradio', 'group'], ['menuitemcheckbox', 'group'], ['menuitem'], ['menuitemcheckbox'], ['menuitemradio']], + requiredProps: {}, + superClass: [['roletype', 'widget', 'composite', 'select'], ['roletype', 'structure', 'section', 'group', 'select']] +}; +var _default = menuRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/menubarRole.js b/node_modules/aria-query/lib/etc/roles/literal/menubarRole.js new file mode 100644 index 0000000000000000000000000000000000000000..3c3d4d8d5edc23646c4aa4e291d30f377e1a2c80 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/menubarRole.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var menubarRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-orientation': 'horizontal' + }, + relatedConcepts: [{ + concept: { + name: 'toolbar' + }, + module: 'ARIA' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [['menuitem', 'group'], ['menuitemradio', 'group'], ['menuitemcheckbox', 'group'], ['menuitem'], ['menuitemcheckbox'], ['menuitemradio']], + requiredProps: {}, + superClass: [['roletype', 'widget', 'composite', 'select', 'menu'], ['roletype', 'structure', 'section', 'group', 'select', 'menu']] +}; +var _default = menubarRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/menuitemRole.js b/node_modules/aria-query/lib/etc/roles/literal/menuitemRole.js new file mode 100644 index 0000000000000000000000000000000000000000..17efd172ca893865ad021f05d5076938a8685348 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/menuitemRole.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var menuitemRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-posinset': null, + 'aria-setsize': null + }, + relatedConcepts: [{ + concept: { + name: 'MENU_ITEM' + }, + module: 'JAPI' + }, { + concept: { + name: 'listitem' + }, + module: 'ARIA' + }, { + concept: { + name: 'option' + }, + module: 'ARIA' + }], + requireContextRole: ['group', 'menu', 'menubar'], + requiredContextRole: ['group', 'menu', 'menubar'], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'widget', 'command']] +}; +var _default = menuitemRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/menuitemcheckboxRole.js b/node_modules/aria-query/lib/etc/roles/literal/menuitemcheckboxRole.js new file mode 100644 index 0000000000000000000000000000000000000000..326bfb9da51465b6a05b1d3d0209d2e15987d20b --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/menuitemcheckboxRole.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var menuitemcheckboxRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: true, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'menuitem' + }, + module: 'ARIA' + }], + requireContextRole: ['group', 'menu', 'menubar'], + requiredContextRole: ['group', 'menu', 'menubar'], + requiredOwnedElements: [], + requiredProps: { + 'aria-checked': null + }, + superClass: [['roletype', 'widget', 'input', 'checkbox'], ['roletype', 'widget', 'command', 'menuitem']] +}; +var _default = menuitemcheckboxRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/menuitemradioRole.js b/node_modules/aria-query/lib/etc/roles/literal/menuitemradioRole.js new file mode 100644 index 0000000000000000000000000000000000000000..30546c28900aafc5766c9cf012ada4ecceac6943 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/menuitemradioRole.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var menuitemradioRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: true, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'menuitem' + }, + module: 'ARIA' + }], + requireContextRole: ['group', 'menu', 'menubar'], + requiredContextRole: ['group', 'menu', 'menubar'], + requiredOwnedElements: [], + requiredProps: { + 'aria-checked': null + }, + superClass: [['roletype', 'widget', 'input', 'checkbox', 'menuitemcheckbox'], ['roletype', 'widget', 'command', 'menuitem', 'menuitemcheckbox'], ['roletype', 'widget', 'input', 'radio']] +}; +var _default = menuitemradioRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/meterRole.js b/node_modules/aria-query/lib/etc/roles/literal/meterRole.js new file mode 100644 index 0000000000000000000000000000000000000000..baddbbaf564caeb514d7f8bd38649a0425d27015 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/meterRole.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var meterRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: true, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-valuetext': null, + 'aria-valuemax': '100', + 'aria-valuemin': '0' + }, + relatedConcepts: [{ + concept: { + name: 'meter' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: { + 'aria-valuenow': null + }, + superClass: [['roletype', 'structure', 'range']] +}; +var _default = meterRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/navigationRole.js b/node_modules/aria-query/lib/etc/roles/literal/navigationRole.js new file mode 100644 index 0000000000000000000000000000000000000000..d1c1761094105c47f06a23d71467d306adf35eeb --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/navigationRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var navigationRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'nav' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = navigationRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/noneRole.js b/node_modules/aria-query/lib/etc/roles/literal/noneRole.js new file mode 100644 index 0000000000000000000000000000000000000000..735e4860880851e10f4fcf8760bb7579fa4fa965 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/noneRole.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var noneRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: [], + prohibitedProps: [], + props: {}, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [] +}; +var _default = noneRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/noteRole.js b/node_modules/aria-query/lib/etc/roles/literal/noteRole.js new file mode 100644 index 0000000000000000000000000000000000000000..bff25906b01c711cd62c08943f688042ad62feac --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/noteRole.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var noteRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = noteRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/optionRole.js b/node_modules/aria-query/lib/etc/roles/literal/optionRole.js new file mode 100644 index 0000000000000000000000000000000000000000..47453253cf1214bd523a8f935b0822131a2ee1b8 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/optionRole.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var optionRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: true, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-checked': null, + 'aria-posinset': null, + 'aria-setsize': null, + 'aria-selected': 'false' + }, + relatedConcepts: [{ + concept: { + name: 'item' + }, + module: 'XForms' + }, { + concept: { + name: 'listitem' + }, + module: 'ARIA' + }, { + concept: { + name: 'option' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: { + 'aria-selected': 'false' + }, + superClass: [['roletype', 'widget', 'input']] +}; +var _default = optionRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/paragraphRole.js b/node_modules/aria-query/lib/etc/roles/literal/paragraphRole.js new file mode 100644 index 0000000000000000000000000000000000000000..501b88b91f2ebaea2db4977817e1a3db2c7c5fc3 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/paragraphRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var paragraphRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['prohibited'], + prohibitedProps: ['aria-label', 'aria-labelledby'], + props: {}, + relatedConcepts: [{ + concept: { + name: 'p' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = paragraphRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/presentationRole.js b/node_modules/aria-query/lib/etc/roles/literal/presentationRole.js new file mode 100644 index 0000000000000000000000000000000000000000..06def2c120b9988299c78f1dff905661d5d0ac5b --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/presentationRole.js @@ -0,0 +1,32 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var presentationRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['prohibited'], + prohibitedProps: ['aria-label', 'aria-labelledby'], + props: {}, + relatedConcepts: [{ + concept: { + attributes: [{ + name: 'alt', + value: '' + }], + name: 'img' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure']] +}; +var _default = presentationRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/progressbarRole.js b/node_modules/aria-query/lib/etc/roles/literal/progressbarRole.js new file mode 100644 index 0000000000000000000000000000000000000000..b5e5f702b1db8e0fe8712060d7f703e1859ae724 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/progressbarRole.js @@ -0,0 +1,35 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var progressbarRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: true, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-valuetext': null + }, + relatedConcepts: [{ + concept: { + name: 'progress' + }, + module: 'HTML' + }, { + concept: { + name: 'status' + }, + module: 'ARIA' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'range'], ['roletype', 'widget']] +}; +var _default = progressbarRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/radioRole.js b/node_modules/aria-query/lib/etc/roles/literal/radioRole.js new file mode 100644 index 0000000000000000000000000000000000000000..8dc4843398350cd82a20a1f04956fa9bbf7bdb2f --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/radioRole.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var radioRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: true, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-checked': null, + 'aria-posinset': null, + 'aria-setsize': null + }, + relatedConcepts: [{ + concept: { + attributes: [{ + name: 'type', + value: 'radio' + }], + name: 'input' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: { + 'aria-checked': null + }, + superClass: [['roletype', 'widget', 'input']] +}; +var _default = radioRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/radiogroupRole.js b/node_modules/aria-query/lib/etc/roles/literal/radiogroupRole.js new file mode 100644 index 0000000000000000000000000000000000000000..cc2d17875a202be3605d48dbe162a34d7acf9c15 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/radiogroupRole.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var radiogroupRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-errormessage': null, + 'aria-invalid': null, + 'aria-readonly': null, + 'aria-required': null + }, + relatedConcepts: [{ + concept: { + name: 'list' + }, + module: 'ARIA' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [['radio']], + requiredProps: {}, + superClass: [['roletype', 'widget', 'composite', 'select'], ['roletype', 'structure', 'section', 'group', 'select']] +}; +var _default = radiogroupRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/regionRole.js b/node_modules/aria-query/lib/etc/roles/literal/regionRole.js new file mode 100644 index 0000000000000000000000000000000000000000..94d6ed4d0999ef41909e5e442bdfcf68aab4b2f2 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/regionRole.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var regionRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + attributes: [{ + constraints: ['set'], + name: 'aria-label' + }], + name: 'section' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + constraints: ['set'], + name: 'aria-labelledby' + }], + name: 'section' + }, + module: 'HTML' + }, { + concept: { + name: 'Device Independence Glossart perceivable unit' + } + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = regionRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/rowRole.js b/node_modules/aria-query/lib/etc/roles/literal/rowRole.js new file mode 100644 index 0000000000000000000000000000000000000000..57be030e6eeb4ef8b07117edd628aeb69990c409 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/rowRole.js @@ -0,0 +1,36 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var rowRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-colindex': null, + 'aria-expanded': null, + 'aria-level': null, + 'aria-posinset': null, + 'aria-rowindex': null, + 'aria-selected': null, + 'aria-setsize': null + }, + relatedConcepts: [{ + concept: { + name: 'tr' + }, + module: 'HTML' + }], + requireContextRole: ['grid', 'rowgroup', 'table', 'treegrid'], + requiredContextRole: ['grid', 'rowgroup', 'table', 'treegrid'], + requiredOwnedElements: [['cell'], ['columnheader'], ['gridcell'], ['rowheader']], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'group'], ['roletype', 'widget']] +}; +var _default = rowRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/rowgroupRole.js b/node_modules/aria-query/lib/etc/roles/literal/rowgroupRole.js new file mode 100644 index 0000000000000000000000000000000000000000..ef9c998ccd78d5ecc2c8788c8cadca54585f406a --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/rowgroupRole.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var rowgroupRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'tbody' + }, + module: 'HTML' + }, { + concept: { + name: 'tfoot' + }, + module: 'HTML' + }, { + concept: { + name: 'thead' + }, + module: 'HTML' + }], + requireContextRole: ['grid', 'table', 'treegrid'], + requiredContextRole: ['grid', 'table', 'treegrid'], + requiredOwnedElements: [['row']], + requiredProps: {}, + superClass: [['roletype', 'structure']] +}; +var _default = rowgroupRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/rowheaderRole.js b/node_modules/aria-query/lib/etc/roles/literal/rowheaderRole.js new file mode 100644 index 0000000000000000000000000000000000000000..c8b230b77600879b341761691129d44fc7ba0955 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/rowheaderRole.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var rowheaderRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-sort': null + }, + relatedConcepts: [{ + concept: { + attributes: [{ + name: 'scope', + value: 'row' + }], + name: 'th' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + name: 'scope', + value: 'rowgroup' + }], + name: 'th' + }, + module: 'HTML' + }], + requireContextRole: ['row', 'rowgroup'], + requiredContextRole: ['row', 'rowgroup'], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'cell'], ['roletype', 'structure', 'section', 'cell', 'gridcell'], ['roletype', 'widget', 'gridcell'], ['roletype', 'structure', 'sectionhead']] +}; +var _default = rowheaderRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/scrollbarRole.js b/node_modules/aria-query/lib/etc/roles/literal/scrollbarRole.js new file mode 100644 index 0000000000000000000000000000000000000000..dcd928fa97470482a6e8a248fefd0e5d6c3733bb --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/scrollbarRole.js @@ -0,0 +1,32 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var scrollbarRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: true, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-valuetext': null, + 'aria-orientation': 'vertical', + 'aria-valuemax': '100', + 'aria-valuemin': '0' + }, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: { + 'aria-controls': null, + 'aria-valuenow': null + }, + superClass: [['roletype', 'structure', 'range'], ['roletype', 'widget']] +}; +var _default = scrollbarRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/searchRole.js b/node_modules/aria-query/lib/etc/roles/literal/searchRole.js new file mode 100644 index 0000000000000000000000000000000000000000..0c054a8670bf25f28542b66b69b2e3d9a6396b7f --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/searchRole.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var searchRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'landmark']] +}; +var _default = searchRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/searchboxRole.js b/node_modules/aria-query/lib/etc/roles/literal/searchboxRole.js new file mode 100644 index 0000000000000000000000000000000000000000..0ab1d0c23a1e2067fd96b3bfc4b2ad3db75083b0 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/searchboxRole.js @@ -0,0 +1,36 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var searchboxRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + attributes: [{ + constraints: ['undefined'], + name: 'list' + }, { + name: 'type', + value: 'search' + }], + constraints: ['the list attribute is not set'], + name: 'input' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'widget', 'input', 'textbox']] +}; +var _default = searchboxRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/separatorRole.js b/node_modules/aria-query/lib/etc/roles/literal/separatorRole.js new file mode 100644 index 0000000000000000000000000000000000000000..a1ed892665da906fdc036f8b598f8b69a5a6728d --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/separatorRole.js @@ -0,0 +1,35 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var separatorRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: true, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-orientation': 'horizontal', + 'aria-valuemax': '100', + 'aria-valuemin': '0', + 'aria-valuenow': null, + 'aria-valuetext': null + }, + relatedConcepts: [{ + concept: { + name: 'hr' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure']] +}; +var _default = separatorRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/sliderRole.js b/node_modules/aria-query/lib/etc/roles/literal/sliderRole.js new file mode 100644 index 0000000000000000000000000000000000000000..f2c9e0a1b19fc793dc30389784650f22bfaddddb --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/sliderRole.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var sliderRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: true, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-errormessage': null, + 'aria-haspopup': null, + 'aria-invalid': null, + 'aria-readonly': null, + 'aria-valuetext': null, + 'aria-orientation': 'horizontal', + 'aria-valuemax': '100', + 'aria-valuemin': '0' + }, + relatedConcepts: [{ + concept: { + attributes: [{ + name: 'type', + value: 'range' + }], + name: 'input' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: { + 'aria-valuenow': null + }, + superClass: [['roletype', 'widget', 'input'], ['roletype', 'structure', 'range']] +}; +var _default = sliderRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/spinbuttonRole.js b/node_modules/aria-query/lib/etc/roles/literal/spinbuttonRole.js new file mode 100644 index 0000000000000000000000000000000000000000..838423c80abc75d30140bae8f917df1f8708fc41 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/spinbuttonRole.js @@ -0,0 +1,39 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var spinbuttonRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-errormessage': null, + 'aria-invalid': null, + 'aria-readonly': null, + 'aria-required': null, + 'aria-valuetext': null, + 'aria-valuenow': '0' + }, + relatedConcepts: [{ + concept: { + attributes: [{ + name: 'type', + value: 'number' + }], + name: 'input' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'widget', 'composite'], ['roletype', 'widget', 'input'], ['roletype', 'structure', 'range']] +}; +var _default = spinbuttonRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/statusRole.js b/node_modules/aria-query/lib/etc/roles/literal/statusRole.js new file mode 100644 index 0000000000000000000000000000000000000000..b2bdbe8e6f340d7574a9e668ce4be2dc4e27e922 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/statusRole.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var statusRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-atomic': 'true', + 'aria-live': 'polite' + }, + relatedConcepts: [{ + concept: { + name: 'output' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = statusRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/strongRole.js b/node_modules/aria-query/lib/etc/roles/literal/strongRole.js new file mode 100644 index 0000000000000000000000000000000000000000..31660787dacaf70c4e4dc9871e445c6b43755f0a --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/strongRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var strongRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['prohibited'], + prohibitedProps: ['aria-label', 'aria-labelledby'], + props: {}, + relatedConcepts: [{ + concept: { + name: 'strong' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = strongRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/subscriptRole.js b/node_modules/aria-query/lib/etc/roles/literal/subscriptRole.js new file mode 100644 index 0000000000000000000000000000000000000000..73a64a0860afb1e5f8718788421647f7b941f1f2 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/subscriptRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var subscriptRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['prohibited'], + prohibitedProps: ['aria-label', 'aria-labelledby'], + props: {}, + relatedConcepts: [{ + concept: { + name: 'sub' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = subscriptRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/superscriptRole.js b/node_modules/aria-query/lib/etc/roles/literal/superscriptRole.js new file mode 100644 index 0000000000000000000000000000000000000000..97bfe7d983eacb1cd881fac8a37e9a4fcbb72828 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/superscriptRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var superscriptRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['prohibited'], + prohibitedProps: ['aria-label', 'aria-labelledby'], + props: {}, + relatedConcepts: [{ + concept: { + name: 'sup' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = superscriptRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/switchRole.js b/node_modules/aria-query/lib/etc/roles/literal/switchRole.js new file mode 100644 index 0000000000000000000000000000000000000000..4e54c8ffb8aef76c2161ac700ecad3c0f4b5a28a --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/switchRole.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var switchRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: true, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'button' + }, + module: 'ARIA' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: { + 'aria-checked': null + }, + superClass: [['roletype', 'widget', 'input', 'checkbox']] +}; +var _default = switchRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/tabRole.js b/node_modules/aria-query/lib/etc/roles/literal/tabRole.js new file mode 100644 index 0000000000000000000000000000000000000000..ebf013eb85fa86606c1a678bf59e1f8cc84f692a --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/tabRole.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var tabRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: true, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-disabled': null, + 'aria-expanded': null, + 'aria-haspopup': null, + 'aria-posinset': null, + 'aria-setsize': null, + 'aria-selected': 'false' + }, + relatedConcepts: [], + requireContextRole: ['tablist'], + requiredContextRole: ['tablist'], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'sectionhead'], ['roletype', 'widget']] +}; +var _default = tabRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/tableRole.js b/node_modules/aria-query/lib/etc/roles/literal/tableRole.js new file mode 100644 index 0000000000000000000000000000000000000000..f12f12769351f09948f8d5f2ea7e5031f6c7a3d4 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/tableRole.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var tableRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-colcount': null, + 'aria-rowcount': null + }, + relatedConcepts: [{ + concept: { + name: 'table' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [['row'], ['row', 'rowgroup']], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = tableRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/tablistRole.js b/node_modules/aria-query/lib/etc/roles/literal/tablistRole.js new file mode 100644 index 0000000000000000000000000000000000000000..7ef083cdeb2083ae929b2e908895eaceba1b7c9e --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/tablistRole.js @@ -0,0 +1,32 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var tablistRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-level': null, + 'aria-multiselectable': null, + 'aria-orientation': 'horizontal' + }, + relatedConcepts: [{ + module: 'DAISY', + concept: { + name: 'guide' + } + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [['tab']], + requiredProps: {}, + superClass: [['roletype', 'widget', 'composite']] +}; +var _default = tablistRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/tabpanelRole.js b/node_modules/aria-query/lib/etc/roles/literal/tabpanelRole.js new file mode 100644 index 0000000000000000000000000000000000000000..c75a9283a0016d0179aadd3ab635b7b157154a97 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/tabpanelRole.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var tabpanelRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = tabpanelRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/termRole.js b/node_modules/aria-query/lib/etc/roles/literal/termRole.js new file mode 100644 index 0000000000000000000000000000000000000000..1ea3b913a850270958cf7255844649e46ffec488 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/termRole.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var termRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'dfn' + }, + module: 'HTML' + }, { + concept: { + name: 'dt' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = termRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/textboxRole.js b/node_modules/aria-query/lib/etc/roles/literal/textboxRole.js new file mode 100644 index 0000000000000000000000000000000000000000..ef2d769a1795cdd3d802b38b40fbf7bcb225f605 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/textboxRole.js @@ -0,0 +1,108 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var textboxRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-activedescendant': null, + 'aria-autocomplete': null, + 'aria-errormessage': null, + 'aria-haspopup': null, + 'aria-invalid': null, + 'aria-multiline': null, + 'aria-placeholder': null, + 'aria-readonly': null, + 'aria-required': null + }, + relatedConcepts: [{ + concept: { + attributes: [{ + constraints: ['undefined'], + name: 'type' + }, { + constraints: ['undefined'], + name: 'list' + }], + constraints: ['the list attribute is not set'], + name: 'input' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + constraints: ['undefined'], + name: 'list' + }, { + name: 'type', + value: 'email' + }], + constraints: ['the list attribute is not set'], + name: 'input' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + constraints: ['undefined'], + name: 'list' + }, { + name: 'type', + value: 'tel' + }], + constraints: ['the list attribute is not set'], + name: 'input' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + constraints: ['undefined'], + name: 'list' + }, { + name: 'type', + value: 'text' + }], + constraints: ['the list attribute is not set'], + name: 'input' + }, + module: 'HTML' + }, { + concept: { + attributes: [{ + constraints: ['undefined'], + name: 'list' + }, { + name: 'type', + value: 'url' + }], + constraints: ['the list attribute is not set'], + name: 'input' + }, + module: 'HTML' + }, { + concept: { + name: 'input' + }, + module: 'XForms' + }, { + concept: { + name: 'textarea' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'widget', 'input']] +}; +var _default = textboxRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/timeRole.js b/node_modules/aria-query/lib/etc/roles/literal/timeRole.js new file mode 100644 index 0000000000000000000000000000000000000000..9358d7f1f44f527348648aca2b2a161bfad90bbe --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/timeRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var timeRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [{ + concept: { + name: 'time' + }, + module: 'HTML' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = timeRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/timerRole.js b/node_modules/aria-query/lib/etc/roles/literal/timerRole.js new file mode 100644 index 0000000000000000000000000000000000000000..20ac0da8e3abac038698a867b1489c31c6e0b1e0 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/timerRole.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var timerRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'status']] +}; +var _default = timerRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/toolbarRole.js b/node_modules/aria-query/lib/etc/roles/literal/toolbarRole.js new file mode 100644 index 0000000000000000000000000000000000000000..4f67c7e778517ac64fb4c249d5f1cf61fcf25da0 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/toolbarRole.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var toolbarRole = { + abstract: false, + accessibleNameRequired: false, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-orientation': 'horizontal' + }, + relatedConcepts: [{ + concept: { + name: 'menubar' + }, + module: 'ARIA' + }], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section', 'group']] +}; +var _default = toolbarRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/tooltipRole.js b/node_modules/aria-query/lib/etc/roles/literal/tooltipRole.js new file mode 100644 index 0000000000000000000000000000000000000000..fa737ac6e18c5a687aecdc52c82f8233c8dcad29 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/tooltipRole.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var tooltipRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: {}, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [], + requiredProps: {}, + superClass: [['roletype', 'structure', 'section']] +}; +var _default = tooltipRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/treeRole.js b/node_modules/aria-query/lib/etc/roles/literal/treeRole.js new file mode 100644 index 0000000000000000000000000000000000000000..e969e70df53e5e5eb20de4fb88ab451fbf2a59e1 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/treeRole.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var treeRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: { + 'aria-errormessage': null, + 'aria-invalid': null, + 'aria-multiselectable': null, + 'aria-required': null, + 'aria-orientation': 'vertical' + }, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [['treeitem', 'group'], ['treeitem']], + requiredProps: {}, + superClass: [['roletype', 'widget', 'composite', 'select'], ['roletype', 'structure', 'section', 'group', 'select']] +}; +var _default = treeRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/treegridRole.js b/node_modules/aria-query/lib/etc/roles/literal/treegridRole.js new file mode 100644 index 0000000000000000000000000000000000000000..d8d24a79ebb63394ee8f1f892c701077d31b8980 --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/treegridRole.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var treegridRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author'], + prohibitedProps: [], + props: {}, + relatedConcepts: [], + requireContextRole: [], + requiredContextRole: [], + requiredOwnedElements: [['row'], ['row', 'rowgroup']], + requiredProps: {}, + superClass: [['roletype', 'widget', 'composite', 'grid'], ['roletype', 'structure', 'section', 'table', 'grid'], ['roletype', 'widget', 'composite', 'select', 'tree'], ['roletype', 'structure', 'section', 'group', 'select', 'tree']] +}; +var _default = treegridRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/etc/roles/literal/treeitemRole.js b/node_modules/aria-query/lib/etc/roles/literal/treeitemRole.js new file mode 100644 index 0000000000000000000000000000000000000000..488fcbebd84e519f8f14999a7ac1d7a322f0624f --- /dev/null +++ b/node_modules/aria-query/lib/etc/roles/literal/treeitemRole.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var treeitemRole = { + abstract: false, + accessibleNameRequired: true, + baseConcepts: [], + childrenPresentational: false, + nameFrom: ['author', 'contents'], + prohibitedProps: [], + props: { + 'aria-expanded': null, + 'aria-haspopup': null + }, + relatedConcepts: [], + requireContextRole: ['group', 'tree'], + requiredContextRole: ['group', 'tree'], + requiredOwnedElements: [], + requiredProps: { + 'aria-selected': null + }, + superClass: [['roletype', 'structure', 'section', 'listitem'], ['roletype', 'widget', 'input', 'option']] +}; +var _default = treeitemRole; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/index.js b/node_modules/aria-query/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1e562cad74ac9fffad6491c4609c5cb2c89c605a --- /dev/null +++ b/node_modules/aria-query/lib/index.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.roles = exports.roleElements = exports.elementRoles = exports.dom = exports.aria = void 0; +var _ariaPropsMap = _interopRequireDefault(require("./ariaPropsMap")); +var _domMap = _interopRequireDefault(require("./domMap")); +var _rolesMap = _interopRequireDefault(require("./rolesMap")); +var _elementRoleMap = _interopRequireDefault(require("./elementRoleMap")); +var _roleElementMap = _interopRequireDefault(require("./roleElementMap")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var aria = _ariaPropsMap.default; +exports.aria = aria; +var dom = _domMap.default; +exports.dom = dom; +var roles = _rolesMap.default; +exports.roles = roles; +var elementRoles = _elementRoleMap.default; +exports.elementRoles = elementRoles; +var roleElements = _roleElementMap.default; +exports.roleElements = roleElements; \ No newline at end of file diff --git a/node_modules/aria-query/lib/roleElementMap.js b/node_modules/aria-query/lib/roleElementMap.js new file mode 100644 index 0000000000000000000000000000000000000000..9dbbde65f5b8db745f9c8a59194e8c87bbf80528 --- /dev/null +++ b/node_modules/aria-query/lib/roleElementMap.js @@ -0,0 +1,85 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _iterationDecorator = _interopRequireDefault(require("./util/iterationDecorator")); +var _rolesMap = _interopRequireDefault(require("./rolesMap")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } +var roleElement = []; +var keys = _rolesMap.default.keys(); +for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var role = _rolesMap.default.get(key); + var relationConcepts = []; + if (role) { + var concepts = [].concat(role.baseConcepts, role.relatedConcepts); + for (var k = 0; k < concepts.length; k++) { + var relation = concepts[k]; + if (relation.module === 'HTML') { + var concept = relation.concept; + if (concept != null) { + relationConcepts.push(concept); + } + } + } + if (relationConcepts.length > 0) { + roleElement.push([key, relationConcepts]); + } + } +} +var roleElementMap = { + entries: function entries() { + return roleElement; + }, + forEach: function forEach(fn) { + var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var _iterator = _createForOfIteratorHelper(roleElement), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var _step$value = _slicedToArray(_step.value, 2), + _key = _step$value[0], + values = _step$value[1]; + fn.call(thisArg, values, _key, roleElement); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + }, + get: function get(key) { + var item = roleElement.find(function (tuple) { + return tuple[0] === key ? true : false; + }); + return item && item[1]; + }, + has: function has(key) { + return !!roleElementMap.get(key); + }, + keys: function keys() { + return roleElement.map(function (_ref) { + var _ref2 = _slicedToArray(_ref, 1), + key = _ref2[0]; + return key; + }); + }, + values: function values() { + return roleElement.map(function (_ref3) { + var _ref4 = _slicedToArray(_ref3, 2), + values = _ref4[1]; + return values; + }); + } +}; +var _default = (0, _iterationDecorator.default)(roleElementMap, roleElementMap.entries()); +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/rolesMap.js b/node_modules/aria-query/lib/rolesMap.js new file mode 100644 index 0000000000000000000000000000000000000000..6d2c4c55c8b1090bbc9b7b85ee1c7103dea4e5c6 --- /dev/null +++ b/node_modules/aria-query/lib/rolesMap.js @@ -0,0 +1,114 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _ariaAbstractRoles = _interopRequireDefault(require("./etc/roles/ariaAbstractRoles")); +var _ariaLiteralRoles = _interopRequireDefault(require("./etc/roles/ariaLiteralRoles")); +var _ariaDpubRoles = _interopRequireDefault(require("./etc/roles/ariaDpubRoles")); +var _ariaGraphicsRoles = _interopRequireDefault(require("./etc/roles/ariaGraphicsRoles")); +var _iterationDecorator = _interopRequireDefault(require("./util/iterationDecorator")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } +function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +var roles = [].concat(_ariaAbstractRoles.default, _ariaLiteralRoles.default, _ariaDpubRoles.default, _ariaGraphicsRoles.default); +roles.forEach(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + roleDefinition = _ref2[1]; + // Conglomerate the properties + var _iterator = _createForOfIteratorHelper(roleDefinition.superClass), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var superClassIter = _step.value; + var _iterator2 = _createForOfIteratorHelper(superClassIter), + _step2; + try { + var _loop = function _loop() { + var superClassName = _step2.value; + var superClassRoleTuple = roles.find(function (_ref3) { + var _ref4 = _slicedToArray(_ref3, 1), + name = _ref4[0]; + return name === superClassName; + }); + if (superClassRoleTuple) { + var superClassDefinition = superClassRoleTuple[1]; + for (var _i2 = 0, _Object$keys = Object.keys(superClassDefinition.props); _i2 < _Object$keys.length; _i2++) { + var prop = _Object$keys[_i2]; + if ( + // $FlowIssue Accessing the hasOwnProperty on the Object prototype is fine. + !Object.prototype.hasOwnProperty.call(roleDefinition.props, prop)) { + Object.assign(roleDefinition.props, _defineProperty({}, prop, superClassDefinition.props[prop])); + } + } + } + }; + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + _loop(); + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } +}); +var rolesMap = { + entries: function entries() { + return roles; + }, + forEach: function forEach(fn) { + var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var _iterator3 = _createForOfIteratorHelper(roles), + _step3; + try { + for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { + var _step3$value = _slicedToArray(_step3.value, 2), + key = _step3$value[0], + values = _step3$value[1]; + fn.call(thisArg, values, key, roles); + } + } catch (err) { + _iterator3.e(err); + } finally { + _iterator3.f(); + } + }, + get: function get(key) { + var item = roles.find(function (tuple) { + return tuple[0] === key ? true : false; + }); + return item && item[1]; + }, + has: function has(key) { + return !!rolesMap.get(key); + }, + keys: function keys() { + return roles.map(function (_ref5) { + var _ref6 = _slicedToArray(_ref5, 1), + key = _ref6[0]; + return key; + }); + }, + values: function values() { + return roles.map(function (_ref7) { + var _ref8 = _slicedToArray(_ref7, 2), + values = _ref8[1]; + return values; + }); + } +}; +var _default = (0, _iterationDecorator.default)(rolesMap, rolesMap.entries()); +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/lib/util/iterationDecorator.js b/node_modules/aria-query/lib/util/iterationDecorator.js new file mode 100644 index 0000000000000000000000000000000000000000..50b1102bb4729aa63963a3102b0aaf79a0e4addc --- /dev/null +++ b/node_modules/aria-query/lib/util/iterationDecorator.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = iterationDecorator; +var _iteratorProxy = _interopRequireDefault(require("./iteratorProxy")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function iterationDecorator(collection, entries) { + if (typeof Symbol === 'function' && _typeof(Symbol.iterator) === 'symbol') { + Object.defineProperty(collection, Symbol.iterator, { + value: _iteratorProxy.default.bind(entries) + }); + } + return collection; +} \ No newline at end of file diff --git a/node_modules/aria-query/lib/util/iteratorProxy.js b/node_modules/aria-query/lib/util/iteratorProxy.js new file mode 100644 index 0000000000000000000000000000000000000000..ae97950cf559686f67df6f25cd568f3e8136eefb --- /dev/null +++ b/node_modules/aria-query/lib/util/iteratorProxy.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +// eslint-disable-next-line no-unused-vars +function iteratorProxy() { + var values = this; + var index = 0; + var iter = { + '@@iterator': function iterator() { + return iter; + }, + next: function next() { + if (index < values.length) { + var value = values[index]; + index = index + 1; + return { + done: false, + value: value + }; + } else { + return { + done: true + }; + } + } + }; + return iter; +} +var _default = iteratorProxy; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/aria-query/package.json b/node_modules/aria-query/package.json new file mode 100644 index 0000000000000000000000000000000000000000..00f04b8a7eb7e6247978dd8f748f86a3ed123fa6 --- /dev/null +++ b/node_modules/aria-query/package.json @@ -0,0 +1,73 @@ +{ + "name": "aria-query", + "version": "5.3.0", + "description": "Programmatic access to the ARIA specification", + "main": "lib/index.js", + "files": [ + "lib" + ], + "scripts": { + "build": "rimraf lib && babel src --out-dir lib", + "flow": "flow", + "lint": "eslint --config .eslintrc src __tests__ scripts", + "lint:fix": "npm run lint -- --fix", + "prepublishOnly": "npm run build", + "pretest": "npm run lint:fix && npm run flow", + "test": "npm run jest", + "test:ci": "npm run jest -- --ci --runInBand", + "jest": "jest --coverage __tests__/**/*", + "output_as_hack": "babel-node ./scripts/output_as_hack.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/A11yance/aria-query.git" + }, + "keywords": [ + "accessibility", + "ARIA" + ], + "author": "Jesse Beach ", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/A11yance/aria-query/issues" + }, + "homepage": "https://github.com/A11yance/aria-query#readme", + "devDependencies": { + "@babel/cli": "^7.19.3", + "@babel/core": "^7.19.6", + "@babel/eslint-parser": "^7.19.1", + "@babel/node": "^7.22.5", + "@babel/preset-env": "^7.19.4", + "@babel/preset-flow": "^7.18.6", + "babel-jest": "^29.2.1", + "commander": "^9.4.1", + "eslint": "^8.26.0", + "eslint-config-airbnb-base": "^15.0.0", + "eslint-plugin-flowtype": "^8.0.3", + "eslint-plugin-import": "^2.26.0", + "eslint-plugin-jest": "^27.1.3", + "expect": "^29.2.1", + "flow-bin": "^0.191.0", + "jest": "^29.2.1", + "minimist": "^1.2.7", + "rimraf": "^3.0.2" + }, + "jest": { + "coverageReporters": [ + "lcov" + ], + "coverageDirectory": "reports", + "roots": [ + "/__tests__" + ] + }, + "browserslist": [ + ">0.2%", + "not dead", + "not op_mini all", + "ie 11" + ], + "dependencies": { + "dequal": "^2.0.3" + } +} diff --git a/node_modules/array-buffer-byte-length/.eslintrc b/node_modules/array-buffer-byte-length/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..fe2fefe961454cb2a48eabf78507593ea7590af5 --- /dev/null +++ b/node_modules/array-buffer-byte-length/.eslintrc @@ -0,0 +1,9 @@ +{ + "root": true, + + "extends": "@ljharb", + + "globals": { + "DataView": false, + }, +} diff --git a/node_modules/array-buffer-byte-length/.github/FUNDING.yml b/node_modules/array-buffer-byte-length/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..b3b30fa8b862410d0dc08e14b359080f23b4dd89 --- /dev/null +++ b/node_modules/array-buffer-byte-length/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/array-buffer-byte-length +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/array-buffer-byte-length/.nycrc b/node_modules/array-buffer-byte-length/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..1826526e091b89c896e7099ccd891db79165e329 --- /dev/null +++ b/node_modules/array-buffer-byte-length/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/array-buffer-byte-length/CHANGELOG.md b/node_modules/array-buffer-byte-length/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..dad50cd02965d90b9c3d7df7b0eec56363d85a49 --- /dev/null +++ b/node_modules/array-buffer-byte-length/CHANGELOG.md @@ -0,0 +1,43 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/inspect-js/array-buffer-byte-length/compare/v1.0.1...v1.0.2) - 2024-12-19 + +### Commits + +- [types] use shared config [`b15321c`](https://github.com/inspect-js/array-buffer-byte-length/commit/b15321cf546dae5d3bc2b354fb8e2a4629d6afb3) +- [actions] split out node 10-20, and 20+ [`fa1eb7d`](https://github.com/inspect-js/array-buffer-byte-length/commit/fa1eb7df107d382b47d7b9e7a07e1c4588e81cbd) +- [Dev Deps] update `@ljharb/eslint-config`, `@ljharb/tsconfig`, `@types/object-inspect`, `@types/tape`, `auto-changelog`, `es-value-fixtures`, `object-inspect`, `tape` [`53e3f93`](https://github.com/inspect-js/array-buffer-byte-length/commit/53e3f93c456b7a8a8217a832b48c416962a176e0) +- [Tests] replace `aud` with `npm audit` [`2d1b66f`](https://github.com/inspect-js/array-buffer-byte-length/commit/2d1b66ff6417b825f58adf859b540c2303d2dbde) +- [Refactor] use `call-bound` directly [`433be34`](https://github.com/inspect-js/array-buffer-byte-length/commit/433be3427e20526d74ab1faaaf0117aaf967f406) +- [Deps] update `call-bind`, `is-array-buffer` [`4ff7467`](https://github.com/inspect-js/array-buffer-byte-length/commit/4ff74673567dcae00e5a8c5d4d0f8c23b29c9a0a) +- [Dev Deps] update `tape`, `typescript` [`42c9f19`](https://github.com/inspect-js/array-buffer-byte-length/commit/42c9f1998fe8630634388b6db2c0563be05c6897) +- [Tests] add attw [`29a72f1`](https://github.com/inspect-js/array-buffer-byte-length/commit/29a72f12eb83dcfaef6a6bed0403e56699669f27) +- [Deps] update `call-bind` [`1e9e902`](https://github.com/inspect-js/array-buffer-byte-length/commit/1e9e90292388a609aa0e722bddbc9313a575ef10) +- [types] remove incorrect overload [`b509518`](https://github.com/inspect-js/array-buffer-byte-length/commit/b509518bc188f79c46aa851311f20c188faa0678) +- [Dev Deps] add missing peer dep [`31962b6`](https://github.com/inspect-js/array-buffer-byte-length/commit/31962b631a173696ceef94e9d00edf13af87d305) + +## [v1.0.1](https://github.com/inspect-js/array-buffer-byte-length/compare/v1.0.0...v1.0.1) - 2024-02-03 + +### Commits + +- [patch] add types [`598d446`](https://github.com/inspect-js/array-buffer-byte-length/commit/598d446f45c8f4246493b2a1fa2b32cd0c669602) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `npmignore`, `object-inspect`, `tape` [`2572345`](https://github.com/inspect-js/array-buffer-byte-length/commit/257234593f576a7cbb1dce1b21d52abeb68db34d) +- [Tests] add coverage [`d27357d`](https://github.com/inspect-js/array-buffer-byte-length/commit/d27357de558c3272341e252c3acc010d38edeb0f) +- [Deps] update `call-bind`, `is-array-buffer` [`2ea13ad`](https://github.com/inspect-js/array-buffer-byte-length/commit/2ea13adc85b7d775d1649ac8e9469ac380cb3665) +- [meta] add missing `engines.node` [`380e96d`](https://github.com/inspect-js/array-buffer-byte-length/commit/380e96d1c91dd579df0261950b46b62d4fed7a23) +- [Deps] update `is-array-buffer` [`cfa7093`](https://github.com/inspect-js/array-buffer-byte-length/commit/cfa7093daaeeccbaa5228a22e6ec32a307d81549) +- [meta] add `sideEffects` flag [`7297ddd`](https://github.com/inspect-js/array-buffer-byte-length/commit/7297dddd40a8f310bb69726a7a6edfae6111b8de) + +## v1.0.0 - 2023-02-28 + +### Commits + +- Initial implementation, tests, readme [`2db6cad`](https://github.com/inspect-js/array-buffer-byte-length/commit/2db6cad79270ab1966f5ea80160abbcd4534c91d) +- Initial commit [`b2a0c9c`](https://github.com/inspect-js/array-buffer-byte-length/commit/b2a0c9c2246514b7999d331aad868c4f32326db7) +- npm init [`376acdb`](https://github.com/inspect-js/array-buffer-byte-length/commit/376acdbd4435cb1d4c31d107cacb3b86f2363aee) +- Only apps should have lockfiles [`70cf325`](https://github.com/inspect-js/array-buffer-byte-length/commit/70cf32526fc727d0d16a12d85a4bddea70075e31) diff --git a/node_modules/array-buffer-byte-length/LICENSE b/node_modules/array-buffer-byte-length/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5ea30366fa48dfde3ad3548b09d05ed54fbe319f --- /dev/null +++ b/node_modules/array-buffer-byte-length/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Inspect JS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/array-buffer-byte-length/README.md b/node_modules/array-buffer-byte-length/README.md new file mode 100644 index 0000000000000000000000000000000000000000..64836c23197161aa6383a0f4f602f7fa814f4b21 --- /dev/null +++ b/node_modules/array-buffer-byte-length/README.md @@ -0,0 +1,40 @@ +# array-buffer-byte-length [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Get the byte length of an ArrayBuffer, even in engines without a `.byteLength` method. + +## Example + +```js +const assert = require('assert'); +const byteLength = require('array-buffer-byte-length'); + +assert.equal(byteLength([]), NaN, 'an array is not an ArrayBuffer, yields NaN'); + +assert.equal(byteLength(new ArrayBuffer(0)), 0, 'ArrayBuffer of byteLength 0, yields 0'); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/array-buffer-byte-length +[npm-version-svg]: https://versionbadg.es/inspect-js/array-buffer-byte-length.svg +[deps-svg]: https://david-dm.org/inspect-js/array-buffer-byte-length.svg +[deps-url]: https://david-dm.org/inspect-js/array-buffer-byte-length +[dev-deps-svg]: https://david-dm.org/inspect-js/array-buffer-byte-length/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/array-buffer-byte-length#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/array-buffer-byte-length.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/array-buffer-byte-length.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/array-buffer-byte-length.svg +[downloads-url]: https://npm-stat.com/charts.html?package=array-buffer-byte-length +[codecov-image]: https://codecov.io/gh/inspect-js/array-buffer-byte-length/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/array-buffer-byte-length/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/array-buffer-byte-length +[actions-url]: https://github.com/inspect-js/array-buffer-byte-length/actions diff --git a/node_modules/array-buffer-byte-length/index.d.ts b/node_modules/array-buffer-byte-length/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b8594b49d3eba4e6d1e50dd2b7e0fb87e6d3f1df --- /dev/null +++ b/node_modules/array-buffer-byte-length/index.d.ts @@ -0,0 +1,4 @@ +declare function arrayBufferByteLength(buffer: ArrayBuffer): number; +declare function arrayBufferByteLength(buffer: unknown): typeof NaN; + +export = arrayBufferByteLength; diff --git a/node_modules/array-buffer-byte-length/index.js b/node_modules/array-buffer-byte-length/index.js new file mode 100644 index 0000000000000000000000000000000000000000..de1be39efa7527d777f6b18c07c52dde1d6a6f60 --- /dev/null +++ b/node_modules/array-buffer-byte-length/index.js @@ -0,0 +1,14 @@ +'use strict'; + +var callBound = require('call-bound'); +var $byteLength = callBound('ArrayBuffer.prototype.byteLength', true); + +var isArrayBuffer = require('is-array-buffer'); + +/** @type {import('.')} */ +module.exports = function byteLength(ab) { + if (!isArrayBuffer(ab)) { + return NaN; + } + return $byteLength ? $byteLength(ab) : ab.byteLength; +}; // in node < 0.11, byteLength is an own nonconfigurable property diff --git a/node_modules/array-buffer-byte-length/package.json b/node_modules/array-buffer-byte-length/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f97c95215a4d9caff6a7f22c24ddd18079424ab1 --- /dev/null +++ b/node_modules/array-buffer-byte-length/package.json @@ -0,0 +1,94 @@ +{ + "name": "array-buffer-byte-length", + "version": "1.0.2", + "description": "Get the byte length of an ArrayBuffer, even in engines without a `.byteLength` method.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc && attw -P", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "keywords": [ + "shim", + "polyfill", + "ArrayBuffer", + "byteLength", + "byte", + "length", + "es-shim API", + "es-shims" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/array-buffer-byte-length.git" + }, + "bugs": { + "url": "https://github.com/inspect-js/array-buffer-byte-length/issues" + }, + "homepage": "https://github.com/inspect-js/array-buffer-byte-length#readme", + "dependencies": { + "call-bound": "^1.0.3", + "is-array-buffer": "^3.0.5" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/es-value-fixtures": "^1.4.4", + "@types/for-each": "^0.3.3", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.8.0", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "es-value-fixtures": "^1.5.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.3", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "testling": { + "files": "test/index.js" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/array-buffer-byte-length/test/index.js b/node_modules/array-buffer-byte-length/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fb328d10be3976d4af99ffe4e2a6521ca7c512f3 --- /dev/null +++ b/node_modules/array-buffer-byte-length/test/index.js @@ -0,0 +1,29 @@ +'use strict'; + +var test = require('tape'); +var forEach = require('for-each'); +var v = require('es-value-fixtures'); +var inspect = require('object-inspect'); + +var byteLength = require('../'); + +test('byteLength', function (t) { + forEach(v.objects.concat(v.primitives), function (nonAB) { + t.equal(byteLength(nonAB), NaN, inspect(nonAB) + ' is not an ArrayBuffer, and yields NaN'); + }); + + t.test('ArrayBuffers', { skip: typeof ArrayBuffer !== 'function' }, function (st) { + var ab32 = new ArrayBuffer(32); + st.equal(byteLength(ab32), 32, 'works on an ArrayBuffer of length 32: ' + inspect(ab32)); + + var ab0 = new ArrayBuffer(0); + st.equal(byteLength(ab0), 0, 'works on an ArrayBuffer of length 0: ' + inspect(ab0)); + + var dv = new DataView(ab32); + st.equal(byteLength(dv), NaN, 'a DataView returns NaN'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/array-buffer-byte-length/tsconfig.json b/node_modules/array-buffer-byte-length/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..b9fbbf12f8d0e5d60469d364c4aa201ec7d63fed --- /dev/null +++ b/node_modules/array-buffer-byte-length/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "ES2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/array-flatten/LICENSE b/node_modules/array-flatten/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..983fbe8aec3f4e2d4add592bb1083b00d7366f66 --- /dev/null +++ b/node_modules/array-flatten/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/array-flatten/README.md b/node_modules/array-flatten/README.md new file mode 100644 index 0000000000000000000000000000000000000000..91fa5b637ec2d2a492d6b5c4bf9ba2e76ff2f352 --- /dev/null +++ b/node_modules/array-flatten/README.md @@ -0,0 +1,43 @@ +# Array Flatten + +[![NPM version][npm-image]][npm-url] +[![NPM downloads][downloads-image]][downloads-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] + +> Flatten an array of nested arrays into a single flat array. Accepts an optional depth. + +## Installation + +``` +npm install array-flatten --save +``` + +## Usage + +```javascript +var flatten = require('array-flatten') + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9]) +//=> [1, 2, 3, 4, 5, 6, 7, 8, 9] + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2) +//=> [1, 2, 3, [4, [5], 6], 7, 8, 9] + +(function () { + flatten(arguments) //=> [1, 2, 3] +})(1, [2, 3]) +``` + +## License + +MIT + +[npm-image]: https://img.shields.io/npm/v/array-flatten.svg?style=flat +[npm-url]: https://npmjs.org/package/array-flatten +[downloads-image]: https://img.shields.io/npm/dm/array-flatten.svg?style=flat +[downloads-url]: https://npmjs.org/package/array-flatten +[travis-image]: https://img.shields.io/travis/blakeembrey/array-flatten.svg?style=flat +[travis-url]: https://travis-ci.org/blakeembrey/array-flatten +[coveralls-image]: https://img.shields.io/coveralls/blakeembrey/array-flatten.svg?style=flat +[coveralls-url]: https://coveralls.io/r/blakeembrey/array-flatten?branch=master diff --git a/node_modules/array-flatten/array-flatten.js b/node_modules/array-flatten/array-flatten.js new file mode 100644 index 0000000000000000000000000000000000000000..089117b322f5857b8bb6bccf7a659686aca067c0 --- /dev/null +++ b/node_modules/array-flatten/array-flatten.js @@ -0,0 +1,64 @@ +'use strict' + +/** + * Expose `arrayFlatten`. + */ +module.exports = arrayFlatten + +/** + * Recursive flatten function with depth. + * + * @param {Array} array + * @param {Array} result + * @param {Number} depth + * @return {Array} + */ +function flattenWithDepth (array, result, depth) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (depth > 0 && Array.isArray(value)) { + flattenWithDepth(value, result, depth - 1) + } else { + result.push(value) + } + } + + return result +} + +/** + * Recursive flatten function. Omitting depth is slightly faster. + * + * @param {Array} array + * @param {Array} result + * @return {Array} + */ +function flattenForever (array, result) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (Array.isArray(value)) { + flattenForever(value, result) + } else { + result.push(value) + } + } + + return result +} + +/** + * Flatten an array, with the ability to define a depth. + * + * @param {Array} array + * @param {Number} depth + * @return {Array} + */ +function arrayFlatten (array, depth) { + if (depth == null) { + return flattenForever(array, []) + } + + return flattenWithDepth(array, [], depth) +} diff --git a/node_modules/array-flatten/package.json b/node_modules/array-flatten/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1a24e2a1a1d3fbd694b77bf6673ab1e1c2fd5043 --- /dev/null +++ b/node_modules/array-flatten/package.json @@ -0,0 +1,39 @@ +{ + "name": "array-flatten", + "version": "1.1.1", + "description": "Flatten an array of nested arrays into a single flat array", + "main": "array-flatten.js", + "files": [ + "array-flatten.js", + "LICENSE" + ], + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "repository": { + "type": "git", + "url": "git://github.com/blakeembrey/array-flatten.git" + }, + "keywords": [ + "array", + "flatten", + "arguments", + "depth" + ], + "author": { + "name": "Blake Embrey", + "email": "hello@blakeembrey.com", + "url": "http://blakeembrey.me" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/blakeembrey/array-flatten/issues" + }, + "homepage": "https://github.com/blakeembrey/array-flatten", + "devDependencies": { + "istanbul": "^0.3.13", + "mocha": "^2.2.4", + "pre-commit": "^1.0.7", + "standard": "^3.7.3" + } +} diff --git a/node_modules/arraybuffer.prototype.slice/.editorconfig b/node_modules/arraybuffer.prototype.slice/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..eaa214161f5cdb409c32465fd822624c633a6bd8 --- /dev/null +++ b/node_modules/arraybuffer.prototype.slice/.editorconfig @@ -0,0 +1,13 @@ +root = true + +[*] +indent_style = tab; +insert_final_newline = true; +quote_type = auto; +space_after_anonymous_functions = true; +space_after_control_statements = true; +spaces_around_operators = true; +trim_trailing_whitespace = true; +spaces_in_brackets = false; +end_of_line = lf; + diff --git a/node_modules/arraybuffer.prototype.slice/.eslintrc b/node_modules/arraybuffer.prototype.slice/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..963e2a847aba424bfeacf333d34d9c35cc5ff574 --- /dev/null +++ b/node_modules/arraybuffer.prototype.slice/.eslintrc @@ -0,0 +1,34 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": 0, + "max-params": 0, + "max-statements": 0, + "multiline-comment-style": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "IsSharedArrayBuffer", + "ToIntegerOrInfinity", + "GetIntrinsic", + "IsDetachedBuffer", + "SpeciesConstructor", + ], + }], + }, + + "overrides": [ + { + "files": "test/**", + "globals": { + "ArrayBuffer": false, + "Uint8Array": false, + }, + "rules": { + "max-lines-per-function": 0, + }, + }, + ], +} diff --git a/node_modules/arraybuffer.prototype.slice/.nycrc b/node_modules/arraybuffer.prototype.slice/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..bdd626ce91477abbdd489b79988baebadbd3c897 --- /dev/null +++ b/node_modules/arraybuffer.prototype.slice/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/arraybuffer.prototype.slice/CHANGELOG.md b/node_modules/arraybuffer.prototype.slice/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..5ba5072d277aac7e5ec7e8decd607c759ab077ba --- /dev/null +++ b/node_modules/arraybuffer.prototype.slice/CHANGELOG.md @@ -0,0 +1,52 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.4](https://github.com/es-shims/ArrayBuffer.prototype.slice/compare/v1.0.3...v1.0.4) - 2024-12-15 + +### Commits + +- [actions] split out node 10-20, and 20+ [`5e59635`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/5e59635c948994b613c544b4e94fe93536d6b213) +- [Deps] update `call-bind`, `es-abstract`, `get-intrinsic` [`0afbb59`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/0afbb5942574055a8a3afdf0f69f60313e3f1af2) +- [Dev Deps] update `@es-shims/api`, `auto-changelog`, `es-value-fixtures`, `object-inspect`, `tape` [`d76caf4`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/d76caf4880ef358cf5384a6eb29d0f2f67e4d3a8) +- [Deps] update `call-bind`, `es-abstract`, `es-errors`, `get-intrinsic` [`2b374a2`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/2b374a2d4078d9122ac30bdecd8a8fae740aa74c) +- [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `object-inspect`, `tape` [`a24fd39`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/a24fd39370d891ea3439f9d7a1c42183c0aa1bf7) +- [Tests] replace `aud` with `npm audit` [`c704fb0`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/c704fb0b1651ceb56b609a5b4646a993fc868219) +- [Deps] remove unused dependency [`0274b32`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/0274b32ab1d345fbf70745a79dd7a44f844179bb) +- [Dev Deps] add missing peer dep [`673f754`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/673f754797dd0c40801cca2f32ff08b372448c6b) + +## [v1.0.3](https://github.com/es-shims/ArrayBuffer.prototype.slice/compare/v1.0.2...v1.0.3) - 2024-02-04 + +### Commits + +- [Deps] update `array-buffer-byte-length`, `call-bind`, `define-properties`, `es-abstract`, `get-intrinsic`, `is-array-buffer` [`d9b6859`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/d9b68591ff509613d0dfc4036539ba4e0dc34931) +- [Dev Deps] update `aud`, `npmignore`, `object-inspect`, `tape` [`38cb58d`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/38cb58dfa3f3c8b11bfb2144f8e7cc74dd461f5e) +- [Refactor] use `es-errors` where possible, so things that only need those do not need `get-intrinsic` [`5c07bef`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/5c07befd134cae93ad5f9ab307ff67691ff5155b) + +## [v1.0.2](https://github.com/es-shims/ArrayBuffer.prototype.slice/compare/v1.0.1...v1.0.2) - 2023-09-05 + +### Commits + +- [Deps] update `es-abstract` [`a9ab0d2`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/a9ab0d2551bb301b740e333ea3795fad23fcbe40) +- [Dev Deps] update `tape` [`6b24af5`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/6b24af585dc9176c8ac3fd482cb1d5257e550a09) +- [Fix] move `es-abstract` to runtime deps [`63a8397`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/63a8397623d7749856f6392ae93bf87152c3916c) + +## [v1.0.1](https://github.com/es-shims/ArrayBuffer.prototype.slice/compare/v1.0.0...v1.0.1) - 2023-07-11 + +### Commits + +- [Fix] node < 0.11 has an own nonconfigurable `slice` property; use it [`554823c`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/554823c92ce16d6b7184a7d0ccfe315b663584d7) +- [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `aud`, `es-abstract`, `tape` [`53b0421`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/53b04217048c645306597e2cfc55adb69c384146) +- [Deps] update `define-properties`, `get-intrinsic` [`4966b02`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/4966b02bc25ac006709b29ca370b9f6e159f723a) + +## v1.0.0 - 2023-07-09 + +### Commits + +- Initial implementation, tests, readme [`36b4b5e`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/36b4b5eedfa225c3086e9453b9db0088c299640a) +- Initial commit [`51499df`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/51499dfac7d8c67c2928cb47363a4de7ff17904a) +- npm init [`8ec604e`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/8ec604e7d3ef8d4c27376b09645f779c2244b08f) +- Only apps should have lockfiles [`ac54435`](https://github.com/es-shims/ArrayBuffer.prototype.slice/commit/ac54435161d4415e2122e3a682499f3a6df2f6de) diff --git a/node_modules/arraybuffer.prototype.slice/LICENSE b/node_modules/arraybuffer.prototype.slice/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..eb970aa5c97e857bc35d652dafc6976006dc6ec5 --- /dev/null +++ b/node_modules/arraybuffer.prototype.slice/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 ECMAScript Shims + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/arraybuffer.prototype.slice/README.md b/node_modules/arraybuffer.prototype.slice/README.md new file mode 100644 index 0000000000000000000000000000000000000000..503585715baa221167b052c9dfb2c1b2fe6cecca --- /dev/null +++ b/node_modules/arraybuffer.prototype.slice/README.md @@ -0,0 +1,61 @@ +# ArrayBuffer.prototype.slice [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +An ES spec-compliant `ArrayBuffer.prototype.slice` shim. Invoke its "shim" method to shim ArrayBuffer.prototype.slice if it is unavailable. + +This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES5-supported environment and complies with the [spec](https://tc39.es/ecma262/#sec-arraybuffer.prototype.slice). + +Most common usage: +```js +var assert = require('assert'); +var slice = require('arraybuffer.prototype.slice'); + +var ab = new ArrayBuffer(1); +var arr = new Uint8Array(ab); +arr[0] = 123; + +var ab2 = slice(ab); + +var arr2 = new Uint8Array(ab2); +arr2[0] = 234; + +assert.deepEqual(arr, new Uint8Array([123])); +assert.deepEqual(arr2, new Uint8Array([234])); + +if (!ArrayBuffer.prototype.transfer) { + slice.shim(); +} + +var ab2 = ab.slice(); + +var arr2 = new Uint8Array(ab2); +arr2[0] = 234; + +assert.deepEqual(arr, new Uint8Array([123])); +assert.deepEqual(arr2, new Uint8Array([234])); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/arraybuffer.prototype.slice +[npm-version-svg]: https://versionbadg.es/es-shims/ArrayBuffer.prototype.slice.svg +[deps-svg]: https://david-dm.org/es-shims/ArrayBuffer.prototype.slice.svg +[deps-url]: https://david-dm.org/es-shims/ArrayBuffer.prototype.slice +[dev-deps-svg]: https://david-dm.org/es-shims/ArrayBuffer.prototype.slice/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/ArrayBuffer.prototype.slice#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/arraybuffer.prototype.slice.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/arraybuffer.prototype.slice.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/arraybuffer.prototype.slice.svg +[downloads-url]: https://npm-stat.com/charts.html?package=arraybuffer.prototype.slice +[codecov-image]: https://codecov.io/gh/es-shims/ArrayBuffer.prototype.slice/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/es-shims/ArrayBuffer.prototype.slice/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/es-shims/ArrayBuffer.prototype.slice +[actions-url]: https://github.com/es-shims/ArrayBuffer.prototype.slice/actions diff --git a/node_modules/arraybuffer.prototype.slice/auto.js b/node_modules/arraybuffer.prototype.slice/auto.js new file mode 100644 index 0000000000000000000000000000000000000000..8ebf606cb02ff3a8c6ef786afa37d21a19254f46 --- /dev/null +++ b/node_modules/arraybuffer.prototype.slice/auto.js @@ -0,0 +1,3 @@ +'use strict'; + +require('./shim')(); diff --git a/node_modules/arraybuffer.prototype.slice/implementation.js b/node_modules/arraybuffer.prototype.slice/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..49ed964415147037ddd814ca03ef9f47f70e646c --- /dev/null +++ b/node_modules/arraybuffer.prototype.slice/implementation.js @@ -0,0 +1,84 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var $ArrayBuffer = GetIntrinsic('%ArrayBuffer%', true); +var $Uint8Array = GetIntrinsic('%Uint8Array%', true); + +var IsDetachedBuffer = require('es-abstract/2024/IsDetachedBuffer'); +var IsSharedArrayBuffer = require('es-abstract/2024/IsSharedArrayBuffer'); +var max = require('es-abstract/2024/max'); +var min = require('es-abstract/2024/min'); +var SpeciesConstructor = require('es-abstract/2024/SpeciesConstructor'); +var ToIntegerOrInfinity = require('es-abstract/2024/ToIntegerOrInfinity'); + +var arrayBufferByteLength = require('array-buffer-byte-length'); +var isArrayBuffer = require('is-array-buffer'); +var $TypeError = require('es-errors/type'); + +module.exports = function slice(start, end) { + var O = this; // step 1 + + if (!isArrayBuffer(O) || IsSharedArrayBuffer(O) || IsDetachedBuffer(O)) { + throw new $TypeError('receiver must be a non-detached, non-shared ArrayBuffer'); // steps 2-4 + } + + var len = arrayBufferByteLength(O); // step 5 + + var relativeStart = ToIntegerOrInfinity(start); // step 6 + + var first; + if (relativeStart === -Infinity) { + first = 0; // step 7 + } else if (relativeStart < 0) { + first = max(len + relativeStart, 0); // step 8 + } else { + first = min(relativeStart, len); // step 9 + } + + var relativeEnd = typeof end === 'undefined' ? len : ToIntegerOrInfinity(end); // step 10 + + var final; + if (relativeEnd === -Infinity) { + final = 0; // step 11 + } else if (relativeEnd < 0) { + final = max(len + relativeEnd, 0); // step 12 + } else { + final = min(relativeEnd, len); // step 13 + } + + var newLen = max(final - first, 0); // step 14 + + var Ctor = SpeciesConstructor(O, $ArrayBuffer); // step 15 + + var new$ = new Ctor(newLen); // step 16 + + if (!isArrayBuffer(new$) || IsSharedArrayBuffer(new$) || IsDetachedBuffer(new$)) { + throw new $TypeError('Species constructor must produce a non-detached, non-shared Array Buffer'); // steps 17-19 + } + + if (new$ === O) { + throw new $TypeError('new ArrayBuffer should not have been the same as the receiver'); // step 20 + } + + if (arrayBufferByteLength(new$) < newLen) { + throw new $TypeError('new ArrayBuffer\'s byteLength must be at least the requested length'); // step 21 + } + + if (IsDetachedBuffer(O)) { + throw new $TypeError('receiver became an detached ArrayBuffer'); // step 23 + } + + /* + 24. Let fromBuf be O.[[ArrayBufferData]]. + 25. Let toBuf be new.[[ArrayBufferData]]. + 26. Perform CopyDataBlockBytes(toBuf, 0, fromBuf, first, newLen). + */ + var sourceArr = new $Uint8Array(O); + var destArr = new $Uint8Array(new$); + for (var i = start, ii = 0; i < end; i++, ii++) { + destArr[ii] = sourceArr[i]; + } + + return new$; // step 27 +}; diff --git a/node_modules/arraybuffer.prototype.slice/index.js b/node_modules/arraybuffer.prototype.slice/index.js new file mode 100644 index 0000000000000000000000000000000000000000..517c4147e95eb17c4f92a9583e020b7971762c8e --- /dev/null +++ b/node_modules/arraybuffer.prototype.slice/index.js @@ -0,0 +1,18 @@ +'use strict'; + +var define = require('define-properties'); +var callBind = require('call-bind'); + +var implementation = require('./implementation'); +var getPolyfill = require('./polyfill'); +var shim = require('./shim'); + +var bound = callBind(getPolyfill()); + +define(bound, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = bound; diff --git a/node_modules/arraybuffer.prototype.slice/package.json b/node_modules/arraybuffer.prototype.slice/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c4d6c9e96ed80103d0234c31192f5cafcc40fe02 --- /dev/null +++ b/node_modules/arraybuffer.prototype.slice/package.json @@ -0,0 +1,102 @@ +{ + "name": "arraybuffer.prototype.slice", + "version": "1.0.4", + "description": "ES spec-compliant shim for ArrayBuffer.prototype.slice", + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "main": "index.js", + "exports": { + ".": "./index.js", + "./auto": "./auto.js", + "./polyfill": "./polyfill.js", + "./implementation": "./implementation.js", + "./shim": "./shim.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run lint", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "tests-only": "nyc tape 'test/**/*.js'", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "evalmd README.md && es-shim-api --bound", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/es-shims/ArrayBuffer.prototype.slice.git" + }, + "homepage": "https://github.com/es-shims/ArrayBuffer.prototype.slice#readme", + "bugs": { + "url": "https://github.com/es-shims/ArrayBuffer.prototype.slice/issues" + }, + "keywords": [ + "javascript", + "ecmascript", + "ArrayBuffer.prototype.slice", + "polyfill", + "shim", + "ArrayBuffer", + "array", + "buffer", + "ArrayBuffer#slice", + "slice", + "typed array", + "es-shim API" + ], + "dependencies": { + "array-buffer-byte-length": "^1.0.1", + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "is-array-buffer": "^3.0.4" + }, + "devDependencies": { + "@es-shims/api": "^2.5.1", + "@ljharb/eslint-config": "^21.1.1", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "es-value-fixtures": "^1.5.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "functions-have-names": "^1.2.3", + "has-strict-mode": "^1.0.1", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.3", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0" + }, + "testling": { + "files": "test/index.js" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/arraybuffer.prototype.slice/polyfill.js b/node_modules/arraybuffer.prototype.slice/polyfill.js new file mode 100644 index 0000000000000000000000000000000000000000..a4a90ca166ee027f736734902943b2001a8ebe98 --- /dev/null +++ b/node_modules/arraybuffer.prototype.slice/polyfill.js @@ -0,0 +1,21 @@ +'use strict'; + +var callBind = require('call-bind'); + +var implementation = require('./implementation'); + +var ownSlice = typeof ArrayBuffer === 'function' && new ArrayBuffer(0).slice; +var ownSliceBound = ownSlice && callBind(ownSlice); +var ownSliceWrapper = ownSliceBound && function slice(start, end) { + /* eslint no-invalid-this: 0 */ + if (arguments.length < 2) { + return ownSliceBound(this, arguments.length > 0 ? start : 0); + } + return ownSliceBound(this, start, end); +}; + +module.exports = function getPolyfill() { + return (typeof ArrayBuffer === 'function' && ArrayBuffer.prototype.slice) + || ownSliceWrapper + || implementation; +}; diff --git a/node_modules/arraybuffer.prototype.slice/shim.js b/node_modules/arraybuffer.prototype.slice/shim.js new file mode 100644 index 0000000000000000000000000000000000000000..cb52c0710281803247e13a827ea429212ad662b2 --- /dev/null +++ b/node_modules/arraybuffer.prototype.slice/shim.js @@ -0,0 +1,18 @@ +'use strict'; + +var define = require('define-properties'); + +var getPolyfill = require('./polyfill'); + +module.exports = function shimArrayBufferSlice() { + if (typeof ArrayBuffer === 'function') { + var polyfill = getPolyfill(); + define( + ArrayBuffer.prototype, + { slice: polyfill }, + { slice: function () { return ArrayBuffer.prototype.slice !== polyfill; } } + ); + } + + return polyfill; +}; diff --git a/node_modules/arraybuffer.prototype.slice/test/implementation.js b/node_modules/arraybuffer.prototype.slice/test/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..7d97bb77c3e91762b2fcce32cc888e221add14aa --- /dev/null +++ b/node_modules/arraybuffer.prototype.slice/test/implementation.js @@ -0,0 +1,32 @@ +'use strict'; + +var implementation = require('../implementation'); +var callBind = require('call-bind'); +var test = require('tape'); +var hasStrictMode = require('has-strict-mode')(); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('ArrayBuffer support', { skip: typeof ArrayBuffer === 'undefined' }, function (st) { + st.test('bad array/this value', { skip: !hasStrictMode }, function (s2t) { + /* eslint no-useless-call: 0 */ + s2t['throws'](function () { implementation.call(undefined); }, TypeError, 'undefined is not an object'); + s2t['throws'](function () { implementation.call(null); }, TypeError, 'null is not an object'); + s2t.end(); + }); + + runTests(callBind(implementation), st); + + st.end(); + }); + + t.test('no ArrayBuffer support', { skip: typeof ArrayBuffer !== 'undefined' }, function (st) { + st['throws']( + function () { implementation.call({}); }, + SyntaxError, + 'ArrayBuffer is not supported' + ); + }); + + t.end(); +}); diff --git a/node_modules/arraybuffer.prototype.slice/test/index.js b/node_modules/arraybuffer.prototype.slice/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0e9dd102cd8e7d63b454f9562d4b548a6b4135ac --- /dev/null +++ b/node_modules/arraybuffer.prototype.slice/test/index.js @@ -0,0 +1,29 @@ +'use strict'; + +var index = require('../'); +var test = require('tape'); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('ArrayBuffer support', { skip: typeof ArrayBuffer === 'undefined' }, function (st) { + st.test('bad array/this value', function (s2t) { + s2t['throws'](function () { index(undefined); }, TypeError, 'undefined is not an object'); + s2t['throws'](function () { index(null); }, TypeError, 'null is not an object'); + s2t.end(); + }); + + runTests(index, st); + + st.end(); + }); + + t.test('no ArrayBuffer support', { skip: typeof ArrayBuffer !== 'undefined' }, function (st) { + st['throws']( + function () { index({}); }, + SyntaxError, + 'ArrayBuffer is not supported' + ); + }); + + t.end(); +}); diff --git a/node_modules/arraybuffer.prototype.slice/test/shimmed.js b/node_modules/arraybuffer.prototype.slice/test/shimmed.js new file mode 100644 index 0000000000000000000000000000000000000000..8dd4f72142e89a94bbed91769a5327018548e77b --- /dev/null +++ b/node_modules/arraybuffer.prototype.slice/test/shimmed.js @@ -0,0 +1,54 @@ +'use strict'; + +require('../auto'); + +var test = require('tape'); +var defineProperties = require('define-properties'); +var callBind = require('call-bind'); + +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = require('functions-have-names')(); +var hasStrictMode = require('has-strict-mode')(); + +var runTests = require('./tests'); + +test('shimmed', function (t) { + t.test('ArrayBuffer support', { skip: typeof ArrayBuffer === 'undefined' }, function (st) { + var method = ArrayBuffer.prototype.slice; + + st.equal(method.length, 2, 'ArrayBuffer#slice has a length of 2'); + + st.test('Function name', { skip: !functionsHaveNames }, function (s2t) { + s2t.equal(method.name, 'slice', 'ArrayBuffer#slice name "slice"'); + s2t.end(); + }); + + st.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(ArrayBuffer.prototype, 'slice'), 'ArrayBuffer#slice is not enumerable'); + et.end(); + }); + + st.test('bad array/this value', { skip: !hasStrictMode }, function (s2t) { + /* eslint no-useless-call: 0 */ + s2t['throws'](function () { return method.call(undefined); }, TypeError, 'undefined is not an object'); + s2t['throws'](function () { return method.call(null); }, TypeError, 'null is not an object'); + s2t.end(); + }); + + t.test('has the correct descriptor', { skip: !Object.getOwnPropertyDescriptor }, function (s2t) { + var descriptor = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'slice'); + + s2t.equal(descriptor.configurable, true); + s2t.equal(descriptor.enumerable, false); + s2t.equal(typeof descriptor.value, 'function'); + s2t.equal(descriptor.writable, true); + s2t.end(); + }); + + runTests(callBind(method), st); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/arraybuffer.prototype.slice/test/tests.js b/node_modules/arraybuffer.prototype.slice/test/tests.js new file mode 100644 index 0000000000000000000000000000000000000000..4128b1b9fd16569649e115ecd72483f16433f88b --- /dev/null +++ b/node_modules/arraybuffer.prototype.slice/test/tests.js @@ -0,0 +1,81 @@ +'use strict'; + +var inspect = require('object-inspect'); +var IsDetachedBuffer = require('es-abstract/2024/IsDetachedBuffer'); + +var forEach = require('for-each'); +var v = require('es-value-fixtures'); + +var byteLength = require('array-buffer-byte-length'); + +module.exports = function runTests(slice, t) { + forEach(v.primitives.concat(v.objects), function (nonAB) { + t['throws']( + function () { slice(nonAB); }, + TypeError, + inspect(nonAB) + ' is not an ArrayBuffer' + ); + }); + + t.test('ArrayBuffers', { skip: typeof ArrayBuffer === 'undefined' }, function (st) { + var ab = new ArrayBuffer(0); + + st.equal(IsDetachedBuffer(ab), false, 'ArrayBuffer is not detached'); + + try { + var nb = slice(ab); + } catch (e) { + if (e instanceof SyntaxError) { + st.skip('Detaching ArrayBuffer is not supported'); + return st.end(); + } + console.log(e.stack); + } + + st.notEqual(nb, ab, 'new ArrayBuffer is not the same as the original'); + st.equal(IsDetachedBuffer(ab), false, 'old ArrayBuffer is not detached'); + st.equal(IsDetachedBuffer(nb), false, 'new ArrayBuffer is not detached'); + + var ab2 = new ArrayBuffer(8); + st.equal(byteLength(ab2), 8, 'original ArrayBuffer has length 8'); + try { + var nbLen = slice(ab2, 4); + } catch (e) { + if (e instanceof SyntaxError) { + st.skip('Detaching ArrayBuffer is not supported'); + return st.end(); + } + } + st.equal(IsDetachedBuffer(ab2), false, 'old ArrayBuffer is not detached'); + st.equal(IsDetachedBuffer(nbLen), false, 'new ArrayBuffer is not detached'); + + st.equal(byteLength(ab2), 8, 'original ArrayBuffer has length 8'); + st.equal(byteLength(nbLen), 4, 'newly sliced ArrayBuffer has length 4'); + + var one = new ArrayBuffer(1); + var arr = new Uint8Array(one); + arr[0] = 123; + + var two = slice(one); + + var arr2 = new Uint8Array(two); + arr2[0] = 234; + + st.deepEqual(arr, new Uint8Array([123]), 'original buffer is unchanged'); + st.deepEqual(arr2, new Uint8Array([234]), 'sliced buffer is changed'); + + return st.end(); + }); + + t.test('SharedArrayBuffers', { skip: typeof SharedArrayBuffer === 'undefined' }, function (st) { + var sab = new SharedArrayBuffer(0); + + st['throws']( + function () { slice(sab); }, + TypeError, + inspect(sab) + ' is not an ArrayBuffer' + ); + + st.end(); + }); +}; diff --git a/node_modules/asap/CHANGES.md b/node_modules/asap/CHANGES.md new file mode 100644 index 0000000000000000000000000000000000000000..f105b91956d156a75195ffb4ddfb688a57deeb9b --- /dev/null +++ b/node_modules/asap/CHANGES.md @@ -0,0 +1,70 @@ + +## 2.0.6 + +Version 2.0.4 adds support for React Native by clarifying in package.json that +the browser environment does not support Node.js domains. +Why this is necessary, we leave as an exercise for the user. + +## 2.0.3 + +Version 2.0.3 fixes a bug when adjusting the capacity of the task queue. + +## 2.0.1-2.02 + +Version 2.0.1 fixes a bug in the way redirects were expressed that affected the +function of Browserify, but which Mr would tolerate. + +## 2.0.0 + +Version 2 of ASAP is a full rewrite with a few salient changes. +First, the ASAP source is CommonJS only and designed with [Browserify][] and +[Browserify-compatible][Mr] module loaders in mind. + +[Browserify]: https://github.com/substack/node-browserify +[Mr]: https://github.com/montagejs/mr + +The new version has been refactored in two dimensions. +Support for Node.js and browsers have been separated, using Browserify +redirects and ASAP has been divided into two modules. +The "raw" layer depends on the tasks to catch thrown exceptions and unravel +Node.js domains. + +The full implementation of ASAP is loadable as `require("asap")` in both Node.js +and browsers. + +The raw layer that lacks exception handling overhead is loadable as +`require("asap/raw")`. +The interface is the same for both layers. + +Tasks are no longer required to be functions, but can rather be any object that +implements `task.call()`. +With this feature you can recycle task objects to avoid garbage collector churn +and avoid closures in general. + +The implementation has been rigorously documented so that our successors can +understand the scope of the problem that this module solves and all of its +nuances, ensuring that the next generation of implementations know what details +are essential. + +- [asap.js](https://github.com/kriskowal/asap/blob/master/asap.js) +- [raw.js](https://github.com/kriskowal/asap/blob/master/raw.js) +- [browser-asap.js](https://github.com/kriskowal/asap/blob/master/browser-asap.js) +- [browser-raw.js](https://github.com/kriskowal/asap/blob/master/browser-raw.js) + +The new version has also been rigorously tested across a broad spectrum of +browsers, in both the window and worker context. +The following charts capture the browser test results for the most recent +release. +The first chart shows test results for ASAP running in the main window context. +The second chart shows test results for ASAP running in a web worker context. +Test results are inconclusive (grey) on browsers that do not support web +workers. +These data are captured automatically by [Continuous +Integration][]. + +![Browser Compatibility](http://kriskowal-asap.s3-website-us-west-2.amazonaws.com/train/integration-2/saucelabs-results-matrix.svg) + +![Compatibility in Web Workers](http://kriskowal-asap.s3-website-us-west-2.amazonaws.com/train/integration-2/saucelabs-worker-results-matrix.svg) + +[Continuous Integration]: https://github.com/kriskowal/asap/blob/master/CONTRIBUTING.md + diff --git a/node_modules/asap/LICENSE.md b/node_modules/asap/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..ba18c61390db9abb932e6bc70fa9a9e8aa2e5d31 --- /dev/null +++ b/node_modules/asap/LICENSE.md @@ -0,0 +1,21 @@ + +Copyright 2009–2014 Contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. + diff --git a/node_modules/asap/README.md b/node_modules/asap/README.md new file mode 100644 index 0000000000000000000000000000000000000000..452fd8c20370995ffc6c3a9be8d15aa6f3397615 --- /dev/null +++ b/node_modules/asap/README.md @@ -0,0 +1,237 @@ +# ASAP + +[![Build Status](https://travis-ci.org/kriskowal/asap.png?branch=master)](https://travis-ci.org/kriskowal/asap) + +Promise and asynchronous observer libraries, as well as hand-rolled callback +programs and libraries, often need a mechanism to postpone the execution of a +callback until the next available event. +(See [Designing API’s for Asynchrony][Zalgo].) +The `asap` function executes a task **as soon as possible** but not before it +returns, waiting only for the completion of the current event and previously +scheduled tasks. + +```javascript +asap(function () { + // ... +}); +``` + +[Zalgo]: http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony + +This CommonJS package provides an `asap` module that exports a function that +executes a task function *as soon as possible*. + +ASAP strives to schedule events to occur before yielding for IO, reflow, +or redrawing. +Each event receives an independent stack, with only platform code in parent +frames and the events run in the order they are scheduled. + +ASAP provides a fast event queue that will execute tasks until it is +empty before yielding to the JavaScript engine's underlying event-loop. +When a task gets added to a previously empty event queue, ASAP schedules a flush +event, preferring for that event to occur before the JavaScript engine has an +opportunity to perform IO tasks or rendering, thus making the first task and +subsequent tasks semantically indistinguishable. +ASAP uses a variety of techniques to preserve this invariant on different +versions of browsers and Node.js. + +By design, ASAP prevents input events from being handled until the task +queue is empty. +If the process is busy enough, this may cause incoming connection requests to be +dropped, and may cause existing connections to inform the sender to reduce the +transmission rate or stall. +ASAP allows this on the theory that, if there is enough work to do, there is no +sense in looking for trouble. +As a consequence, ASAP can interfere with smooth animation. +If your task should be tied to the rendering loop, consider using +`requestAnimationFrame` instead. +A long sequence of tasks can also effect the long running script dialog. +If this is a problem, you may be able to use ASAP’s cousin `setImmediate` to +break long processes into shorter intervals and periodically allow the browser +to breathe. +`setImmediate` will yield for IO, reflow, and repaint events. +It also returns a handler and can be canceled. +For a `setImmediate` shim, consider [YuzuJS setImmediate][setImmediate]. + +[setImmediate]: https://github.com/YuzuJS/setImmediate + +Take care. +ASAP can sustain infinite recursive calls without warning. +It will not halt from a stack overflow, and it will not consume unbounded +memory. +This is behaviorally equivalent to an infinite loop. +Just as with infinite loops, you can monitor a Node.js process for this behavior +with a heart-beat signal. +As with infinite loops, a very small amount of caution goes a long way to +avoiding problems. + +```javascript +function loop() { + asap(loop); +} +loop(); +``` + +In browsers, if a task throws an exception, it will not interrupt the flushing +of high-priority tasks. +The exception will be postponed to a later, low-priority event to avoid +slow-downs. +In Node.js, if a task throws an exception, ASAP will resume flushing only if—and +only after—the error is handled by `domain.on("error")` or +`process.on("uncaughtException")`. + +## Raw ASAP + +Checking for exceptions comes at a cost. +The package also provides an `asap/raw` module that exports the underlying +implementation which is faster but stalls if a task throws an exception. +This internal version of the ASAP function does not check for errors. +If a task does throw an error, it will stall the event queue unless you manually +call `rawAsap.requestFlush()` before throwing the error, or any time after. + +In Node.js, `asap/raw` also runs all tasks outside any domain. +If you need a task to be bound to your domain, you will have to do it manually. + +```js +if (process.domain) { + task = process.domain.bind(task); +} +rawAsap(task); +``` + +## Tasks + +A task may be any object that implements `call()`. +A function will suffice, but closures tend not to be reusable and can cause +garbage collector churn. +Both `asap` and `rawAsap` accept task objects to give you the option of +recycling task objects or using higher callable object abstractions. +See the `asap` source for an illustration. + + +## Compatibility + +ASAP is tested on Node.js v0.10 and in a broad spectrum of web browsers. +The following charts capture the browser test results for the most recent +release. +The first chart shows test results for ASAP running in the main window context. +The second chart shows test results for ASAP running in a web worker context. +Test results are inconclusive (grey) on browsers that do not support web +workers. +These data are captured automatically by [Continuous +Integration][]. + +[Continuous Integration]: https://github.com/kriskowal/asap/blob/master/CONTRIBUTING.md + +![Browser Compatibility](http://kriskowal-asap.s3-website-us-west-2.amazonaws.com/train/integration-2/saucelabs-results-matrix.svg) + +![Compatibility in Web Workers](http://kriskowal-asap.s3-website-us-west-2.amazonaws.com/train/integration-2/saucelabs-worker-results-matrix.svg) + +## Caveats + +When a task is added to an empty event queue, it is not always possible to +guarantee that the task queue will begin flushing immediately after the current +event. +However, once the task queue begins flushing, it will not yield until the queue +is empty, even if the queue grows while executing tasks. + +The following browsers allow the use of [DOM mutation observers][] to access +the HTML [microtask queue][], and thus begin flushing ASAP's task queue +immediately at the end of the current event loop turn, before any rendering or +IO: + +[microtask queue]: http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#microtask-queue +[DOM mutation observers]: http://dom.spec.whatwg.org/#mutation-observers + +- Android 4–4.3 +- Chrome 26–34 +- Firefox 14–29 +- Internet Explorer 11 +- iPad Safari 6–7.1 +- iPhone Safari 7–7.1 +- Safari 6–7 + +In the absense of mutation observers, there are a few browsers, and situations +like web workers in some of the above browsers, where [message channels][] +would be a useful way to avoid falling back to timers. +Message channels give direct access to the HTML [task queue][], so the ASAP +task queue would flush after any already queued rendering and IO tasks, but +without having the minimum delay imposed by timers. +However, among these browsers, Internet Explorer 10 and Safari do not reliably +dispatch messages, so they are not worth the trouble to implement. + +[message channels]: http://www.whatwg.org/specs/web-apps/current-work/multipage/web-messaging.html#message-channels +[task queue]: http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#concept-task + +- Internet Explorer 10 +- Safair 5.0-1 +- Opera 11-12 + +In the absense of mutation observers, these browsers and the following browsers +all fall back to using `setTimeout` and `setInterval` to ensure that a `flush` +occurs. +The implementation uses both and cancels whatever handler loses the race, since +`setTimeout` tends to occasionally skip tasks in unisolated circumstances. +Timers generally delay the flushing of ASAP's task queue for four milliseconds. + +- Firefox 3–13 +- Internet Explorer 6–10 +- iPad Safari 4.3 +- Lynx 2.8.7 + + +## Heritage + +ASAP has been factored out of the [Q][] asynchronous promise library. +It originally had a naïve implementation in terms of `setTimeout`, but +[Malte Ubl][NonBlocking] provided an insight that `postMessage` might be +useful for creating a high-priority, no-delay event dispatch hack. +Since then, Internet Explorer proposed and implemented `setImmediate`. +Robert Katić began contributing to Q by measuring the performance of +the internal implementation of `asap`, paying particular attention to +error recovery. +Domenic, Robert, and Kris Kowal collectively settled on the current strategy of +unrolling the high-priority event queue internally regardless of what strategy +we used to dispatch the potentially lower-priority flush event. +Domenic went on to make ASAP cooperate with Node.js domains. + +[Q]: https://github.com/kriskowal/q +[NonBlocking]: http://www.nonblocking.io/2011/06/windownexttick.html + +For further reading, Nicholas Zakas provided a thorough article on [The +Case for setImmediate][NCZ]. + +[NCZ]: http://www.nczonline.net/blog/2013/07/09/the-case-for-setimmediate/ + +Ember’s RSVP promise implementation later [adopted][RSVP ASAP] the name ASAP but +further developed the implentation. +Particularly, The `MessagePort` implementation was abandoned due to interaction +[problems with Mobile Internet Explorer][IE Problems] in favor of an +implementation backed on the newer and more reliable DOM `MutationObserver` +interface. +These changes were back-ported into this library. + +[IE Problems]: https://github.com/cujojs/when/issues/197 +[RSVP ASAP]: https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js + +In addition, ASAP factored into `asap` and `asap/raw`, such that `asap` remained +exception-safe, but `asap/raw` provided a tight kernel that could be used for +tasks that guaranteed that they would not throw exceptions. +This core is useful for promise implementations that capture thrown errors in +rejected promises and do not need a second safety net. +At the same time, the exception handling in `asap` was factored into separate +implementations for Node.js and browsers, using the the [Browserify][Browser +Config] `browser` property in `package.json` to instruct browser module loaders +and bundlers, including [Browserify][], [Mr][], and [Mop][], to use the +browser-only implementation. + +[Browser Config]: https://gist.github.com/defunctzombie/4339901 +[Browserify]: https://github.com/substack/node-browserify +[Mr]: https://github.com/montagejs/mr +[Mop]: https://github.com/montagejs/mop + +## License + +Copyright 2009-2014 by Contributors +MIT License (enclosed) + diff --git a/node_modules/asap/asap.js b/node_modules/asap/asap.js new file mode 100644 index 0000000000000000000000000000000000000000..f04fcd58fc0b22a2451b5ff86096de0145451f68 --- /dev/null +++ b/node_modules/asap/asap.js @@ -0,0 +1,65 @@ +"use strict"; + +var rawAsap = require("./raw"); +var freeTasks = []; + +/** + * Calls a task as soon as possible after returning, in its own event, with + * priority over IO events. An exception thrown in a task can be handled by + * `process.on("uncaughtException") or `domain.on("error")`, but will otherwise + * crash the process. If the error is handled, all subsequent tasks will + * resume. + * + * @param {{call}} task A callable object, typically a function that takes no + * arguments. + */ +module.exports = asap; +function asap(task) { + var rawTask; + if (freeTasks.length) { + rawTask = freeTasks.pop(); + } else { + rawTask = new RawTask(); + } + rawTask.task = task; + rawTask.domain = process.domain; + rawAsap(rawTask); +} + +function RawTask() { + this.task = null; + this.domain = null; +} + +RawTask.prototype.call = function () { + if (this.domain) { + this.domain.enter(); + } + var threw = true; + try { + this.task.call(); + threw = false; + // If the task throws an exception (presumably) Node.js restores the + // domain stack for the next event. + if (this.domain) { + this.domain.exit(); + } + } finally { + // We use try/finally and a threw flag to avoid messing up stack traces + // when we catch and release errors. + if (threw) { + // In Node.js, uncaught exceptions are considered fatal errors. + // Re-throw them to interrupt flushing! + // Ensure that flushing continues if an uncaught exception is + // suppressed listening process.on("uncaughtException") or + // domain.on("error"). + rawAsap.requestFlush(); + } + // If the task threw an error, we do not want to exit the domain here. + // Exiting the domain would prevent the domain from catching the error. + this.task = null; + this.domain = null; + freeTasks.push(this); + } +}; + diff --git a/node_modules/asap/browser-asap.js b/node_modules/asap/browser-asap.js new file mode 100644 index 0000000000000000000000000000000000000000..805c9824605b07ccc1f5bc114beb48cb37384f95 --- /dev/null +++ b/node_modules/asap/browser-asap.js @@ -0,0 +1,66 @@ +"use strict"; + +// rawAsap provides everything we need except exception management. +var rawAsap = require("./raw"); +// RawTasks are recycled to reduce GC churn. +var freeTasks = []; +// We queue errors to ensure they are thrown in right order (FIFO). +// Array-as-queue is good enough here, since we are just dealing with exceptions. +var pendingErrors = []; +var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError); + +function throwFirstError() { + if (pendingErrors.length) { + throw pendingErrors.shift(); + } +} + +/** + * Calls a task as soon as possible after returning, in its own event, with priority + * over other events like animation, reflow, and repaint. An error thrown from an + * event will not interrupt, nor even substantially slow down the processing of + * other events, but will be rather postponed to a lower priority event. + * @param {{call}} task A callable object, typically a function that takes no + * arguments. + */ +module.exports = asap; +function asap(task) { + var rawTask; + if (freeTasks.length) { + rawTask = freeTasks.pop(); + } else { + rawTask = new RawTask(); + } + rawTask.task = task; + rawAsap(rawTask); +} + +// We wrap tasks with recyclable task objects. A task object implements +// `call`, just like a function. +function RawTask() { + this.task = null; +} + +// The sole purpose of wrapping the task is to catch the exception and recycle +// the task object after its single use. +RawTask.prototype.call = function () { + try { + this.task.call(); + } catch (error) { + if (asap.onerror) { + // This hook exists purely for testing purposes. + // Its name will be periodically randomized to break any code that + // depends on its existence. + asap.onerror(error); + } else { + // In a web browser, exceptions are not fatal. However, to avoid + // slowing down the queue of pending tasks, we rethrow the error in a + // lower priority turn. + pendingErrors.push(error); + requestErrorThrow(); + } + } finally { + this.task = null; + freeTasks[freeTasks.length] = this; + } +}; diff --git a/node_modules/asap/browser-raw.js b/node_modules/asap/browser-raw.js new file mode 100644 index 0000000000000000000000000000000000000000..9cee7e32eb5d354c90fbd5b6f0d34f4c2827d92e --- /dev/null +++ b/node_modules/asap/browser-raw.js @@ -0,0 +1,223 @@ +"use strict"; + +// Use the fastest means possible to execute a task in its own turn, with +// priority over other events including IO, animation, reflow, and redraw +// events in browsers. +// +// An exception thrown by a task will permanently interrupt the processing of +// subsequent tasks. The higher level `asap` function ensures that if an +// exception is thrown by a task, that the task queue will continue flushing as +// soon as possible, but if you use `rawAsap` directly, you are responsible to +// either ensure that no exceptions are thrown from your task, or to manually +// call `rawAsap.requestFlush` if an exception is thrown. +module.exports = rawAsap; +function rawAsap(task) { + if (!queue.length) { + requestFlush(); + flushing = true; + } + // Equivalent to push, but avoids a function call. + queue[queue.length] = task; +} + +var queue = []; +// Once a flush has been requested, no further calls to `requestFlush` are +// necessary until the next `flush` completes. +var flushing = false; +// `requestFlush` is an implementation-specific method that attempts to kick +// off a `flush` event as quickly as possible. `flush` will attempt to exhaust +// the event queue before yielding to the browser's own event loop. +var requestFlush; +// The position of the next task to execute in the task queue. This is +// preserved between calls to `flush` so that it can be resumed if +// a task throws an exception. +var index = 0; +// If a task schedules additional tasks recursively, the task queue can grow +// unbounded. To prevent memory exhaustion, the task queue will periodically +// truncate already-completed tasks. +var capacity = 1024; + +// The flush function processes all tasks that have been scheduled with +// `rawAsap` unless and until one of those tasks throws an exception. +// If a task throws an exception, `flush` ensures that its state will remain +// consistent and will resume where it left off when called again. +// However, `flush` does not make any arrangements to be called again if an +// exception is thrown. +function flush() { + while (index < queue.length) { + var currentIndex = index; + // Advance the index before calling the task. This ensures that we will + // begin flushing on the next task the task throws an error. + index = index + 1; + queue[currentIndex].call(); + // Prevent leaking memory for long chains of recursive calls to `asap`. + // If we call `asap` within tasks scheduled by `asap`, the queue will + // grow, but to avoid an O(n) walk for every task we execute, we don't + // shift tasks off the queue after they have been executed. + // Instead, we periodically shift 1024 tasks off the queue. + if (index > capacity) { + // Manually shift all values starting at the index back to the + // beginning of the queue. + for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { + queue[scan] = queue[scan + index]; + } + queue.length -= index; + index = 0; + } + } + queue.length = 0; + index = 0; + flushing = false; +} + +// `requestFlush` is implemented using a strategy based on data collected from +// every available SauceLabs Selenium web driver worker at time of writing. +// https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593 + +// Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that +// have WebKitMutationObserver but not un-prefixed MutationObserver. +// Must use `global` or `self` instead of `window` to work in both frames and web +// workers. `global` is a provision of Browserify, Mr, Mrs, or Mop. + +/* globals self */ +var scope = typeof global !== "undefined" ? global : self; +var BrowserMutationObserver = scope.MutationObserver || scope.WebKitMutationObserver; + +// MutationObservers are desirable because they have high priority and work +// reliably everywhere they are implemented. +// They are implemented in all modern browsers. +// +// - Android 4-4.3 +// - Chrome 26-34 +// - Firefox 14-29 +// - Internet Explorer 11 +// - iPad Safari 6-7.1 +// - iPhone Safari 7-7.1 +// - Safari 6-7 +if (typeof BrowserMutationObserver === "function") { + requestFlush = makeRequestCallFromMutationObserver(flush); + +// MessageChannels are desirable because they give direct access to the HTML +// task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera +// 11-12, and in web workers in many engines. +// Although message channels yield to any queued rendering and IO tasks, they +// would be better than imposing the 4ms delay of timers. +// However, they do not work reliably in Internet Explorer or Safari. + +// Internet Explorer 10 is the only browser that has setImmediate but does +// not have MutationObservers. +// Although setImmediate yields to the browser's renderer, it would be +// preferrable to falling back to setTimeout since it does not have +// the minimum 4ms penalty. +// Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and +// Desktop to a lesser extent) that renders both setImmediate and +// MessageChannel useless for the purposes of ASAP. +// https://github.com/kriskowal/q/issues/396 + +// Timers are implemented universally. +// We fall back to timers in workers in most engines, and in foreground +// contexts in the following browsers. +// However, note that even this simple case requires nuances to operate in a +// broad spectrum of browsers. +// +// - Firefox 3-13 +// - Internet Explorer 6-9 +// - iPad Safari 4.3 +// - Lynx 2.8.7 +} else { + requestFlush = makeRequestCallFromTimer(flush); +} + +// `requestFlush` requests that the high priority event queue be flushed as +// soon as possible. +// This is useful to prevent an error thrown in a task from stalling the event +// queue if the exception handled by Node.js’s +// `process.on("uncaughtException")` or by a domain. +rawAsap.requestFlush = requestFlush; + +// To request a high priority event, we induce a mutation observer by toggling +// the text of a text node between "1" and "-1". +function makeRequestCallFromMutationObserver(callback) { + var toggle = 1; + var observer = new BrowserMutationObserver(callback); + var node = document.createTextNode(""); + observer.observe(node, {characterData: true}); + return function requestCall() { + toggle = -toggle; + node.data = toggle; + }; +} + +// The message channel technique was discovered by Malte Ubl and was the +// original foundation for this library. +// http://www.nonblocking.io/2011/06/windownexttick.html + +// Safari 6.0.5 (at least) intermittently fails to create message ports on a +// page's first load. Thankfully, this version of Safari supports +// MutationObservers, so we don't need to fall back in that case. + +// function makeRequestCallFromMessageChannel(callback) { +// var channel = new MessageChannel(); +// channel.port1.onmessage = callback; +// return function requestCall() { +// channel.port2.postMessage(0); +// }; +// } + +// For reasons explained above, we are also unable to use `setImmediate` +// under any circumstances. +// Even if we were, there is another bug in Internet Explorer 10. +// It is not sufficient to assign `setImmediate` to `requestFlush` because +// `setImmediate` must be called *by name* and therefore must be wrapped in a +// closure. +// Never forget. + +// function makeRequestCallFromSetImmediate(callback) { +// return function requestCall() { +// setImmediate(callback); +// }; +// } + +// Safari 6.0 has a problem where timers will get lost while the user is +// scrolling. This problem does not impact ASAP because Safari 6.0 supports +// mutation observers, so that implementation is used instead. +// However, if we ever elect to use timers in Safari, the prevalent work-around +// is to add a scroll event listener that calls for a flush. + +// `setTimeout` does not call the passed callback if the delay is less than +// approximately 7 in web workers in Firefox 8 through 18, and sometimes not +// even then. + +function makeRequestCallFromTimer(callback) { + return function requestCall() { + // We dispatch a timeout with a specified delay of 0 for engines that + // can reliably accommodate that request. This will usually be snapped + // to a 4 milisecond delay, but once we're flushing, there's no delay + // between events. + var timeoutHandle = setTimeout(handleTimer, 0); + // However, since this timer gets frequently dropped in Firefox + // workers, we enlist an interval handle that will try to fire + // an event 20 times per second until it succeeds. + var intervalHandle = setInterval(handleTimer, 50); + + function handleTimer() { + // Whichever timer succeeds will cancel both timers and + // execute the callback. + clearTimeout(timeoutHandle); + clearInterval(intervalHandle); + callback(); + } + }; +} + +// This is for `asap.js` only. +// Its name will be periodically randomized to break any code that depends on +// its existence. +rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer; + +// ASAP was originally a nextTick shim included in Q. This was factored out +// into this ASAP package. It was later adapted to RSVP which made further +// amendments. These decisions, particularly to marginalize MessageChannel and +// to capture the MutationObserver implementation in a closure, were integrated +// back into ASAP proper. +// https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js diff --git a/node_modules/asap/package.json b/node_modules/asap/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ae9f303bcd15db6709cadc34cc13ab79e0aa2177 --- /dev/null +++ b/node_modules/asap/package.json @@ -0,0 +1,58 @@ +{ + "name": "asap", + "version": "2.0.6", + "description": "High-priority task queue for Node.js and browsers", + "keywords": [ + "event", + "task", + "queue" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/kriskowal/asap.git" + }, + "main": "./asap.js", + "browser": { + "./asap": "./browser-asap.js", + "./asap.js": "./browser-asap.js", + "./raw": "./browser-raw.js", + "./raw.js": "./browser-raw.js", + "./test/domain.js": "./test/browser-domain.js" + }, + "react-native": { + "domain": false + }, + "files": [ + "raw.js", + "asap.js", + "browser-raw.js", + "browser-asap.js" + ], + "scripts": { + "test": "npm run lint && npm run test-node", + "test-travis": "npm run lint && npm run test-node && npm run test-saucelabs && npm run test-saucelabs-worker", + "test-node": "node test/asap-test.js", + "test-publish": "node scripts/publish-bundle.js test/asap-test.js | pbcopy", + "test-browser": "node scripts/publish-bundle.js test/asap-test.js | xargs opener", + "test-saucelabs": "node scripts/saucelabs.js test/asap-test.js scripts/saucelabs-spot-configurations.json", + "test-saucelabs-all": "node scripts/saucelabs.js test/asap-test.js scripts/saucelabs-all-configurations.json", + "test-saucelabs-worker": "node scripts/saucelabs-worker-test.js scripts/saucelabs-spot-configurations.json", + "test-saucelabs-worker-all": "node scripts/saucelabs-worker-test.js scripts/saucelabs-all-configurations.json", + "lint": "jshint raw.js asap.js browser-raw.js browser-asap.js $(find scripts -name '*.js' | grep -v gauntlet)", + "benchmarks": "node benchmarks" + }, + "devDependencies": { + "events": "^1.0.1", + "jshint": "^2.5.1", + "knox": "^0.8.10", + "mr": "^2.0.5", + "opener": "^1.3.0", + "q": "^2.0.3", + "q-io": "^2.0.3", + "saucelabs": "^0.1.1", + "wd": "^0.2.21", + "weak-map": "^1.0.5", + "benchmark": "^1.0.0" + } +} diff --git a/node_modules/asap/raw.js b/node_modules/asap/raw.js new file mode 100644 index 0000000000000000000000000000000000000000..ae3b892316842335650bd09582d86fc53f29e64b --- /dev/null +++ b/node_modules/asap/raw.js @@ -0,0 +1,101 @@ +"use strict"; + +var domain; // The domain module is executed on demand +var hasSetImmediate = typeof setImmediate === "function"; + +// Use the fastest means possible to execute a task in its own turn, with +// priority over other events including network IO events in Node.js. +// +// An exception thrown by a task will permanently interrupt the processing of +// subsequent tasks. The higher level `asap` function ensures that if an +// exception is thrown by a task, that the task queue will continue flushing as +// soon as possible, but if you use `rawAsap` directly, you are responsible to +// either ensure that no exceptions are thrown from your task, or to manually +// call `rawAsap.requestFlush` if an exception is thrown. +module.exports = rawAsap; +function rawAsap(task) { + if (!queue.length) { + requestFlush(); + flushing = true; + } + // Avoids a function call + queue[queue.length] = task; +} + +var queue = []; +// Once a flush has been requested, no further calls to `requestFlush` are +// necessary until the next `flush` completes. +var flushing = false; +// The position of the next task to execute in the task queue. This is +// preserved between calls to `flush` so that it can be resumed if +// a task throws an exception. +var index = 0; +// If a task schedules additional tasks recursively, the task queue can grow +// unbounded. To prevent memory excaustion, the task queue will periodically +// truncate already-completed tasks. +var capacity = 1024; + +// The flush function processes all tasks that have been scheduled with +// `rawAsap` unless and until one of those tasks throws an exception. +// If a task throws an exception, `flush` ensures that its state will remain +// consistent and will resume where it left off when called again. +// However, `flush` does not make any arrangements to be called again if an +// exception is thrown. +function flush() { + while (index < queue.length) { + var currentIndex = index; + // Advance the index before calling the task. This ensures that we will + // begin flushing on the next task the task throws an error. + index = index + 1; + queue[currentIndex].call(); + // Prevent leaking memory for long chains of recursive calls to `asap`. + // If we call `asap` within tasks scheduled by `asap`, the queue will + // grow, but to avoid an O(n) walk for every task we execute, we don't + // shift tasks off the queue after they have been executed. + // Instead, we periodically shift 1024 tasks off the queue. + if (index > capacity) { + // Manually shift all values starting at the index back to the + // beginning of the queue. + for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { + queue[scan] = queue[scan + index]; + } + queue.length -= index; + index = 0; + } + } + queue.length = 0; + index = 0; + flushing = false; +} + +rawAsap.requestFlush = requestFlush; +function requestFlush() { + // Ensure flushing is not bound to any domain. + // It is not sufficient to exit the domain, because domains exist on a stack. + // To execute code outside of any domain, the following dance is necessary. + var parentDomain = process.domain; + if (parentDomain) { + if (!domain) { + // Lazy execute the domain module. + // Only employed if the user elects to use domains. + domain = require("domain"); + } + domain.active = process.domain = null; + } + + // `setImmediate` is slower that `process.nextTick`, but `process.nextTick` + // cannot handle recursion. + // `requestFlush` will only be called recursively from `asap.js`, to resume + // flushing after an error is thrown into a domain. + // Conveniently, `setImmediate` was introduced in the same version + // `process.nextTick` started throwing recursion errors. + if (flushing && hasSetImmediate) { + setImmediate(flush); + } else { + process.nextTick(flush); + } + + if (parentDomain) { + domain.active = process.domain = parentDomain; + } +} diff --git a/node_modules/asn1js/LICENSE b/node_modules/asn1js/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8d571903292029c7c7ce48747b0d63908f6e4f6d --- /dev/null +++ b/node_modules/asn1js/LICENSE @@ -0,0 +1,30 @@ +Copyright (c) 2014, GMO GlobalSign +Copyright (c) 2015-2022, Peculiar Ventures +All rights reserved. + +Author 2014-2019, Yury Strozhevsky + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/asn1js/README.md b/node_modules/asn1js/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f721fa0b1065fae13818db50de64175b6898f22d --- /dev/null +++ b/node_modules/asn1js/README.md @@ -0,0 +1,204 @@ +

+ ASN1js +

+ +
+ +![NPM License](https://img.shields.io/npm/l/asn1js) +![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/PeculiarVentures/ASN1.js/test.yml?label=test) +[![npm version](https://img.shields.io/npm/v/asn1js.svg)](https://www.npmjs.com/package/asn1js) +![Coveralls](https://img.shields.io/coverallsCoverage/github/PeculiarVentures/ASN1.js) +[![npm downloads](https://img.shields.io/npm/dm/asn1js.svg)](https://www.npmjs.com/package/asn1js) + +
+ +Abstract Syntax Notation One (ASN.1) is a standard and notation that describes rules and structures for representing, encoding, transmitting, and decoding data in telecommunications and computer networking. [ASN1js] is a pure JavaScript library implementing this standard. ASN.1 is the basis of all X.509 related data structures and numerous other protocols used on the web. + +## Important Information for ASN1.js V1 Users + +ASN1.js V2 (ES2015 version) is **incompatible** with ASN1.js V1 code. + +## Introduction + +[ASN1js] is the first library for [BER] encoding/decoding in Javascript designed for browser use. [BER] is the basic encoding rules for [ASN.1] that all others are based on, [DER] is the encoding rules used by PKI applications - it is a subset of [BER]. The [ASN1js] library was tested against [freely available ASN.1:2008 test suite], with some limitations related to JavaScript language. + +## Features of the library + +* Based on latest features of JavaScript language from ES2015 standard; +* [ASN1js] is a "base layer" for full-featured JS library [PKIjs], which is using Web Cryptography API and has all classes, necessary to work with PKI-related data; +* Fully object-oriented library. Inheritance is using everywhere inside the lib; +* Working with HTML5 data objects (ArrayBuffer, Uint8Array etc.); +* Working with all ASN.1:2008 types; +* Working with [BER] encoded data; +* All types inside the library constantly stores information about all ASN.1 sub blocks (tag block, length block or value block); +* User may have access to any byte inside any ASN.1 sub-block; +* Any sub-block may have unlimited length, as it described in ASN.1 standard (even "tag block"); +* Ability to work with ASN.1 string date types (including all "international" strings like UniversalString, BMPString, UTF8String) by passing native JavaScript strings into constructors. And vice versa - all initially parsed data of ASN.1 string types right after decoding automatically converts into native JavaScript strings; +* Same with ASN.1 date-time types: for major types like UTCTime and GeneralizedTime there are automatic conversion between "JS date type - ASN.1 date-time type" + vice versa; +* Same with ASN.1 OBJECT-IDENTIFIER (OID) data-type: you can initialize OID by JavaScript string and can get string representation via calling "oid.valueBlock.toString()"; +* Working with "easy-to-understand" ASN.1 schemas (pre-defined or built by user); +* Has special types to work with ASN.1 schemas: + * Any + * Choice + * Repeated +* User can name any block inside ASN.1 schema and easily get information by name; +* Ability to parse internal data inside a primitively encoded data types and automatically validate it against special schema; +* All types inside library are dynamic; +* All types can be initialized in static or dynamic ways. +* [ASN1js] fully tested against [ASN.1:2008 TestSuite]. + +## Examples + +### How to create new ASN. structures + +```javascript +var sequence = new asn1js.Sequence(); +sequence.valueBlock.value.push(new asn1js.Integer({ value: 1 })); + +var sequence_buffer = sequence.toBER(false); // Encode current sequence to BER (in ArrayBuffer) +var current_size = sequence_buffer.byteLength; + +var integer_data = new ArrayBuffer(8); +var integer_view = new Uint8Array(integer_data); +integer_view[0] = 0x01; +integer_view[1] = 0x01; +integer_view[2] = 0x01; +integer_view[3] = 0x01; +integer_view[4] = 0x01; +integer_view[5] = 0x01; +integer_view[6] = 0x01; +integer_view[7] = 0x01; + +sequence.valueBlock.value.push(new asn1js.Integer({ + isHexOnly: true, + valueHex: integer_data, +})); // Put too long for decoding Integer value + +sequence_buffer = sequence.toBER(); +current_size = sequence_buffer.byteLength; +``` + +### How to create new ASN.1 structures by calling constructors with parameters + +```javascript +var sequence2 = new asn1js.Sequence({ + value: [ + new asn1js.Integer({ value: 1 }), + new asn1js.Integer({ + isHexOnly: true, + valueHex: integer_data + }), + ] +}); +``` + +### How to validate ASN.1 against pre-defined schema + +```javascript +var asn1_schema = new asn1js.Sequence({ + name: "block1", + value: [ + new asn1js.Null({ + name: "block2" + }), + new asn1js.Integer({ + name: "block3", + optional: true // This block is absent inside data, but it's "optional". Hence verification against the schema will be passed. + }) + ] +}); + +var variant1 = asn1js.verifySchema(encoded_sequence, asn1_schema); // Verify schema together with decoding of raw data +var variant1_verified = variant1.verified; +var variant1_result = variant1.result; // Verified decoded data with all block names inside +``` + +### How to use "internal schemas" for primitively encoded data types + +```javascript +var primitive_octetstring = new asn1js.OctetString({ valueHex: encoded_sequence }); // Create a primitively encoded OctetString where internal data is an encoded Sequence + +var asn1_schema_internal = new asn1js.OctetString({ + name: "outer_block", + primitiveSchema: new asn1js.Sequence({ + name: "block1", + value: [ + new asn1js.Null({ + name: "block2" + }) + ] + }) +}); + +var variant6 = asn1js.compareSchema(primitive_octetstring, primitive_octetstring, asn1_schema_internal); +var variant6_verified = variant4.verified; +var variant6_block1_tag_num = variant6.result.block1.idBlock.tagNumber; +var variant6_block2_tag_num = variant6.result.block2.idBlock.tagNumber; +``` + +More examples could be found in "examples" directory or inside [PKIjs] library. + +## Parsing Untrusted Input + +`fromBER()` accepts optional parser resource limits for untrusted ASN.1 input. + +```typescript +const asn1 = asn1js.fromBER(inputBuffer, { + maxDepth: 100, + maxNodes: 10000, + maxContentLength: 16 * 1024 * 1024, +}); +``` + +When any limit is exceeded the parser returns a normal `FromBerResult` error instead of exhausting the JavaScript stack or continuing to parse excessive input. + +## Related source code + +* [C++ ASN1:2008 BER coder/decoder](https://github.com/YuryStrozhevsky/C-plus-plus-ASN.1-2008-coder-decoder) - the "father" of [ASN1js] project; +* [Freely available ASN.1:2008 test suite](https://github.com/YuryStrozhevsky/ASN1-2008-free-test-suite) - the suite which can help you to validate (and better understand) any ASN.1 coder/decoder; +* [NPM package for ASN.1:2008 test suite](https://github.com/YuryStrozhevsky/asn1-test-suite) + +## Suitability + +There are several commercial products, enterprise solutions as well as open source project based on versions of ASN1js. You should, however, do your own code and security review before utilization in a production application before utilizing any open source library to ensure it will meet your needs. + +## License + +Copyright (c) 2014, [GMO GlobalSign](http://www.globalsign.com/) +Copyright (c) 2015-2022, [Peculiar Ventures](http://peculiarventures.com/) +All rights reserved. + +Author 2014-2018, [Yury Strozhevsky](http://www.strozhevsky.com/). + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY +OF SUCH DAMAGE. + +[ASN.1]: http://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One +[ASN1js]: http://asn1js.org/ +[PKIjs]: http://pkijs.org/ +[BER]: http://en.wikipedia.org/wiki/X.690#BER_encoding +[DER]: http://en.wikipedia.org/wiki/X.690#DER_encoding +[freely available ASN.1:2008 test suite]: http://www.strozhevsky.com/free_docs/free_asn1_testsuite_descr.pdf +[ASN.1:2008 TestSuite]: https://github.com/YuryStrozhevsky/asn1-test-suite diff --git a/node_modules/asn1js/build/index.d.ts b/node_modules/asn1js/build/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..03c8bb56de8b5407a7c2e79fecce40c4799cc44b --- /dev/null +++ b/node_modules/asn1js/build/index.d.ts @@ -0,0 +1,1366 @@ +/*! + * Copyright (c) 2014, GMO GlobalSign + * Copyright (c) 2015-2022, Peculiar Ventures + * All rights reserved. + * + * Author 2014-2019, Yury Strozhevsky + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * * Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +import * as pvtsutils from 'pvtsutils'; + +interface IBerConvertible { + /** + * Base function for converting block from BER encoded array of bytes + * @param inputBuffer ASN.1 BER encoded array + * @param inputOffset Offset in ASN.1 BER encoded array where decoding should be started + * @param inputLength Maximum length of array of bytes which can be using in this function + * @returns Offset after least decoded byte + */ + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + /** + * Encoding of current ASN.1 block into ASN.1 encoded array (BER rules) + * @param sizeOnly Flag that we need only a size of encoding, not a real array of bytes + * @returns ASN.1 BER encoded array + */ + toBER(sizeOnly?: boolean): ArrayBuffer; +} +interface IDerConvertible { + /** + * Base function for converting block from DER encoded array of bytes + * @param inputBuffer ASN.1 DER encoded array + * @param inputOffset Offset in ASN.1 DER encoded array where decoding should be started + * @param inputLength Maximum length of array of bytes which can be using in this function + * @param expectedLength Expected length of converted VALUE_HEX buffer + * @returns Offset after least decoded byte + */ + fromDER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number, expectedLength?: number): number; + /** + * Encoding of current ASN.1 block into ASN.1 encoded array (DER rules) + * @param sizeOnly Flag that we need only a size of encoding, not a real array of bytes + * @returns ASN.1 DER encoded array + */ + toDER(sizeOnly?: boolean): ArrayBuffer; +} +interface IStringConvertible { + /** + * Returns a string representation of an object + * @returns String representation of the class object + */ + toString(): string; + /** + * Creates a class object from the string + * @param data Input string to convert from + */ + fromString(data: string): void; +} +interface IDateConvertible { + /** + * Converts a class object into the JavaScrip Date Object + * @returns Date object + */ + toDate(): Date; + /** + * Creates a class object from the JavaScript Date object + * @param date Date object + */ + fromDate(date: Date): void; +} + +declare class ViewWriter { + items: ArrayBuffer[]; + /** + * Writes buffer + * @param buf + */ + write(buf: ArrayBuffer): void; + /** + * Concatenates all buffers + * @returns Concatenated buffer + */ + final(): ArrayBuffer; +} + +interface ILocalBaseBlock { + blockLength: number; + error: string; + warnings: string[]; +} +interface LocalBaseBlockJson extends ILocalBaseBlock { + blockName: string; + valueBeforeDecode: string; +} +interface LocalBaseBlockParams extends Partial { + valueBeforeDecode?: pvtsutils.BufferSource; +} +interface LocalBaseBlockConstructor { + new (...args: any[]): T; + prototype: T; + NAME: string; + blockName(): string; +} +/** + * Class used as a base block for all remaining ASN.1 classes + */ +declare class LocalBaseBlock implements ILocalBaseBlock { + /** + * Name of the block + */ + static NAME: string; + /** + * Aux function, need to get a block name. Need to have it here for inheritance + * @returns Returns name of the block + */ + static blockName(): string; + blockLength: number; + error: string; + warnings: string[]; + /** + * @deprecated since version 3.0.0 + */ + get valueBeforeDecode(): ArrayBuffer; + /** + * @deprecated since version 3.0.0 + */ + set valueBeforeDecode(value: ArrayBuffer); + /** + * @since 3.0.0 + */ + valueBeforeDecodeView: Uint8Array; + /** + * Creates and initializes an object instance of that class + * @param param0 Initialization parameters + */ + constructor({ blockLength, error, warnings, valueBeforeDecode, }?: LocalBaseBlockParams); + /** + * Returns a JSON representation of an object + * @returns JSON object + */ + toJSON(): LocalBaseBlockJson; +} + +interface IHexBlock { + isHexOnly: boolean; + valueHex: pvtsutils.BufferSource; +} +interface HexBlockJson extends Omit { + valueHex: string; +} +type HexBlockParams = Partial; +/** + * Class used as a base block for all remaining ASN.1 classes + */ +declare function HexBlock(BaseClass: T): { + new (...args: any[]): { + isHexOnly: boolean; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; + /** + * Binary data in Uint8Array representation + * + * @since 3.0.0 + */ + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number, _context?: unknown): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + /** + * Returns a JSON representation of an object + * @returns JSON object + */ + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & T; + +type IValueBlock = ILocalBaseBlock; +type ValueBlockParams = LocalBaseBlockParams; +type ValueBlockJson = LocalBaseBlockJson; +declare class ValueBlock extends LocalBaseBlock implements IValueBlock, IBerConvertible { + static NAME: string; + fromBER(_inputBuffer: ArrayBuffer | Uint8Array, _inputOffset: number, _inputLength: number, _context?: unknown): number; + toBER(_sizeOnly?: boolean, _writer?: ViewWriter): ArrayBuffer; +} + +interface ILocalIdentificationBlock { + tagClass: number; + tagNumber: number; + isConstructed: boolean; +} +interface LocalIdentificationBlockParams { + idBlock?: Partial & HexBlockParams; +} +interface LocalIdentificationBlockJson extends HexBlockJson, LocalBaseBlockJson, ILocalIdentificationBlock { +} +declare const LocalIdentificationBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number, _context?: unknown): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof LocalBaseBlock; +declare class LocalIdentificationBlock extends LocalIdentificationBlock_base implements ILocalIdentificationBlock { + static NAME: string; + tagClass: number; + tagNumber: number; + isConstructed: boolean; + constructor({ idBlock }?: LocalIdentificationBlockParams); + toBER(sizeOnly?: boolean): ArrayBuffer; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toJSON(): LocalIdentificationBlockJson; +} +interface LocalIdentificationBlock { + /** + * @deprecated since version 3.0.0 + */ + valueBeforeDecode: ArrayBuffer; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; +} + +interface ILocalLengthBlock { + isIndefiniteForm: boolean; + longFormUsed: boolean; + length: number; +} +interface LocalLengthBlockParams { + lenBlock?: Partial; +} +interface LocalLengthBlockJson extends LocalBaseBlockJson, ILocalLengthBlock { + isIndefiniteForm: boolean; + longFormUsed: boolean; + length: number; +} +declare class LocalLengthBlock extends LocalBaseBlock implements ILocalLengthBlock, IBerConvertible { + static NAME: string; + isIndefiniteForm: boolean; + longFormUsed: boolean; + length: number; + constructor({ lenBlock }?: LocalLengthBlockParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): LocalLengthBlockJson; +} + +interface IAny { + name: string; + optional: boolean; +} +type AnyParams = Partial; +declare class Any implements IAny { + name: string; + optional: boolean; + constructor({ name, optional }?: AnyParams); +} + +type ConstructedItem = BaseBlock | Any; +interface ILocalConstructedValueBlock { + value: ConstructedItem[]; + isIndefiniteForm: boolean; +} +interface LocalConstructedValueBlockParams extends ValueBlockParams, Partial { +} +interface LocalConstructedValueBlockJson extends LocalBaseBlockJson, Omit { + value: LocalBaseBlockJson[]; +} +declare class LocalConstructedValueBlock extends ValueBlock implements ILocalConstructedValueBlock { + static NAME: string; + value: BaseBlock[]; + isIndefiniteForm: boolean; + constructor({ value, isIndefiniteForm, ...parameters }?: LocalConstructedValueBlockParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number, context?: FromBerContext): number; + toBER(sizeOnly?: boolean, writer?: ViewWriter): ArrayBuffer; + toJSON(): LocalConstructedValueBlockJson; +} + +interface ILocalBitStringValueBlock { + unusedBits: number; + isConstructed: boolean; +} +interface LocalBitStringValueBlockParams extends HexBlockParams, LocalConstructedValueBlockParams, Partial { + value?: BitString[]; +} +interface LocalBitStringValueBlockJson extends HexBlockJson, LocalConstructedValueBlockJson, ILocalBitStringValueBlock { +} +declare const LocalBitStringValueBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number, _context?: unknown): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof LocalConstructedValueBlock; +declare class LocalBitStringValueBlock extends LocalBitStringValueBlock_base implements ILocalBitStringValueBlock { + static NAME: string; + unusedBits: number; + isConstructed: boolean; + constructor({ unusedBits, isConstructed, ...parameters }?: LocalBitStringValueBlockParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number, context?: FromBerContext): number; + toBER(sizeOnly?: boolean, writer?: ViewWriter): ArrayBuffer; + toJSON(): LocalBitStringValueBlockJson; +} +interface LocalBitStringValueBlock { + /** + * @deprecated since version 3.0.0 + */ + valueBeforeDecode: ArrayBuffer; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; +} + +interface BitStringParams extends BaseBlockParams, LocalBitStringValueBlockParams { +} +type BitStringJson = BaseBlockJson; +declare class BitString extends BaseBlock { + static NAME: string; + constructor({ idBlock, lenBlock, ...parameters }?: BitStringParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number, context?: FromBerContext): number; + protected onAsciiEncoding(): string; +} + +type LocalUtf8StringValueBlockParams = LocalSimpleStringBlockParams; +type LocalUtf8StringValueBlockJson = LocalSimpleStringBlockJson; +declare class LocalUtf8StringValueBlock extends LocalSimpleStringBlock { + static NAME: string; + fromBuffer(inputBuffer: ArrayBuffer | Uint8Array): void; + fromString(inputString: string): void; +} + +interface ILocalStringValueBlock { + value: string; +} +interface LocalStringValueBlockParams extends Omit, ValueBlockParams, Partial { +} +interface LocalStringValueBlockJson extends HexBlockJson, ValueBlockJson, ILocalStringValueBlock { +} +declare const LocalStringValueBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number, _context?: unknown): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof ValueBlock; +declare abstract class LocalStringValueBlock extends LocalStringValueBlock_base implements ILocalStringValueBlock { + static NAME: string; + value: string; + constructor({ ...parameters }?: LocalUtf8StringValueBlockParams); + toJSON(): LocalUtf8StringValueBlockJson; +} +interface LocalStringValueBlock { + /** + * @deprecated since version 3.0.0 + */ + valueBeforeDecode: ArrayBuffer; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; +} + +interface BaseStringBlockParams extends BaseBlockParams, LocalStringValueBlockParams { +} +type BaseStringBlockJson = LocalStringValueBlockJson; +declare abstract class BaseStringBlock extends BaseBlock implements IStringConvertible { + static NAME: string; + /** + * String value + * @since 3.0.0 + */ + getValue(): string; + /** + * String value + * @param value String value + * @since 3.0.0 + */ + setValue(value: string): void; + constructor({ value, ...parameters }: BaseStringBlockParams | undefined, stringValueBlockType: new () => T); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + /** + * Function converting ArrayBuffer into ASN.1 internal string + * @param inputBuffer ASN.1 BER encoded array + */ + abstract fromBuffer(inputBuffer: ArrayBuffer | Uint8Array): void; + abstract fromString(inputString: string): void; + protected onAsciiEncoding(): string; +} + +type LocalSimpleStringValueBlockParams = LocalStringValueBlockParams; +type LocalSimpleStringValueBlockJson = LocalStringValueBlockJson; +declare class LocalSimpleStringValueBlock extends LocalStringValueBlock { + static NAME: string; +} + +interface LocalSimpleStringBlockParams extends BaseBlockParams, LocalSimpleStringValueBlockParams { +} +type LocalSimpleStringBlockJson = LocalSimpleStringValueBlockJson; +declare class LocalSimpleStringBlock extends BaseStringBlock { + static NAME: string; + constructor({ ...parameters }?: LocalSimpleStringBlockParams); + fromBuffer(inputBuffer: ArrayBuffer | Uint8Array): void; + fromString(inputString: string): void; +} + +type LocalBmpStringValueBlockParams = LocalSimpleStringBlockParams; +type LocalBmpStringValueBlockJson = LocalSimpleStringBlockJson; +declare class LocalBmpStringValueBlock extends LocalSimpleStringBlock { + static NAME: string; + fromBuffer(inputBuffer: ArrayBuffer | Uint8Array): void; + fromString(inputString: string): void; +} + +type BmpStringParams = LocalBmpStringValueBlockParams; +type BmpStringJson = LocalBmpStringValueBlockJson; +declare class BmpString extends LocalBmpStringValueBlock { + static NAME: string; + constructor({ ...parameters }?: BmpStringParams); +} + +interface ILocalBooleanValueBlock { + value: boolean; +} +interface LocalBooleanValueBlockParams extends ValueBlockParams, HexBlockParams, Partial { +} +interface LocalBooleanValueBlockJson extends ValueBlockJson, HexBlockJson, ILocalBooleanValueBlock { +} +declare const LocalBooleanValueBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number, _context?: unknown): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof ValueBlock; +declare class LocalBooleanValueBlock extends LocalBooleanValueBlock_base implements ILocalBooleanValueBlock { + static NAME: string; + get value(): boolean; + set value(value: boolean); + constructor({ value, ...parameters }?: LocalBooleanValueBlockParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(): ArrayBuffer; + toJSON(): LocalBooleanValueBlockJson; +} +interface LocalBooleanValueBlock { + /** + * @deprecated since version 3.0.0 + */ + valueBeforeDecode: ArrayBuffer; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; +} + +interface BooleanParams extends BaseBlockParams, LocalBooleanValueBlockParams { +} +type BooleanJson = BaseBlockJson; +declare class Boolean extends BaseBlock { + /** + * Gets value + * @since 3.0.0 + */ + getValue(): boolean; + /** + * Sets value + * @param value Boolean value + * @since 3.0.0 + */ + setValue(value: boolean): void; + static NAME: string; + constructor(parameters?: BooleanParams); + protected onAsciiEncoding(): string; +} + +type CharacterStringParams = LocalSimpleStringBlockParams; +type CharacterStringJson = LocalSimpleStringBlockJson; +declare class CharacterString extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: CharacterStringParams); +} + +interface ConstructedParams extends BaseBlockParams, LocalConstructedValueBlockParams { +} +type ConstructedJson = BaseBlockJson; +declare class Constructed extends BaseBlock { + static NAME: string; + constructor(parameters?: ConstructedParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number, context?: FromBerContext): number; +} + +interface Utf8StringParams extends BaseStringBlockParams, LocalUtf8StringValueBlockParams { +} +type Utf8StringJson = BaseBlockJson; +declare class Utf8String extends LocalUtf8StringValueBlock { + static NAME: string; + constructor(parameters?: Utf8StringParams); +} + +type DATEParams = Utf8StringParams; +type DATEJson = Utf8StringJson; +declare class DATE extends Utf8String { + static NAME: string; + constructor(parameters?: DATEParams); +} + +type DateTimeParams = Utf8StringParams; +type DateTimeJson = Utf8StringJson; +declare class DateTime extends Utf8String { + static NAME: string; + constructor(parameters?: DateTimeParams); +} + +type DurationParams = Utf8StringParams; +type DurationJson = Utf8StringJson; +declare class Duration extends Utf8String { + static NAME: string; + constructor(parameters?: DurationParams); +} + +declare class LocalEndOfContentValueBlock extends ValueBlock { + static override: string; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, _inputLength: number): number; + toBER(_sizeOnly?: boolean): ArrayBuffer; +} + +type EndOfContentParams = BaseBlockParams; +type EndOfContentJson = BaseBlockJson; +declare class EndOfContent extends BaseBlock { + static NAME: string; + constructor(parameters?: EndOfContentParams); +} + +interface ILocalIntegerValueBlock { + value: number; +} +interface LocalIntegerValueBlockParams extends HexBlockParams, ValueBlockParams, Partial { +} +interface LocalIntegerValueBlockJson extends HexBlockJson, ValueBlockJson { + valueDec: number; +} +declare const LocalIntegerValueBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number, _context?: unknown): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof ValueBlock; +declare class LocalIntegerValueBlock extends LocalIntegerValueBlock_base implements IDerConvertible { + protected setValueHex(): void; + static NAME: string; + private _valueDec; + constructor({ value, ...parameters }?: LocalIntegerValueBlockParams); + set valueDec(v: number); + get valueDec(): number; + fromDER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number, expectedLength?: number): number; + toDER(sizeOnly?: boolean): ArrayBuffer; + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): LocalIntegerValueBlockJson; + toString(): string; +} +interface LocalIntegerValueBlock { + /** + * @deprecated since version 3.0.0 + */ + valueBeforeDecode: ArrayBuffer; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; +} + +interface IntegerParams extends BaseBlockParams, LocalIntegerValueBlockParams { +} +type IntegerJson = BaseBlockJson; +declare class Integer extends BaseBlock { + static NAME: string; + constructor(parameters?: IntegerParams); + /** + * Converts Integer into BigInt + * @throws Throws Error if BigInt is not supported + * @since 3.0.0 + */ + toBigInt(): bigint; + /** + * Creates Integer from BigInt value + * @param value BigInt value + * @returns ASN.1 Integer + * @throws Throws Error if BigInt is not supported + * @since 3.0.0 + */ + static fromBigInt(value: number | string | bigint | boolean): Integer; + convertToDER(): Integer; + /** + * Convert current Integer value from DER to BER format + * @returns + */ + convertFromDER(): Integer; + protected onAsciiEncoding(): string; +} + +type EnumeratedParams = IntegerParams; +type EnumeratedJson = IntegerJson; +declare class Enumerated extends Integer { + static NAME: string; + constructor(parameters?: EnumeratedParams); +} + +type VisibleStringParams = LocalSimpleStringBlockParams; +type VisibleStringJson = LocalSimpleStringBlockJson; +declare class VisibleString extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: VisibleStringParams); +} + +interface IUTCTime { + year: number; + month: number; + day: number; + hour: number; + minute: number; + second: number; +} +interface UTCTimeParams extends VisibleStringParams { + value?: string; + valueDate?: Date; +} +interface UTCTimeJson extends BaseBlockJson, IUTCTime { +} +type DateStringEncoding = StringEncoding | "iso"; +declare class UTCTime extends VisibleString implements IUTCTime, IDateConvertible { + static NAME: string; + year: number; + month: number; + day: number; + hour: number; + minute: number; + second: number; + constructor({ value, valueDate, ...parameters }?: UTCTimeParams); + fromBuffer(inputBuffer: ArrayBuffer | Uint8Array): void; + /** + * Function converting ASN.1 internal string into ArrayBuffer + * @returns + */ + toBuffer(): ArrayBuffer; + /** + * Function converting "Date" object into ASN.1 internal string + * @param {!Date} inputDate JavaScript "Date" object + */ + fromDate(inputDate: Date): void; + toDate(): Date; + fromString(inputString: string): void; + toString(encoding?: DateStringEncoding): string; + protected onAsciiEncoding(): string; + toJSON(): UTCTimeJson; +} + +interface IGeneralizedTime extends IUTCTime { + millisecond: number; +} +type GeneralizedTimeParams = UTCTimeParams; +interface GeneralizedTimeJson extends UTCTimeJson { + millisecond: number; +} +declare class GeneralizedTime extends UTCTime { + static NAME: string; + millisecond: number; + constructor(parameters?: GeneralizedTimeParams); + fromDate(inputDate: Date): void; + toDate(): Date; + fromString(inputString: string): void; + toString(encoding?: DateStringEncoding): string; + toJSON(): GeneralizedTimeJson; +} + +type GeneralStringParams = LocalSimpleStringBlockParams; +type GeneralStringJson = LocalSimpleStringBlockJson; +declare class GeneralString extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: GeneralStringParams); +} + +type GraphicStringParams = LocalSimpleStringBlockParams; +type GraphicStringJson = LocalSimpleStringBlockJson; +declare class GraphicString extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: GraphicStringParams); +} + +type IA5StringParams = LocalSimpleStringBlockParams; +type IA5StringJson = LocalSimpleStringBlockJson; +declare class IA5String extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: IA5StringParams); +} + +type NullParams = BaseBlockParams; +type NullJson = BaseBlockJson; +declare class Null extends BaseBlock { + static NAME: string; + constructor(parameters?: NullParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean, writer?: ViewWriter): ArrayBuffer; + protected onAsciiEncoding(): string; +} + +type NumericStringParams = LocalSimpleStringBlockParams; +type NumericStringJson = LocalSimpleStringBlockJson; +declare class NumericString extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: NumericStringParams); +} + +interface ILocalSidValueBlock { + valueDec: number; + isFirstSid: boolean; +} +interface LocalSidValueBlockParams extends HexBlockParams, ValueBlockParams, Partial { +} +interface LocalSidValueBlockJson extends HexBlockJson, ValueBlockJson, ILocalSidValueBlock { +} +declare const LocalSidValueBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number, _context?: unknown): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof ValueBlock; +declare class LocalSidValueBlock extends LocalSidValueBlock_base implements ILocalSidValueBlock { + static NAME: string; + valueDec: number; + isFirstSid: boolean; + constructor({ valueDec, isFirstSid, ...parameters }?: LocalSidValueBlockParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + set valueBigInt(value: bigint); + toBER(sizeOnly?: boolean): ArrayBuffer; + toString(): string; + toJSON(): LocalSidValueBlockJson; +} +interface LocalSidValueBlock { + /** + * @deprecated since version 3.0.0 + */ + valueBeforeDecode: ArrayBuffer; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; +} + +interface ILocalObjectIdentifierValueBlock { + value: string; +} +interface LocalObjectIdentifierValueBlockParams extends ValueBlockParams, Partial { +} +interface LocalObjectIdentifierValueBlockJson extends ValueBlockJson, ILocalObjectIdentifierValueBlock { + sidArray: LocalSidValueBlockJson[]; +} +declare class LocalObjectIdentifierValueBlock extends ValueBlock implements IStringConvertible { + static NAME: string; + value: LocalSidValueBlock[]; + constructor({ value, ...parameters }?: LocalObjectIdentifierValueBlockParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + fromString(string: string): void; + toString(): string; + toJSON(): LocalObjectIdentifierValueBlockJson; +} + +interface ObjectIdentifierParams extends BaseBlockParams, LocalObjectIdentifierValueBlockParams { +} +interface ObjectIdentifierJson extends BaseBlockJson { + value: string; +} +declare class ObjectIdentifier extends BaseBlock { + static NAME: string; + /** + * Gets string representation of Object Identifier + * @since 3.0.0 + */ + getValue(): string; + /** + * Sets Object Identifier value from string + * @param value String value + * @since 3.0.0 + */ + setValue(value: string): void; + constructor(parameters?: ObjectIdentifierParams); + protected onAsciiEncoding(): string; + toJSON(): ObjectIdentifierJson; +} + +interface ILocalOctetStringValueBlock { + isConstructed: boolean; +} +interface LocalOctetStringValueBlockParams extends HexBlockParams, LocalConstructedValueBlockParams, Partial { + value?: OctetString[]; +} +interface LocalOctetStringValueBlockJson extends HexBlockJson, LocalConstructedValueBlockJson, ILocalOctetStringValueBlock { +} +declare const LocalOctetStringValueBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number, _context?: unknown): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof LocalConstructedValueBlock; +declare class LocalOctetStringValueBlock extends LocalOctetStringValueBlock_base { + static NAME: string; + isConstructed: boolean; + constructor({ isConstructed, ...parameters }?: LocalOctetStringValueBlockParams); + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number, context?: FromBerContext): number; + toBER(sizeOnly?: boolean, writer?: ViewWriter): ArrayBuffer; + toJSON(): LocalOctetStringValueBlockJson; +} +interface LocalOctetStringValueBlock { + /** + * @deprecated since version 3.0.0 + */ + valueBeforeDecode: ArrayBuffer; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; +} + +interface OctetStringParams extends BaseBlockParams, LocalOctetStringValueBlockParams { +} +type OctetStringJson = BaseBlockJson; +declare class OctetString extends BaseBlock { + static NAME: string; + constructor({ idBlock, lenBlock, ...parameters }?: OctetStringParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number, context?: FromBerContext): number; + protected onAsciiEncoding(): string; + /** + * Returns OctetString value. If OctetString is constructed, returns concatenated internal OctetString values + * @returns Array buffer + * @since 3.0.0 + */ + getValue(): ArrayBuffer; +} + +interface LocalPrimitiveValueBlockParams extends HexBlockParams, ValueBlockParams { +} +interface LocalPrimitiveValueBlockJson extends HexBlockJson, ValueBlockJson { +} +declare const LocalPrimitiveValueBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number, _context?: unknown): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof ValueBlock; +declare class LocalPrimitiveValueBlock extends LocalPrimitiveValueBlock_base { + static NAME: string; + constructor({ isHexOnly, ...parameters }?: LocalPrimitiveValueBlockParams); +} +interface LocalPrimitiveValueBlock { + /** + * @deprecated since version 3.0.0 + */ + valueBeforeDecode: ArrayBuffer; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; +} + +interface PrimitiveParams extends BaseBlockParams, LocalPrimitiveValueBlockParams { +} +type PrimitiveJson = BaseBlockJson; +declare class Primitive extends BaseBlock { + static NAME: string; + constructor(parameters?: PrimitiveParams); +} + +type PrintableStringParams = LocalSimpleStringBlockParams; +type PrintableStringJson = LocalSimpleStringBlockJson; +declare class PrintableString extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: PrintableStringParams); +} + +interface ILocalRelativeSidValueBlock { + valueDec: number; +} +interface LocalRelativeSidValueBlockParams extends HexBlockParams, ValueBlockParams, Partial { +} +interface LocalRelativeSidValueBlockJson extends HexBlockJson, ValueBlockJson, ILocalRelativeSidValueBlock { +} +declare const LocalRelativeSidValueBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number, _context?: unknown): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof LocalBaseBlock; +declare class LocalRelativeSidValueBlock extends LocalRelativeSidValueBlock_base implements ILocalRelativeSidValueBlock { + static NAME: string; + valueDec: number; + constructor({ valueDec, ...parameters }?: LocalRelativeSidValueBlockParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toString(): string; + toJSON(): LocalRelativeSidValueBlockJson; +} + +interface ILocalRelativeObjectIdentifierValueBlock { + value: string; +} +interface LocalRelativeObjectIdentifierValueBlockParams extends ValueBlockParams, Partial { +} +interface LocalRelativeObjectIdentifierValueBlockJson extends ValueBlockJson, ILocalRelativeObjectIdentifierValueBlock { + sidArray: LocalRelativeSidValueBlockJson[]; +} +declare class LocalRelativeObjectIdentifierValueBlock extends ValueBlock implements IStringConvertible { + static NAME: string; + value: LocalRelativeSidValueBlock[]; + constructor({ value, ...parameters }?: LocalRelativeObjectIdentifierValueBlockParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean, _writer?: ViewWriter): ArrayBuffer; + fromString(string: string): boolean; + toString(): string; + toJSON(): LocalRelativeObjectIdentifierValueBlockJson; +} + +interface RelativeObjectIdentifierParams extends BaseBlockParams, LocalRelativeObjectIdentifierValueBlockParams { +} +interface RelativeObjectIdentifierJson extends BaseBlockJson { + value: string; +} +declare class RelativeObjectIdentifier extends BaseBlock { + /** + * Gets string representation of Relative Object Identifier + * @since 3.0.0 + */ + getValue(): string; + /** + * Sets Relative Object Identifier value from string + * @param value String value + * @since 3.0.0 + */ + setValue(value: string): void; + static NAME: string; + constructor(parameters?: RelativeObjectIdentifierParams); + protected onAsciiEncoding(): string; + toJSON(): RelativeObjectIdentifierJson; +} + +type SequenceParams = ConstructedParams; +type SequenceJson = ConstructedJson; +declare class Sequence extends Constructed { + static NAME: string; + constructor(parameters?: SequenceParams); +} + +type SetParams = ConstructedParams; +type SetJson = ConstructedJson; +declare class Set extends Constructed { + static NAME: string; + constructor(parameters?: SetParams); +} + +type TeletexStringParams = LocalSimpleStringBlockParams; +type TeletexStringJson = LocalSimpleStringBlockJson; +declare class TeletexString extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: TeletexStringParams); +} + +type TIMEParams = Utf8StringParams; +type TIMEJson = Utf8StringJson; +declare class TIME extends Utf8String { + static NAME: string; + constructor(parameters?: TIMEParams); +} + +type TimeOfDayParams = Utf8StringParams; +type TimeOfDayJson = Utf8StringJson; +declare class TimeOfDay extends Utf8String { + static NAME: string; + constructor(parameters?: TimeOfDayParams); +} + +type LocalUniversalStringValueBlockParams = LocalSimpleStringBlockParams; +type LocalUniversalStringValueBlockJson = LocalSimpleStringBlockJson; +declare class LocalUniversalStringValueBlock extends LocalSimpleStringBlock { + static NAME: string; + fromBuffer(inputBuffer: ArrayBuffer | Uint8Array): void; + fromString(inputString: string): void; +} + +type UniversalStringParams = LocalUniversalStringValueBlockParams; +type UniversalStringJson = LocalUniversalStringValueBlockJson; +declare class UniversalString extends LocalUniversalStringValueBlock { + static NAME: string; + constructor({ ...parameters }?: UniversalStringParams); +} + +type VideotexStringParams = LocalSimpleStringBlockParams; +type VideotexStringJson = LocalSimpleStringBlockJson; +declare class VideotexString extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: VideotexStringParams); +} + +type AsnType = BaseBlock | EndOfContent | Boolean | Integer | BitString | OctetString | Null | ObjectIdentifier | Enumerated | Utf8String | RelativeObjectIdentifier | TIME | Sequence | Set | NumericString | PrintableString | TeletexString | VideotexString | IA5String | UTCTime | GeneralizedTime | GraphicString | VisibleString | GeneralString | UniversalString | CharacterString | BmpString | DATE | TimeOfDay | DateTime | Duration | Constructed | Primitive; + +interface FromBerResult { + offset: number; + result: AsnType; +} +interface FromBerOptions { + maxDepth?: number; + maxNodes?: number; + maxContentLength?: number; +} +interface FromBerContext { + depth: number; + maxDepth: number; + nodesCount: number; + maxNodes: number; + maxContentLength: number; +} +declare const DEFAULT_MAX_DEPTH = 100; +declare const DEFAULT_MAX_NODES = 10000; +declare const DEFAULT_MAX_CONTENT_LENGTH: number; +/** + * Major function for decoding ASN.1 BER array into internal library structures + * @param inputBuffer ASN.1 BER encoded array of bytes + * @param options Parser resource limits for untrusted input + */ +declare function fromBER(inputBuffer: pvtsutils.BufferSource, options?: FromBerOptions): FromBerResult; + +interface IBaseBlock { + name: string; + optional: boolean; + primitiveSchema?: BaseBlock; +} +interface BaseBlockParams extends LocalBaseBlockParams, LocalIdentificationBlockParams, LocalLengthBlockParams, Partial { +} +type ValueBlockConstructor = new (...args: any[]) => T; +interface BaseBlockJson extends LocalBaseBlockJson, Omit { + idBlock: LocalIdentificationBlockJson; + lenBlock: LocalLengthBlockJson; + valueBlock: T; + primitiveSchema?: BaseBlockJson; +} +type StringEncoding = "ascii" | "hex"; +declare class BaseBlock extends LocalBaseBlock implements IBaseBlock, IBerConvertible { + static NAME: string; + idBlock: LocalIdentificationBlock; + lenBlock: LocalLengthBlock; + valueBlock: T; + name: string; + optional: boolean; + primitiveSchema?: BaseBlock; + constructor({ name, optional, primitiveSchema, ...parameters }?: BaseBlockParams, valueBlockType?: ValueBlockConstructor); + fromBER(inputBuffer: Uint8Array, inputOffset: number, inputLength: number, context?: FromBerContext): number; + toBER(sizeOnly?: boolean, writer?: ViewWriter): ArrayBuffer; + toJSON(): BaseBlockJson; + toString(encoding?: StringEncoding): string; + protected onAsciiEncoding(): string; + /** + * Determines whether two object instances are equal + * @param other Object to compare with the current object + */ + isEqual(other: unknown): other is this; +} + +interface IChoice extends IAny { + value: BaseBlock[]; +} +type ChoiceParams = Partial; +declare class Choice extends Any implements IChoice { + value: BaseBlock[]; + constructor({ value, ...parameters }?: ChoiceParams); +} + +interface IRepeated extends IAny { + value: Any; + local: boolean; +} +type RepeatedParams = Partial; +declare class Repeated extends Any { + value: Any; + local: boolean; + constructor({ value, local, ...parameters }?: RepeatedParams); +} + +interface IRawData { + data: ArrayBuffer; +} +type RawDataParams = Partial; +/** + * Special class providing ability to have "toBER/fromBER" for raw ArrayBuffer + */ +declare class RawData implements IBerConvertible { + /** + * @deprecated Since v3.0.0 + */ + get data(): ArrayBuffer; + /** + * @deprecated Since v3.0.0 + */ + set data(value: ArrayBuffer); + /** + * @since 3.0.0 + */ + dataView: Uint8Array; + constructor({ data }?: RawDataParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(_sizeOnly?: boolean): ArrayBuffer; +} + +type AsnSchemaType = AsnType | Any | Choice | Repeated; +interface CompareSchemaSuccess { + verified: true; + result: AsnType & Record; +} +interface CompareSchemaFail { + verified: false; + name?: string; + result: AsnType | { + error: string; + }; +} +type CompareSchemaResult = CompareSchemaSuccess | CompareSchemaFail; +/** + * Compare of two ASN.1 object trees + * @param root Root of input ASN.1 object tree + * @param inputData Input ASN.1 object tree + * @param inputSchema Input ASN.1 schema to compare with + * @return Returns result of comparison + */ +declare function compareSchema(root: AsnType, inputData: AsnType, inputSchema: AsnSchemaType): CompareSchemaResult; +/** + * ASN.1 schema verification for ArrayBuffer data + * @param inputBuffer Input BER-encoded ASN.1 data + * @param inputSchema Input ASN.1 schema to verify against to + * @return + */ +declare function verifySchema(inputBuffer: pvtsutils.BufferSource, inputSchema: AsnSchemaType): CompareSchemaResult; + +export { Any, BaseBlock, BaseStringBlock, BitString, BmpString, Boolean, CharacterString, Choice, Constructed, DATE, DEFAULT_MAX_CONTENT_LENGTH, DEFAULT_MAX_DEPTH, DEFAULT_MAX_NODES, DateTime, Duration, EndOfContent, Enumerated, GeneralString, GeneralizedTime, GraphicString, HexBlock, IA5String, Integer, Null, NumericString, ObjectIdentifier, OctetString, Primitive, PrintableString, RawData, RelativeObjectIdentifier, Repeated, Sequence, Set, TIME, TeletexString, TimeOfDay, UTCTime, UniversalString, Utf8String, ValueBlock, VideotexString, ViewWriter, VisibleString, compareSchema, fromBER, verifySchema }; +export type { AnyParams, AsnSchemaType, AsnType, BaseBlockJson, BaseBlockParams, BaseStringBlockJson, BaseStringBlockParams, BitStringJson, BitStringParams, BmpStringJson, BmpStringParams, BooleanJson, BooleanParams, CharacterStringJson, CharacterStringParams, ChoiceParams, CompareSchemaFail, CompareSchemaResult, CompareSchemaSuccess, ConstructedJson, ConstructedParams, DATEJson, DATEParams, DateStringEncoding, DateTimeJson, DateTimeParams, DurationJson, DurationParams, EndOfContentJson, EndOfContentParams, EnumeratedJson, EnumeratedParams, FromBerOptions, FromBerResult, GeneralStringJson, GeneralStringParams, GeneralizedTimeJson, GeneralizedTimeParams, GraphicStringJson, GraphicStringParams, HexBlockJson, HexBlockParams, IA5StringJson, IA5StringParams, IAny, IBaseBlock, IBerConvertible, IChoice, IDateConvertible, IDerConvertible, IGeneralizedTime, IHexBlock, IRawData, IRepeated, IStringConvertible, IUTCTime, IValueBlock, IntegerJson, IntegerParams, NullJson, NullParams, NumericStringJson, NumericStringParams, ObjectIdentifierJson, ObjectIdentifierParams, OctetStringJson, OctetStringParams, PrimitiveJson, PrimitiveParams, PrintableStringJson, PrintableStringParams, RawDataParams, RelativeObjectIdentifierJson, RelativeObjectIdentifierParams, RepeatedParams, SequenceJson, SequenceParams, SetJson, SetParams, StringEncoding, TIMEJson, TIMEParams, TeletexStringJson, TeletexStringParams, TimeOfDayJson, TimeOfDayParams, UTCTimeJson, UTCTimeParams, UniversalStringJson, UniversalStringParams, Utf8StringJson, Utf8StringParams, ValueBlockConstructor, ValueBlockJson, ValueBlockParams, VideotexStringJson, VideotexStringParams, VisibleStringJson, VisibleStringParams }; diff --git a/node_modules/asn1js/build/index.es.js b/node_modules/asn1js/build/index.es.js new file mode 100644 index 0000000000000000000000000000000000000000..5189586136c84e35ea9b6c8fe728773b2a48eae1 --- /dev/null +++ b/node_modules/asn1js/build/index.es.js @@ -0,0 +1,3198 @@ +/*! + * Copyright (c) 2014, GMO GlobalSign + * Copyright (c) 2015-2022, Peculiar Ventures + * All rights reserved. + * + * Author 2014-2019, Yury Strozhevsky + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * * Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +import * as pvtsutils from 'pvtsutils'; +import * as pvutils from 'pvutils'; + +function assertBigInt() { + if (typeof BigInt === "undefined") { + throw new Error("BigInt is not defined. Your environment doesn't implement BigInt."); + } +} +function concat(buffers) { + let outputLength = 0; + let prevLength = 0; + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + outputLength += buffer.byteLength; + } + const retView = new Uint8Array(outputLength); + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + retView.set(new Uint8Array(buffer), prevLength); + prevLength += buffer.byteLength; + } + return retView.buffer; +} +function checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) { + if (!(inputBuffer instanceof Uint8Array)) { + baseBlock.error = "Wrong parameter: inputBuffer must be 'Uint8Array'"; + return false; + } + if (!inputBuffer.byteLength) { + baseBlock.error = "Wrong parameter: inputBuffer has zero length"; + return false; + } + if (inputOffset < 0) { + baseBlock.error = "Wrong parameter: inputOffset less than zero"; + return false; + } + if (inputLength < 0) { + baseBlock.error = "Wrong parameter: inputLength less than zero"; + return false; + } + if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) { + baseBlock.error = "End of input reached before message was fully decoded (inconsistent offset and length values)"; + return false; + } + return true; +} + +class ViewWriter { + constructor() { + this.items = []; + } + write(buf) { + this.items.push(buf); + } + final() { + return concat(this.items); + } +} + +const powers2 = [new Uint8Array([1])]; +const digitsString = "0123456789"; +const NAME = "name"; +const VALUE_HEX_VIEW = "valueHexView"; +const IS_HEX_ONLY = "isHexOnly"; +const ID_BLOCK = "idBlock"; +const TAG_CLASS = "tagClass"; +const TAG_NUMBER = "tagNumber"; +const IS_CONSTRUCTED = "isConstructed"; +const FROM_BER = "fromBER"; +const TO_BER = "toBER"; +const LOCAL = "local"; +const EMPTY_STRING = ""; +const EMPTY_BUFFER = new ArrayBuffer(0); +const EMPTY_VIEW = new Uint8Array(0); +const END_OF_CONTENT_NAME = "EndOfContent"; +const OCTET_STRING_NAME = "OCTET STRING"; +const BIT_STRING_NAME = "BIT STRING"; + +function HexBlock(BaseClass) { + var _a; + return _a = class Some extends BaseClass { + get valueHex() { + return this.valueHexView.slice().buffer; + } + set valueHex(value) { + this.valueHexView = new Uint8Array(value); + } + constructor(...args) { + var _b; + super(...args); + const params = args[0] || {}; + this.isHexOnly = (_b = params.isHexOnly) !== null && _b !== void 0 ? _b : false; + this.valueHexView = params.valueHex ? pvtsutils.BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW; + } + fromBER(inputBuffer, inputOffset, inputLength, _context) { + const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer; + if (!checkBufferParams(this, view, inputOffset, inputLength)) { + return -1; + } + const endLength = inputOffset + inputLength; + this.valueHexView = view.subarray(inputOffset, endLength); + if (!this.valueHexView.length) { + this.warnings.push("Zero buffer length"); + return inputOffset; + } + this.blockLength = inputLength; + return endLength; + } + toBER(sizeOnly = false) { + if (!this.isHexOnly) { + this.error = "Flag 'isHexOnly' is not set, abort"; + return EMPTY_BUFFER; + } + if (sizeOnly) { + return new ArrayBuffer(this.valueHexView.byteLength); + } + return (this.valueHexView.byteLength === this.valueHexView.buffer.byteLength) + ? this.valueHexView.buffer + : this.valueHexView.slice().buffer; + } + toJSON() { + return { + ...super.toJSON(), + isHexOnly: this.isHexOnly, + valueHex: pvtsutils.Convert.ToHex(this.valueHexView), + }; + } + }, + _a.NAME = "hexBlock", + _a; +} + +class LocalBaseBlock { + static blockName() { + return this.NAME; + } + get valueBeforeDecode() { + return this.valueBeforeDecodeView.slice().buffer; + } + set valueBeforeDecode(value) { + this.valueBeforeDecodeView = new Uint8Array(value); + } + constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW, } = {}) { + this.blockLength = blockLength; + this.error = error; + this.warnings = warnings; + this.valueBeforeDecodeView = pvtsutils.BufferSourceConverter.toUint8Array(valueBeforeDecode); + } + toJSON() { + return { + blockName: this.constructor.NAME, + blockLength: this.blockLength, + error: this.error, + warnings: this.warnings, + valueBeforeDecode: pvtsutils.Convert.ToHex(this.valueBeforeDecodeView), + }; + } +} +LocalBaseBlock.NAME = "baseBlock"; + +class ValueBlock extends LocalBaseBlock { + fromBER(_inputBuffer, _inputOffset, _inputLength, _context) { + throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'"); + } + toBER(_sizeOnly, _writer) { + throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'"); + } +} +ValueBlock.NAME = "valueBlock"; + +class LocalIdentificationBlock extends HexBlock(LocalBaseBlock) { + constructor({ idBlock = {} } = {}) { + var _a, _b, _c, _d; + super(); + if (idBlock) { + this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false; + this.valueHexView = idBlock.valueHex + ? pvtsutils.BufferSourceConverter.toUint8Array(idBlock.valueHex) + : EMPTY_VIEW; + this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1; + this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1; + this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false; + } + else { + this.tagClass = -1; + this.tagNumber = -1; + this.isConstructed = false; + } + } + toBER(sizeOnly = false) { + let firstOctet = 0; + switch (this.tagClass) { + case 1: + firstOctet |= 0x00; + break; + case 2: + firstOctet |= 0x40; + break; + case 3: + firstOctet |= 0x80; + break; + case 4: + firstOctet |= 0xC0; + break; + default: + this.error = "Unknown tag class"; + return EMPTY_BUFFER; + } + if (this.isConstructed) + firstOctet |= 0x20; + if (this.tagNumber < 31 && !this.isHexOnly) { + const retView = new Uint8Array(1); + if (!sizeOnly) { + let number = this.tagNumber; + number &= 0x1F; + firstOctet |= number; + retView[0] = firstOctet; + } + return retView.buffer; + } + if (!this.isHexOnly) { + const encodedBuf = pvutils.utilToBase(this.tagNumber, 7); + const encodedView = new Uint8Array(encodedBuf); + const size = encodedBuf.byteLength; + const retView = new Uint8Array(size + 1); + retView[0] = (firstOctet | 0x1F); + if (!sizeOnly) { + for (let i = 0; i < (size - 1); i++) + retView[i + 1] = encodedView[i] | 0x80; + retView[size] = encodedView[size - 1]; + } + return retView.buffer; + } + const retView = new Uint8Array(this.valueHexView.byteLength + 1); + retView[0] = (firstOctet | 0x1F); + if (!sizeOnly) { + const curView = this.valueHexView; + for (let i = 0; i < (curView.length - 1); i++) + retView[i + 1] = curView[i] | 0x80; + retView[this.valueHexView.byteLength] = curView[curView.length - 1]; + } + return retView.buffer; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + if (intBuffer.length === 0) { + this.error = "Zero buffer length"; + return -1; + } + const tagClassMask = intBuffer[0] & 0xC0; + switch (tagClassMask) { + case 0x00: + this.tagClass = (1); + break; + case 0x40: + this.tagClass = (2); + break; + case 0x80: + this.tagClass = (3); + break; + case 0xC0: + this.tagClass = (4); + break; + default: + this.error = "Unknown tag class"; + return -1; + } + this.isConstructed = (intBuffer[0] & 0x20) === 0x20; + this.isHexOnly = false; + const tagNumberMask = intBuffer[0] & 0x1F; + if (tagNumberMask !== 0x1F) { + this.tagNumber = (tagNumberMask); + this.blockLength = 1; + } + else { + let count = 0; + while (true) { + const tagByteIndex = count + 1; + if (tagByteIndex >= intBuffer.length) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + count++; + if ((intBuffer[tagByteIndex] & 0x80) === 0x00) + break; + } + this.blockLength = (count + 1); + const intTagNumberBuffer = this.valueHexView = new Uint8Array(count); + for (let i = 0; i < count; i++) + intTagNumberBuffer[i] = intBuffer[i + 1] & 0x7F; + if (this.blockLength <= 9) + this.tagNumber = pvutils.utilFromBase(intTagNumberBuffer, 7); + else { + this.isHexOnly = true; + this.warnings.push("Tag too long, represented as hex-coded"); + } + } + if (((this.tagClass === 1)) + && (this.isConstructed)) { + switch (this.tagNumber) { + case 1: + case 2: + case 5: + case 6: + case 9: + case 13: + case 14: + case 23: + case 24: + case 31: + case 32: + case 33: + case 34: + this.error = "Constructed encoding used for primitive type"; + return -1; + } + } + return (inputOffset + this.blockLength); + } + toJSON() { + return { + ...super.toJSON(), + tagClass: this.tagClass, + tagNumber: this.tagNumber, + isConstructed: this.isConstructed, + }; + } +} +LocalIdentificationBlock.NAME = "identificationBlock"; + +class LocalLengthBlock extends LocalBaseBlock { + constructor({ lenBlock = {} } = {}) { + var _a, _b, _c; + super(); + this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false; + this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false; + this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const view = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, view, inputOffset, inputLength)) { + return -1; + } + const intBuffer = view.subarray(inputOffset, inputOffset + inputLength); + if (intBuffer.length === 0) { + this.error = "Zero buffer length"; + return -1; + } + if (intBuffer[0] === 0xFF) { + this.error = "Length block 0xFF is reserved by standard"; + return -1; + } + this.isIndefiniteForm = intBuffer[0] === 0x80; + if (this.isIndefiniteForm) { + this.blockLength = 1; + return (inputOffset + this.blockLength); + } + this.longFormUsed = !!(intBuffer[0] & 0x80); + if (this.longFormUsed === false) { + this.length = (intBuffer[0]); + this.blockLength = 1; + return (inputOffset + this.blockLength); + } + const count = intBuffer[0] & 0x7F; + if (count > 8) { + this.error = "Too big integer"; + return -1; + } + if ((count + 1) > intBuffer.length) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + const lenOffset = inputOffset + 1; + const lengthBufferView = view.subarray(lenOffset, lenOffset + count); + if (lengthBufferView[count - 1] === 0x00) + this.warnings.push("Needlessly long encoded length"); + this.length = pvutils.utilFromBase(lengthBufferView, 8); + if (this.longFormUsed && (this.length <= 127)) + this.warnings.push("Unnecessary usage of long length form"); + this.blockLength = count + 1; + return (inputOffset + this.blockLength); + } + toBER(sizeOnly = false) { + let retBuf; + let retView; + if (this.length > 127) + this.longFormUsed = true; + if (this.isIndefiniteForm) { + retBuf = new ArrayBuffer(1); + if (sizeOnly === false) { + retView = new Uint8Array(retBuf); + retView[0] = 0x80; + } + return retBuf; + } + if (this.longFormUsed) { + const encodedBuf = pvutils.utilToBase(this.length, 8); + if (encodedBuf.byteLength > 127) { + this.error = "Too big length"; + return (EMPTY_BUFFER); + } + retBuf = new ArrayBuffer(encodedBuf.byteLength + 1); + if (sizeOnly) + return retBuf; + const encodedView = new Uint8Array(encodedBuf); + retView = new Uint8Array(retBuf); + retView[0] = encodedBuf.byteLength | 0x80; + for (let i = 0; i < encodedBuf.byteLength; i++) + retView[i + 1] = encodedView[i]; + return retBuf; + } + retBuf = new ArrayBuffer(1); + if (sizeOnly === false) { + retView = new Uint8Array(retBuf); + retView[0] = this.length; + } + return retBuf; + } + toJSON() { + return { + ...super.toJSON(), + isIndefiniteForm: this.isIndefiniteForm, + longFormUsed: this.longFormUsed, + length: this.length, + }; + } +} +LocalLengthBlock.NAME = "lengthBlock"; + +const typeStore = {}; + +class BaseBlock extends LocalBaseBlock { + constructor({ name = EMPTY_STRING, optional = false, primitiveSchema, ...parameters } = {}, valueBlockType) { + super(parameters); + this.name = name; + this.optional = optional; + if (primitiveSchema) { + this.primitiveSchema = primitiveSchema; + } + this.idBlock = new LocalIdentificationBlock(parameters); + this.lenBlock = new LocalLengthBlock(parameters); + this.valueBlock = valueBlockType ? new valueBlockType(parameters) : new ValueBlock(parameters); + } + fromBER(inputBuffer, inputOffset, inputLength, context) { + const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) + ? inputLength + : this.lenBlock.length, context); + if (resultOffset === -1) { + this.error = this.valueBlock.error; + return resultOffset; + } + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + if (!this.valueBlock.error.length) + this.blockLength += this.valueBlock.blockLength; + return resultOffset; + } + toBER(sizeOnly, writer) { + const _writer = writer || new ViewWriter(); + if (!writer) { + prepareIndefiniteForm(this); + } + const idBlockBuf = this.idBlock.toBER(sizeOnly); + _writer.write(idBlockBuf); + if (this.lenBlock.isIndefiniteForm) { + _writer.write(new Uint8Array([0x80]).buffer); + this.valueBlock.toBER(sizeOnly, _writer); + _writer.write(new ArrayBuffer(2)); + } + else { + const valueBlockBuf = this.valueBlock.toBER(sizeOnly); + this.lenBlock.length = valueBlockBuf.byteLength; + const lenBlockBuf = this.lenBlock.toBER(sizeOnly); + _writer.write(lenBlockBuf); + _writer.write(valueBlockBuf); + } + if (!writer) { + return _writer.final(); + } + return EMPTY_BUFFER; + } + toJSON() { + const object = { + ...super.toJSON(), + idBlock: this.idBlock.toJSON(), + lenBlock: this.lenBlock.toJSON(), + valueBlock: this.valueBlock.toJSON(), + name: this.name, + optional: this.optional, + }; + if (this.primitiveSchema) + object.primitiveSchema = this.primitiveSchema.toJSON(); + return object; + } + toString(encoding = "ascii") { + if (encoding === "ascii") { + return this.onAsciiEncoding(); + } + return pvtsutils.Convert.ToHex(this.toBER()); + } + onAsciiEncoding() { + const name = this.constructor.NAME; + const value = pvtsutils.Convert.ToHex(this.valueBlock.valueBeforeDecodeView); + return `${name} : ${value}`; + } + isEqual(other) { + if (this === other) { + return true; + } + if (!(other instanceof this.constructor)) { + return false; + } + const thisRaw = this.toBER(); + const otherRaw = other.toBER(); + return pvutils.isEqualBuffer(thisRaw, otherRaw); + } +} +BaseBlock.NAME = "BaseBlock"; +function prepareIndefiniteForm(baseBlock) { + var _a; + if (baseBlock instanceof typeStore.Constructed) { + for (const value of baseBlock.valueBlock.value) { + if (prepareIndefiniteForm(value)) { + baseBlock.lenBlock.isIndefiniteForm = true; + } + } + } + return !!((_a = baseBlock.lenBlock) === null || _a === void 0 ? void 0 : _a.isIndefiniteForm); +} + +class BaseStringBlock extends BaseBlock { + getValue() { + return this.valueBlock.value; + } + setValue(value) { + this.valueBlock.value = value; + } + constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) { + super(parameters, stringValueBlockType); + if (value) { + this.fromString(value); + } + } + fromBER(inputBuffer, inputOffset, inputLength) { + const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) + ? inputLength + : this.lenBlock.length); + if (resultOffset === -1) { + this.error = this.valueBlock.error; + return resultOffset; + } + this.fromBuffer(this.valueBlock.valueHexView); + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + if (!this.valueBlock.error.length) + this.blockLength += this.valueBlock.blockLength; + return resultOffset; + } + onAsciiEncoding() { + return `${this.constructor.NAME} : '${this.valueBlock.value}'`; + } +} +BaseStringBlock.NAME = "BaseStringBlock"; + +class LocalPrimitiveValueBlock extends HexBlock(ValueBlock) { + constructor({ isHexOnly = true, ...parameters } = {}) { + super(parameters); + this.isHexOnly = isHexOnly; + } +} +LocalPrimitiveValueBlock.NAME = "PrimitiveValueBlock"; + +var _a$w; +class Primitive extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalPrimitiveValueBlock); + this.idBlock.isConstructed = false; + } +} +_a$w = Primitive; +(() => { + typeStore.Primitive = _a$w; +})(); +Primitive.NAME = "PRIMITIVE"; + +const DEFAULT_MAX_DEPTH = 100; +const DEFAULT_MAX_NODES = 10000; +const DEFAULT_MAX_CONTENT_LENGTH = 16 * 1024 * 1024; +const MAX_DEPTH_EXCEEDED_ERROR = "Maximum ASN.1 nesting depth exceeded"; +const MAX_NODES_EXCEEDED_ERROR = "Maximum ASN.1 node count exceeded"; +const MAX_CONTENT_LENGTH_EXCEEDED_ERROR = "Maximum ASN.1 content length exceeded"; +function createFromBerContext(options = {}) { + var _a, _b, _c; + return { + depth: 0, + maxDepth: (_a = options.maxDepth) !== null && _a !== void 0 ? _a : DEFAULT_MAX_DEPTH, + nodesCount: 0, + maxNodes: (_b = options.maxNodes) !== null && _b !== void 0 ? _b : DEFAULT_MAX_NODES, + maxContentLength: (_c = options.maxContentLength) !== null && _c !== void 0 ? _c : DEFAULT_MAX_CONTENT_LENGTH, + }; +} +function createErrorResult(error) { + const result = new BaseBlock({}, ValueBlock); + result.error = error; + return { + offset: -1, + result, + }; +} +function checkNodesLimit(context) { + context.nodesCount += 1; + if (context.nodesCount > context.maxNodes) { + return MAX_NODES_EXCEEDED_ERROR; + } + return undefined; +} +function checkContentLengthLimit(inputLength, context) { + if (inputLength > context.maxContentLength) { + return MAX_CONTENT_LENGTH_EXCEEDED_ERROR; + } + return undefined; +} +function localFromBERWithChildContext(inputBuffer, inputOffset, inputLength, context) { + const childDepth = context.depth + 1; + if (childDepth > context.maxDepth) { + return createErrorResult(MAX_DEPTH_EXCEEDED_ERROR); + } + context.depth = childDepth; + try { + return localFromBER(inputBuffer, inputOffset, inputLength, context); + } + finally { + context.depth -= 1; + } +} +function localChangeType(inputObject, newType) { + if (inputObject instanceof newType) { + return inputObject; + } + const newObject = new newType(); + newObject.idBlock = inputObject.idBlock; + newObject.lenBlock = inputObject.lenBlock; + newObject.warnings = inputObject.warnings; + newObject.valueBeforeDecodeView = inputObject.valueBeforeDecodeView; + return newObject; +} +function localFromBER(inputBuffer, inputOffset = 0, inputLength = inputBuffer.length, context = createFromBerContext()) { + const incomingOffset = inputOffset; + let returnObject = new BaseBlock({}, ValueBlock); + const baseBlock = new LocalBaseBlock(); + if (!checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength)) { + returnObject.error = baseBlock.error; + return { + offset: -1, + result: returnObject, + }; + } + const intBuffer = inputBuffer.subarray(inputOffset, inputOffset + inputLength); + if (!intBuffer.length) { + returnObject.error = "Zero buffer length"; + return { + offset: -1, + result: returnObject, + }; + } + const nodesLimitError = checkNodesLimit(context); + if (nodesLimitError) { + returnObject.error = nodesLimitError; + return { + offset: -1, + result: returnObject, + }; + } + let resultOffset = returnObject.idBlock.fromBER(inputBuffer, inputOffset, inputLength); + if (returnObject.idBlock.warnings.length) { + returnObject.warnings.concat(returnObject.idBlock.warnings); + } + if (resultOffset === -1) { + returnObject.error = returnObject.idBlock.error; + return { + offset: -1, + result: returnObject, + }; + } + inputOffset = resultOffset; + inputLength -= returnObject.idBlock.blockLength; + resultOffset = returnObject.lenBlock.fromBER(inputBuffer, inputOffset, inputLength); + if (returnObject.lenBlock.warnings.length) { + returnObject.warnings.concat(returnObject.lenBlock.warnings); + } + if (resultOffset === -1) { + returnObject.error = returnObject.lenBlock.error; + return { + offset: -1, + result: returnObject, + }; + } + inputOffset = resultOffset; + inputLength -= returnObject.lenBlock.blockLength; + const valueLength = returnObject.lenBlock.isIndefiniteForm ? inputLength : returnObject.lenBlock.length; + const contentLengthError = checkContentLengthLimit(valueLength, context); + if (contentLengthError) { + returnObject.error = contentLengthError; + return { + offset: -1, + result: returnObject, + }; + } + if (!returnObject.idBlock.isConstructed + && returnObject.lenBlock.isIndefiniteForm) { + returnObject.error = "Indefinite length form used for primitive encoding form"; + return { + offset: -1, + result: returnObject, + }; + } + let newASN1Type = BaseBlock; + switch (returnObject.idBlock.tagClass) { + case 1: + if ((returnObject.idBlock.tagNumber >= 37) + && (returnObject.idBlock.isHexOnly === false)) { + returnObject.error = "UNIVERSAL 37 and upper tags are reserved by ASN.1 standard"; + return { + offset: -1, + result: returnObject, + }; + } + switch (returnObject.idBlock.tagNumber) { + case 0: + if ((returnObject.idBlock.isConstructed) + && (returnObject.lenBlock.length > 0)) { + returnObject.error = "Type [UNIVERSAL 0] is reserved"; + return { + offset: -1, + result: returnObject, + }; + } + newASN1Type = typeStore.EndOfContent; + break; + case 1: + newASN1Type = typeStore.Boolean; + break; + case 2: + newASN1Type = typeStore.Integer; + break; + case 3: + newASN1Type = typeStore.BitString; + break; + case 4: + newASN1Type = typeStore.OctetString; + break; + case 5: + newASN1Type = typeStore.Null; + break; + case 6: + newASN1Type = typeStore.ObjectIdentifier; + break; + case 10: + newASN1Type = typeStore.Enumerated; + break; + case 12: + newASN1Type = typeStore.Utf8String; + break; + case 13: + newASN1Type = typeStore.RelativeObjectIdentifier; + break; + case 14: + newASN1Type = typeStore.TIME; + break; + case 15: + returnObject.error = "[UNIVERSAL 15] is reserved by ASN.1 standard"; + return { + offset: -1, + result: returnObject, + }; + case 16: + newASN1Type = typeStore.Sequence; + break; + case 17: + newASN1Type = typeStore.Set; + break; + case 18: + newASN1Type = typeStore.NumericString; + break; + case 19: + newASN1Type = typeStore.PrintableString; + break; + case 20: + newASN1Type = typeStore.TeletexString; + break; + case 21: + newASN1Type = typeStore.VideotexString; + break; + case 22: + newASN1Type = typeStore.IA5String; + break; + case 23: + newASN1Type = typeStore.UTCTime; + break; + case 24: + newASN1Type = typeStore.GeneralizedTime; + break; + case 25: + newASN1Type = typeStore.GraphicString; + break; + case 26: + newASN1Type = typeStore.VisibleString; + break; + case 27: + newASN1Type = typeStore.GeneralString; + break; + case 28: + newASN1Type = typeStore.UniversalString; + break; + case 29: + newASN1Type = typeStore.CharacterString; + break; + case 30: + newASN1Type = typeStore.BmpString; + break; + case 31: + newASN1Type = typeStore.DATE; + break; + case 32: + newASN1Type = typeStore.TimeOfDay; + break; + case 33: + newASN1Type = typeStore.DateTime; + break; + case 34: + newASN1Type = typeStore.Duration; + break; + default: { + const newObject = returnObject.idBlock.isConstructed + ? new typeStore.Constructed() + : new typeStore.Primitive(); + newObject.idBlock = returnObject.idBlock; + newObject.lenBlock = returnObject.lenBlock; + newObject.warnings = returnObject.warnings; + returnObject = newObject; + } + } + break; + case 2: + case 3: + case 4: + default: { + newASN1Type = returnObject.idBlock.isConstructed + ? typeStore.Constructed + : typeStore.Primitive; + } + } + returnObject = localChangeType(returnObject, newASN1Type); + resultOffset = returnObject.fromBER(inputBuffer, inputOffset, valueLength, context); + returnObject.valueBeforeDecodeView = inputBuffer.subarray(incomingOffset, incomingOffset + returnObject.blockLength); + return { + offset: resultOffset, + result: returnObject, + }; +} +function fromBER(inputBuffer, options = {}) { + if (!inputBuffer.byteLength) { + const result = new BaseBlock({}, ValueBlock); + result.error = "Input buffer has zero length"; + return { + offset: -1, + result, + }; + } + return localFromBER(pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer).slice(), 0, inputBuffer.byteLength, createFromBerContext(options)); +} + +function checkLen(indefiniteLength, length) { + if (indefiniteLength) { + return 1; + } + return length; +} +class LocalConstructedValueBlock extends ValueBlock { + constructor({ value = [], isIndefiniteForm = false, ...parameters } = {}) { + super(parameters); + this.value = value; + this.isIndefiniteForm = isIndefiniteForm; + } + fromBER(inputBuffer, inputOffset, inputLength, context) { + const view = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + const parseContext = context !== null && context !== void 0 ? context : createFromBerContext(); + if (!checkBufferParams(this, view, inputOffset, inputLength)) { + return -1; + } + this.valueBeforeDecodeView = view.subarray(inputOffset, inputOffset + inputLength); + if (this.valueBeforeDecodeView.length === 0) { + this.warnings.push("Zero buffer length"); + return inputOffset; + } + let currentOffset = inputOffset; + while (checkLen(this.isIndefiniteForm, inputLength) > 0) { + const returnObject = localFromBERWithChildContext(view, currentOffset, inputLength, parseContext); + if (returnObject.offset === -1) { + this.error = returnObject.result.error; + this.warnings.concat(returnObject.result.warnings); + return -1; + } + currentOffset = returnObject.offset; + this.blockLength += returnObject.result.blockLength; + inputLength -= returnObject.result.blockLength; + this.value.push(returnObject.result); + if (this.isIndefiniteForm && returnObject.result.constructor.NAME === END_OF_CONTENT_NAME) { + break; + } + } + if (this.isIndefiniteForm) { + if (this.value[this.value.length - 1].constructor.NAME === END_OF_CONTENT_NAME) { + this.value.pop(); + } + else { + this.warnings.push("No EndOfContent block encoded"); + } + } + return currentOffset; + } + toBER(sizeOnly, writer) { + const _writer = writer || new ViewWriter(); + for (let i = 0; i < this.value.length; i++) { + this.value[i].toBER(sizeOnly, _writer); + } + if (!writer) { + return _writer.final(); + } + return EMPTY_BUFFER; + } + toJSON() { + const object = { + ...super.toJSON(), + isIndefiniteForm: this.isIndefiniteForm, + value: [], + }; + for (const value of this.value) { + object.value.push(value.toJSON()); + } + return object; + } +} +LocalConstructedValueBlock.NAME = "ConstructedValueBlock"; + +var _a$v; +class Constructed extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalConstructedValueBlock); + this.idBlock.isConstructed = true; + } + fromBER(inputBuffer, inputOffset, inputLength, context) { + this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; + const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length, context); + if (resultOffset === -1) { + this.error = this.valueBlock.error; + return resultOffset; + } + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + if (!this.valueBlock.error.length) + this.blockLength += this.valueBlock.blockLength; + return resultOffset; + } + onAsciiEncoding() { + const values = []; + for (const value of this.valueBlock.value) { + values.push(value.toString("ascii").split("\n").map((o) => ` ${o}`).join("\n")); + } + const blockName = this.idBlock.tagClass === 3 + ? `[${this.idBlock.tagNumber}]` + : this.constructor.NAME; + return values.length + ? `${blockName} :\n${values.join("\n")}` + : `${blockName} :`; + } +} +_a$v = Constructed; +(() => { + typeStore.Constructed = _a$v; +})(); +Constructed.NAME = "CONSTRUCTED"; + +class LocalEndOfContentValueBlock extends ValueBlock { + fromBER(inputBuffer, inputOffset, _inputLength) { + return inputOffset; + } + toBER(_sizeOnly) { + return EMPTY_BUFFER; + } +} +LocalEndOfContentValueBlock.override = "EndOfContentValueBlock"; + +var _a$u; +class EndOfContent extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalEndOfContentValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 0; + } +} +_a$u = EndOfContent; +(() => { + typeStore.EndOfContent = _a$u; +})(); +EndOfContent.NAME = END_OF_CONTENT_NAME; + +var _a$t; +class Null extends BaseBlock { + constructor(parameters = {}) { + super(parameters, ValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 5; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (this.lenBlock.length > 0) + this.warnings.push("Non-zero length of value block for Null type"); + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + this.blockLength += inputLength; + if ((inputOffset + inputLength) > inputBuffer.byteLength) { + this.error = "End of input reached before message was fully decoded (inconsistent offset and length values)"; + return -1; + } + return (inputOffset + inputLength); + } + toBER(sizeOnly, writer) { + const retBuf = new ArrayBuffer(2); + if (!sizeOnly) { + const retView = new Uint8Array(retBuf); + retView[0] = 0x05; + retView[1] = 0x00; + } + if (writer) { + writer.write(retBuf); + } + return retBuf; + } + onAsciiEncoding() { + return `${this.constructor.NAME}`; + } +} +_a$t = Null; +(() => { + typeStore.Null = _a$t; +})(); +Null.NAME = "NULL"; + +class LocalBooleanValueBlock extends HexBlock(ValueBlock) { + get value() { + for (const octet of this.valueHexView) { + if (octet > 0) { + return true; + } + } + return false; + } + set value(value) { + this.valueHexView[0] = value ? 0xFF : 0x00; + } + constructor({ value, ...parameters } = {}) { + super(parameters); + if (parameters.valueHex) { + this.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(parameters.valueHex); + } + else { + this.valueHexView = new Uint8Array(1); + } + if (value) { + this.value = value; + } + } + fromBER(inputBuffer, inputOffset, inputLength) { + const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + this.valueHexView = inputView.subarray(inputOffset, inputOffset + inputLength); + if (inputLength > 1) + this.warnings.push("Boolean value encoded in more then 1 octet"); + this.isHexOnly = true; + pvutils.utilDecodeTC.call(this); + this.blockLength = inputLength; + return (inputOffset + inputLength); + } + toBER() { + return this.valueHexView.slice(); + } + toJSON() { + return { + ...super.toJSON(), + value: this.value, + }; + } +} +LocalBooleanValueBlock.NAME = "BooleanValueBlock"; + +var _a$s; +class Boolean extends BaseBlock { + getValue() { + return this.valueBlock.value; + } + setValue(value) { + this.valueBlock.value = value; + } + constructor(parameters = {}) { + super(parameters, LocalBooleanValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 1; + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.getValue}`; + } +} +_a$s = Boolean; +(() => { + typeStore.Boolean = _a$s; +})(); +Boolean.NAME = "BOOLEAN"; + +class LocalOctetStringValueBlock extends HexBlock(LocalConstructedValueBlock) { + constructor({ isConstructed = false, ...parameters } = {}) { + super(parameters); + this.isConstructed = isConstructed; + } + fromBER(inputBuffer, inputOffset, inputLength, context) { + let resultOffset = 0; + if (this.isConstructed) { + this.isHexOnly = false; + resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength, context); + if (resultOffset === -1) + return resultOffset; + for (let i = 0; i < this.value.length; i++) { + const currentBlockName = this.value[i].constructor.NAME; + if (currentBlockName === END_OF_CONTENT_NAME) { + if (this.isIndefiniteForm) + break; + else { + this.error = "EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only"; + return -1; + } + } + if (currentBlockName !== OCTET_STRING_NAME) { + this.error = "OCTET STRING may consists of OCTET STRINGs only"; + return -1; + } + } + } + else { + this.isHexOnly = true; + resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength); + this.blockLength = inputLength; + } + return resultOffset; + } + toBER(sizeOnly, writer) { + if (this.isConstructed) + return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer); + return sizeOnly + ? new ArrayBuffer(this.valueHexView.byteLength) + : this.valueHexView.slice().buffer; + } + toJSON() { + return { + ...super.toJSON(), + isConstructed: this.isConstructed, + }; + } +} +LocalOctetStringValueBlock.NAME = "OctetStringValueBlock"; + +var _a$r; +class OctetString extends BaseBlock { + constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) { + var _b, _c; + (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length)); + super({ + idBlock: { + isConstructed: parameters.isConstructed, + ...idBlock, + }, + lenBlock: { + ...lenBlock, + isIndefiniteForm: !!parameters.isIndefiniteForm, + }, + ...parameters, + }, LocalOctetStringValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 4; + } + fromBER(inputBuffer, inputOffset, inputLength, context) { + this.valueBlock.isConstructed = this.idBlock.isConstructed; + this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; + if (inputLength === 0) { + if (this.idBlock.error.length === 0) + this.blockLength += this.idBlock.blockLength; + if (this.lenBlock.error.length === 0) + this.blockLength += this.lenBlock.blockLength; + return inputOffset; + } + if (!this.valueBlock.isConstructed) { + const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer; + const buf = view.subarray(inputOffset, inputOffset + inputLength); + try { + if (buf.byteLength) { + const parseContext = context !== null && context !== void 0 ? context : createFromBerContext(); + const asn = localFromBERWithChildContext(buf, 0, buf.byteLength, parseContext); + if (asn.offset !== -1 && asn.offset === inputLength) { + this.valueBlock.value = [asn.result]; + } + } + } + catch { + } + } + return super.fromBER(inputBuffer, inputOffset, inputLength, context); + } + onAsciiEncoding() { + if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) { + return Constructed.prototype.onAsciiEncoding.call(this); + } + const name = this.constructor.NAME; + const value = pvtsutils.Convert.ToHex(this.valueBlock.valueHexView); + return `${name} : ${value}`; + } + getValue() { + if (!this.idBlock.isConstructed) { + return this.valueBlock.valueHexView.slice().buffer; + } + const array = []; + for (const content of this.valueBlock.value) { + if (content instanceof _a$r) { + array.push(content.valueBlock.valueHexView); + } + } + return pvtsutils.BufferSourceConverter.concat(array); + } +} +_a$r = OctetString; +(() => { + typeStore.OctetString = _a$r; +})(); +OctetString.NAME = OCTET_STRING_NAME; + +class LocalBitStringValueBlock extends HexBlock(LocalConstructedValueBlock) { + constructor({ unusedBits = 0, isConstructed = false, ...parameters } = {}) { + super(parameters); + this.unusedBits = unusedBits; + this.isConstructed = isConstructed; + this.blockLength = this.valueHexView.byteLength; + } + fromBER(inputBuffer, inputOffset, inputLength, context) { + if (!inputLength) { + return inputOffset; + } + let resultOffset = -1; + if (this.isConstructed) { + resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength, context); + if (resultOffset === -1) + return resultOffset; + for (const value of this.value) { + const currentBlockName = value.constructor.NAME; + if (currentBlockName === END_OF_CONTENT_NAME) { + if (this.isIndefiniteForm) + break; + else { + this.error = "EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only"; + return -1; + } + } + if (currentBlockName !== BIT_STRING_NAME) { + this.error = "BIT STRING may consists of BIT STRINGs only"; + return -1; + } + const valueBlock = value.valueBlock; + if ((this.unusedBits > 0) && (valueBlock.unusedBits > 0)) { + this.error = "Using of \"unused bits\" inside constructive BIT STRING allowed for least one only"; + return -1; + } + this.unusedBits = valueBlock.unusedBits; + } + return resultOffset; + } + const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + this.unusedBits = intBuffer[0]; + if (this.unusedBits > 7) { + this.error = "Unused bits for BitString must be in range 0-7"; + return -1; + } + if (!this.unusedBits) { + const buf = intBuffer.subarray(1); + try { + if (buf.byteLength) { + const parseContext = context !== null && context !== void 0 ? context : createFromBerContext(); + const asn = localFromBERWithChildContext(buf, 0, buf.byteLength, parseContext); + if (asn.offset !== -1 && asn.offset === (inputLength - 1)) { + this.value = [asn.result]; + } + } + } + catch { + } + } + this.valueHexView = intBuffer.subarray(1); + this.blockLength = intBuffer.length; + return (inputOffset + inputLength); + } + toBER(sizeOnly, writer) { + if (this.isConstructed) { + return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer); + } + if (sizeOnly) { + return new ArrayBuffer(this.valueHexView.byteLength + 1); + } + if (!this.valueHexView.byteLength) { + const empty = new Uint8Array(1); + empty[0] = 0; + return empty.buffer; + } + const retView = new Uint8Array(this.valueHexView.length + 1); + retView[0] = this.unusedBits; + retView.set(this.valueHexView, 1); + return retView.buffer; + } + toJSON() { + return { + ...super.toJSON(), + unusedBits: this.unusedBits, + isConstructed: this.isConstructed, + }; + } +} +LocalBitStringValueBlock.NAME = "BitStringValueBlock"; + +var _a$q; +class BitString extends BaseBlock { + constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) { + var _b, _c; + (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length)); + super({ + idBlock: { + isConstructed: parameters.isConstructed, + ...idBlock, + }, + lenBlock: { + ...lenBlock, + isIndefiniteForm: !!parameters.isIndefiniteForm, + }, + ...parameters, + }, LocalBitStringValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 3; + } + fromBER(inputBuffer, inputOffset, inputLength, context) { + this.valueBlock.isConstructed = this.idBlock.isConstructed; + this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; + return super.fromBER(inputBuffer, inputOffset, inputLength, context); + } + onAsciiEncoding() { + if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) { + return Constructed.prototype.onAsciiEncoding.call(this); + } + else { + const bits = []; + const valueHex = this.valueBlock.valueHexView; + for (const byte of valueHex) { + bits.push(byte.toString(2).padStart(8, "0")); + } + const bitsStr = bits.join(""); + const name = this.constructor.NAME; + const value = bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits); + return `${name} : ${value}`; + } + } +} +_a$q = BitString; +(() => { + typeStore.BitString = _a$q; +})(); +BitString.NAME = BIT_STRING_NAME; + +var _a$p; +function viewAdd(first, second) { + const c = new Uint8Array([0]); + const firstView = new Uint8Array(first); + const secondView = new Uint8Array(second); + let firstViewCopy = firstView.slice(0); + const firstViewCopyLength = firstViewCopy.length - 1; + const secondViewCopy = secondView.slice(0); + const secondViewCopyLength = secondViewCopy.length - 1; + let value = 0; + const max = (secondViewCopyLength < firstViewCopyLength) ? firstViewCopyLength : secondViewCopyLength; + let counter = 0; + for (let i = max; i >= 0; i--, counter++) { + switch (true) { + case (counter < secondViewCopy.length): + value = firstViewCopy[firstViewCopyLength - counter] + secondViewCopy[secondViewCopyLength - counter] + c[0]; + break; + default: + value = firstViewCopy[firstViewCopyLength - counter] + c[0]; + } + c[0] = value / 10; + switch (true) { + case (counter >= firstViewCopy.length): + firstViewCopy = pvutils.utilConcatView(new Uint8Array([value % 10]), firstViewCopy); + break; + default: + firstViewCopy[firstViewCopyLength - counter] = value % 10; + } + } + if (c[0] > 0) + firstViewCopy = pvutils.utilConcatView(c, firstViewCopy); + return firstViewCopy; +} +function power2(n) { + if (n >= powers2.length) { + for (let p = powers2.length; p <= n; p++) { + const c = new Uint8Array([0]); + let digits = (powers2[p - 1]).slice(0); + for (let i = (digits.length - 1); i >= 0; i--) { + const newValue = new Uint8Array([(digits[i] << 1) + c[0]]); + c[0] = newValue[0] / 10; + digits[i] = newValue[0] % 10; + } + if (c[0] > 0) + digits = pvutils.utilConcatView(c, digits); + powers2.push(digits); + } + } + return powers2[n]; +} +function viewSub(first, second) { + let b = 0; + const firstView = new Uint8Array(first); + const secondView = new Uint8Array(second); + const firstViewCopy = firstView.slice(0); + const firstViewCopyLength = firstViewCopy.length - 1; + const secondViewCopy = secondView.slice(0); + const secondViewCopyLength = secondViewCopy.length - 1; + let value; + let counter = 0; + for (let i = secondViewCopyLength; i >= 0; i--, counter++) { + value = firstViewCopy[firstViewCopyLength - counter] - secondViewCopy[secondViewCopyLength - counter] - b; + switch (true) { + case (value < 0): + b = 1; + firstViewCopy[firstViewCopyLength - counter] = value + 10; + break; + default: + b = 0; + firstViewCopy[firstViewCopyLength - counter] = value; + } + } + if (b > 0) { + for (let i = (firstViewCopyLength - secondViewCopyLength + 1); i >= 0; i--, counter++) { + value = firstViewCopy[firstViewCopyLength - counter] - b; + if (value < 0) { + b = 1; + firstViewCopy[firstViewCopyLength - counter] = value + 10; + } + else { + b = 0; + firstViewCopy[firstViewCopyLength - counter] = value; + break; + } + } + } + return firstViewCopy.slice(); +} +class LocalIntegerValueBlock extends HexBlock(ValueBlock) { + setValueHex() { + if (this.valueHexView.length >= 4) { + this.warnings.push("Too big Integer for decoding, hex only"); + this.isHexOnly = true; + this._valueDec = 0; + } + else { + this.isHexOnly = false; + if (this.valueHexView.length > 0) { + this._valueDec = pvutils.utilDecodeTC.call(this); + } + } + } + constructor({ value, ...parameters } = {}) { + super(parameters); + this._valueDec = 0; + if (parameters.valueHex) { + this.setValueHex(); + } + if (value !== undefined) { + this.valueDec = value; + } + } + set valueDec(v) { + this._valueDec = v; + this.isHexOnly = false; + this.valueHexView = new Uint8Array(pvutils.utilEncodeTC(v)); + } + get valueDec() { + return this._valueDec; + } + fromDER(inputBuffer, inputOffset, inputLength, expectedLength = 0) { + const offset = this.fromBER(inputBuffer, inputOffset, inputLength); + if (offset === -1) + return offset; + const view = this.valueHexView; + if ((view[0] === 0x00) && ((view[1] & 0x80) !== 0)) { + this.valueHexView = view.subarray(1); + } + else { + if (expectedLength !== 0) { + if (view.length < expectedLength) { + if ((expectedLength - view.length) > 1) + expectedLength = view.length + 1; + this.valueHexView = view.subarray(expectedLength - view.length); + } + } + } + return offset; + } + toDER(sizeOnly = false) { + const view = this.valueHexView; + switch (true) { + case ((view[0] & 0x80) !== 0): + { + const updatedView = new Uint8Array(this.valueHexView.length + 1); + updatedView[0] = 0x00; + updatedView.set(view, 1); + this.valueHexView = updatedView; + } + break; + case ((view[0] === 0x00) && ((view[1] & 0x80) === 0)): + { + this.valueHexView = this.valueHexView.subarray(1); + } + break; + } + return this.toBER(sizeOnly); + } + fromBER(inputBuffer, inputOffset, inputLength) { + const resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength); + if (resultOffset === -1) { + return resultOffset; + } + this.setValueHex(); + return resultOffset; + } + toBER(sizeOnly) { + return sizeOnly + ? new ArrayBuffer(this.valueHexView.length) + : this.valueHexView.slice().buffer; + } + toJSON() { + return { + ...super.toJSON(), + valueDec: this.valueDec, + }; + } + toString() { + const firstBit = (this.valueHexView.length * 8) - 1; + let digits = new Uint8Array((this.valueHexView.length * 8) / 3); + let bitNumber = 0; + let currentByte; + const asn1View = this.valueHexView; + let result = ""; + let flag = false; + for (let byteNumber = (asn1View.byteLength - 1); byteNumber >= 0; byteNumber--) { + currentByte = asn1View[byteNumber]; + for (let i = 0; i < 8; i++) { + if ((currentByte & 1) === 1) { + switch (bitNumber) { + case firstBit: + digits = viewSub(power2(bitNumber), digits); + result = "-"; + break; + default: + digits = viewAdd(digits, power2(bitNumber)); + } + } + bitNumber++; + currentByte >>= 1; + } + } + for (let i = 0; i < digits.length; i++) { + if (digits[i]) + flag = true; + if (flag) + result += digitsString.charAt(digits[i]); + } + if (flag === false) + result += digitsString.charAt(0); + return result; + } +} +_a$p = LocalIntegerValueBlock; +LocalIntegerValueBlock.NAME = "IntegerValueBlock"; +(() => { + Object.defineProperty(_a$p.prototype, "valueHex", { + set: function (v) { + this.valueHexView = new Uint8Array(v); + this.setValueHex(); + }, + get: function () { + return this.valueHexView.slice().buffer; + }, + }); +})(); + +var _a$o; +class Integer extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalIntegerValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 2; + } + toBigInt() { + assertBigInt(); + return BigInt(this.valueBlock.toString()); + } + static fromBigInt(value) { + assertBigInt(); + const bigIntValue = BigInt(value); + const writer = new ViewWriter(); + const hex = bigIntValue.toString(16).replace(/^-/, ""); + const view = new Uint8Array(pvtsutils.Convert.FromHex(hex)); + if (bigIntValue < 0) { + const first = new Uint8Array(view.length + (view[0] & 0x80 ? 1 : 0)); + first[0] |= 0x80; + const firstInt = BigInt(`0x${pvtsutils.Convert.ToHex(first)}`); + const secondInt = firstInt + bigIntValue; + const second = pvtsutils.BufferSourceConverter.toUint8Array(pvtsutils.Convert.FromHex(secondInt.toString(16))); + second[0] |= 0x80; + writer.write(second); + } + else { + if (view[0] & 0x80) { + writer.write(new Uint8Array([0])); + } + writer.write(view); + } + const res = new _a$o({ valueHex: writer.final() }); + return res; + } + convertToDER() { + const integer = new _a$o({ valueHex: this.valueBlock.valueHexView }); + integer.valueBlock.toDER(); + return integer; + } + convertFromDER() { + return new _a$o({ + valueHex: this.valueBlock.valueHexView[0] === 0 + ? this.valueBlock.valueHexView.subarray(1) + : this.valueBlock.valueHexView, + }); + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.valueBlock.toString()}`; + } +} +_a$o = Integer; +(() => { + typeStore.Integer = _a$o; +})(); +Integer.NAME = "INTEGER"; + +var _a$n; +class Enumerated extends Integer { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 10; + } +} +_a$n = Enumerated; +(() => { + typeStore.Enumerated = _a$n; +})(); +Enumerated.NAME = "ENUMERATED"; + +class LocalSidValueBlock extends HexBlock(ValueBlock) { + constructor({ valueDec = -1, isFirstSid = false, ...parameters } = {}) { + super(parameters); + this.valueDec = valueDec; + this.isFirstSid = isFirstSid; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (!inputLength) { + return inputOffset; + } + const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + this.valueHexView = new Uint8Array(inputLength); + for (let i = 0; i < inputLength; i++) { + this.valueHexView[i] = intBuffer[i] & 0x7F; + this.blockLength++; + if ((intBuffer[i] & 0x80) === 0x00) + break; + } + const tempView = new Uint8Array(this.blockLength); + for (let i = 0; i < this.blockLength; i++) { + tempView[i] = this.valueHexView[i]; + } + this.valueHexView = tempView; + if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + if (this.valueHexView[0] === 0x00) + this.warnings.push("Needlessly long format of SID encoding"); + if (this.blockLength <= 8) + this.valueDec = pvutils.utilFromBase(this.valueHexView, 7); + else { + this.isHexOnly = true; + this.warnings.push("Too big SID for decoding, hex only"); + } + return (inputOffset + this.blockLength); + } + set valueBigInt(value) { + assertBigInt(); + let bits = BigInt(value).toString(2); + while (bits.length % 7) { + bits = "0" + bits; + } + const bytes = new Uint8Array(bits.length / 7); + for (let i = 0; i < bytes.length; i++) { + bytes[i] = parseInt(bits.slice(i * 7, i * 7 + 7), 2) + (i + 1 < bytes.length ? 0x80 : 0); + } + this.fromBER(bytes.buffer, 0, bytes.length); + } + toBER(sizeOnly) { + if (this.isHexOnly) { + if (sizeOnly) + return (new ArrayBuffer(this.valueHexView.byteLength)); + const curView = this.valueHexView; + const retView = new Uint8Array(this.blockLength); + for (let i = 0; i < (this.blockLength - 1); i++) + retView[i] = curView[i] | 0x80; + retView[this.blockLength - 1] = curView[this.blockLength - 1]; + return retView.buffer; + } + const encodedBuf = pvutils.utilToBase(this.valueDec, 7); + if (encodedBuf.byteLength === 0) { + this.error = "Error during encoding SID value"; + return EMPTY_BUFFER; + } + const retView = new Uint8Array(encodedBuf.byteLength); + if (!sizeOnly) { + const encodedView = new Uint8Array(encodedBuf); + const len = encodedBuf.byteLength - 1; + for (let i = 0; i < len; i++) + retView[i] = encodedView[i] | 0x80; + retView[len] = encodedView[len]; + } + return retView; + } + toString() { + let result = ""; + if (this.isHexOnly) + result = pvtsutils.Convert.ToHex(this.valueHexView); + else { + if (this.isFirstSid) { + let sidValue = this.valueDec; + if (this.valueDec <= 39) + result = "0."; + else { + if (this.valueDec <= 79) { + result = "1."; + sidValue -= 40; + } + else { + result = "2."; + sidValue -= 80; + } + } + result += sidValue.toString(); + } + else + result = this.valueDec.toString(); + } + return result; + } + toJSON() { + return { + ...super.toJSON(), + valueDec: this.valueDec, + isFirstSid: this.isFirstSid, + }; + } +} +LocalSidValueBlock.NAME = "sidBlock"; + +class LocalObjectIdentifierValueBlock extends ValueBlock { + constructor({ value = EMPTY_STRING, ...parameters } = {}) { + super(parameters); + this.value = []; + if (value) { + this.fromString(value); + } + } + fromBER(inputBuffer, inputOffset, inputLength) { + let resultOffset = inputOffset; + while (inputLength > 0) { + const sidBlock = new LocalSidValueBlock(); + resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength); + if (resultOffset === -1) { + this.blockLength = 0; + this.error = sidBlock.error; + return resultOffset; + } + if (this.value.length === 0) + sidBlock.isFirstSid = true; + this.blockLength += sidBlock.blockLength; + inputLength -= sidBlock.blockLength; + this.value.push(sidBlock); + } + return resultOffset; + } + toBER(sizeOnly) { + const retBuffers = []; + for (let i = 0; i < this.value.length; i++) { + const valueBuf = this.value[i].toBER(sizeOnly); + if (valueBuf.byteLength === 0) { + this.error = this.value[i].error; + return EMPTY_BUFFER; + } + retBuffers.push(valueBuf); + } + return concat(retBuffers); + } + fromString(string) { + this.value = []; + let pos1 = 0; + let pos2 = 0; + let sid = ""; + let flag = false; + do { + pos2 = string.indexOf(".", pos1); + if (pos2 === -1) + sid = string.substring(pos1); + else + sid = string.substring(pos1, pos2); + pos1 = pos2 + 1; + if (flag) { + const sidBlock = this.value[0]; + let plus = 0; + switch (sidBlock.valueDec) { + case 0: + break; + case 1: + plus = 40; + break; + case 2: + plus = 80; + break; + default: + this.value = []; + return; + } + const parsedSID = parseInt(sid, 10); + if (isNaN(parsedSID)) + return; + sidBlock.valueDec = parsedSID + plus; + flag = false; + } + else { + const sidBlock = new LocalSidValueBlock(); + if (sid > Number.MAX_SAFE_INTEGER) { + assertBigInt(); + const sidValue = BigInt(sid); + sidBlock.valueBigInt = sidValue; + } + else { + sidBlock.valueDec = parseInt(sid, 10); + if (isNaN(sidBlock.valueDec)) + return; + } + if (!this.value.length) { + sidBlock.isFirstSid = true; + flag = true; + } + this.value.push(sidBlock); + } + } while (pos2 !== -1); + } + toString() { + let result = ""; + let isHexOnly = false; + for (let i = 0; i < this.value.length; i++) { + isHexOnly = this.value[i].isHexOnly; + let sidStr = this.value[i].toString(); + if (i !== 0) + result = `${result}.`; + if (isHexOnly) { + sidStr = `{${sidStr}}`; + if (this.value[i].isFirstSid) + result = `2.{${sidStr} - 80}`; + else + result += sidStr; + } + else + result += sidStr; + } + return result; + } + toJSON() { + const object = { + ...super.toJSON(), + value: this.toString(), + sidArray: [], + }; + for (let i = 0; i < this.value.length; i++) { + object.sidArray.push(this.value[i].toJSON()); + } + return object; + } +} +LocalObjectIdentifierValueBlock.NAME = "ObjectIdentifierValueBlock"; + +var _a$m; +class ObjectIdentifier extends BaseBlock { + getValue() { + return this.valueBlock.toString(); + } + setValue(value) { + this.valueBlock.fromString(value); + } + constructor(parameters = {}) { + super(parameters, LocalObjectIdentifierValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 6; + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`; + } + toJSON() { + return { + ...super.toJSON(), + value: this.getValue(), + }; + } +} +_a$m = ObjectIdentifier; +(() => { + typeStore.ObjectIdentifier = _a$m; +})(); +ObjectIdentifier.NAME = "OBJECT IDENTIFIER"; + +class LocalRelativeSidValueBlock extends HexBlock(LocalBaseBlock) { + constructor({ valueDec = 0, ...parameters } = {}) { + super(parameters); + this.valueDec = valueDec; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (inputLength === 0) + return inputOffset; + const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) + return -1; + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + this.valueHexView = new Uint8Array(inputLength); + for (let i = 0; i < inputLength; i++) { + this.valueHexView[i] = intBuffer[i] & 0x7F; + this.blockLength++; + if ((intBuffer[i] & 0x80) === 0x00) + break; + } + const tempView = new Uint8Array(this.blockLength); + for (let i = 0; i < this.blockLength; i++) + tempView[i] = this.valueHexView[i]; + this.valueHexView = tempView; + if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + if (this.valueHexView[0] === 0x00) + this.warnings.push("Needlessly long format of SID encoding"); + if (this.blockLength <= 8) + this.valueDec = pvutils.utilFromBase(this.valueHexView, 7); + else { + this.isHexOnly = true; + this.warnings.push("Too big SID for decoding, hex only"); + } + return (inputOffset + this.blockLength); + } + toBER(sizeOnly) { + if (this.isHexOnly) { + if (sizeOnly) + return (new ArrayBuffer(this.valueHexView.byteLength)); + const curView = this.valueHexView; + const retView = new Uint8Array(this.blockLength); + for (let i = 0; i < (this.blockLength - 1); i++) + retView[i] = curView[i] | 0x80; + retView[this.blockLength - 1] = curView[this.blockLength - 1]; + return retView.buffer; + } + const encodedBuf = pvutils.utilToBase(this.valueDec, 7); + if (encodedBuf.byteLength === 0) { + this.error = "Error during encoding SID value"; + return EMPTY_BUFFER; + } + const retView = new Uint8Array(encodedBuf.byteLength); + if (!sizeOnly) { + const encodedView = new Uint8Array(encodedBuf); + const len = encodedBuf.byteLength - 1; + for (let i = 0; i < len; i++) + retView[i] = encodedView[i] | 0x80; + retView[len] = encodedView[len]; + } + return retView.buffer; + } + toString() { + let result = ""; + if (this.isHexOnly) + result = pvtsutils.Convert.ToHex(this.valueHexView); + else { + result = this.valueDec.toString(); + } + return result; + } + toJSON() { + return { + ...super.toJSON(), + valueDec: this.valueDec, + }; + } +} +LocalRelativeSidValueBlock.NAME = "relativeSidBlock"; + +class LocalRelativeObjectIdentifierValueBlock extends ValueBlock { + constructor({ value = EMPTY_STRING, ...parameters } = {}) { + super(parameters); + this.value = []; + if (value) { + this.fromString(value); + } + } + fromBER(inputBuffer, inputOffset, inputLength) { + let resultOffset = inputOffset; + while (inputLength > 0) { + const sidBlock = new LocalRelativeSidValueBlock(); + resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength); + if (resultOffset === -1) { + this.blockLength = 0; + this.error = sidBlock.error; + return resultOffset; + } + this.blockLength += sidBlock.blockLength; + inputLength -= sidBlock.blockLength; + this.value.push(sidBlock); + } + return resultOffset; + } + toBER(sizeOnly, _writer) { + const retBuffers = []; + for (let i = 0; i < this.value.length; i++) { + const valueBuf = this.value[i].toBER(sizeOnly); + if (valueBuf.byteLength === 0) { + this.error = this.value[i].error; + return EMPTY_BUFFER; + } + retBuffers.push(valueBuf); + } + return concat(retBuffers); + } + fromString(string) { + this.value = []; + let pos1 = 0; + let pos2 = 0; + let sid = ""; + do { + pos2 = string.indexOf(".", pos1); + if (pos2 === -1) + sid = string.substring(pos1); + else + sid = string.substring(pos1, pos2); + pos1 = pos2 + 1; + const sidBlock = new LocalRelativeSidValueBlock(); + sidBlock.valueDec = parseInt(sid, 10); + if (isNaN(sidBlock.valueDec)) + return true; + this.value.push(sidBlock); + } while (pos2 !== -1); + return true; + } + toString() { + let result = ""; + let isHexOnly = false; + for (let i = 0; i < this.value.length; i++) { + isHexOnly = this.value[i].isHexOnly; + let sidStr = this.value[i].toString(); + if (i !== 0) + result = `${result}.`; + if (isHexOnly) { + sidStr = `{${sidStr}}`; + result += sidStr; + } + else + result += sidStr; + } + return result; + } + toJSON() { + const object = { + ...super.toJSON(), + value: this.toString(), + sidArray: [], + }; + for (let i = 0; i < this.value.length; i++) + object.sidArray.push(this.value[i].toJSON()); + return object; + } +} +LocalRelativeObjectIdentifierValueBlock.NAME = "RelativeObjectIdentifierValueBlock"; + +var _a$l; +class RelativeObjectIdentifier extends BaseBlock { + getValue() { + return this.valueBlock.toString(); + } + setValue(value) { + this.valueBlock.fromString(value); + } + constructor(parameters = {}) { + super(parameters, LocalRelativeObjectIdentifierValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 13; + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`; + } + toJSON() { + return { + ...super.toJSON(), + value: this.getValue(), + }; + } +} +_a$l = RelativeObjectIdentifier; +(() => { + typeStore.RelativeObjectIdentifier = _a$l; +})(); +RelativeObjectIdentifier.NAME = "RelativeObjectIdentifier"; + +var _a$k; +class Sequence extends Constructed { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 16; + } +} +_a$k = Sequence; +(() => { + typeStore.Sequence = _a$k; +})(); +Sequence.NAME = "SEQUENCE"; + +var _a$j; +class Set extends Constructed { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 17; + } +} +_a$j = Set; +(() => { + typeStore.Set = _a$j; +})(); +Set.NAME = "SET"; + +class LocalStringValueBlock extends HexBlock(ValueBlock) { + constructor({ ...parameters } = {}) { + super(parameters); + this.isHexOnly = true; + this.value = EMPTY_STRING; + } + toJSON() { + return { + ...super.toJSON(), + value: this.value, + }; + } +} +LocalStringValueBlock.NAME = "StringValueBlock"; + +class LocalSimpleStringValueBlock extends LocalStringValueBlock { +} +LocalSimpleStringValueBlock.NAME = "SimpleStringValueBlock"; + +class LocalSimpleStringBlock extends BaseStringBlock { + constructor({ ...parameters } = {}) { + super(parameters, LocalSimpleStringValueBlock); + } + fromBuffer(inputBuffer) { + this.valueBlock.value = String.fromCharCode.apply(null, pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer)); + } + fromString(inputString) { + const strLen = inputString.length; + const view = this.valueBlock.valueHexView = new Uint8Array(strLen); + for (let i = 0; i < strLen; i++) + view[i] = inputString.charCodeAt(i); + this.valueBlock.value = inputString; + } +} +LocalSimpleStringBlock.NAME = "SIMPLE STRING"; + +class LocalUtf8StringValueBlock extends LocalSimpleStringBlock { + fromBuffer(inputBuffer) { + this.valueBlock.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + try { + this.valueBlock.value = pvtsutils.Convert.ToUtf8String(inputBuffer); + } + catch (ex) { + this.warnings.push(`Error during "decodeURIComponent": ${ex}, using raw string`); + this.valueBlock.value = pvtsutils.Convert.ToBinary(inputBuffer); + } + } + fromString(inputString) { + this.valueBlock.valueHexView = new Uint8Array(pvtsutils.Convert.FromUtf8String(inputString)); + this.valueBlock.value = inputString; + } +} +LocalUtf8StringValueBlock.NAME = "Utf8StringValueBlock"; + +var _a$i; +class Utf8String extends LocalUtf8StringValueBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 12; + } +} +_a$i = Utf8String; +(() => { + typeStore.Utf8String = _a$i; +})(); +Utf8String.NAME = "UTF8String"; + +class LocalBmpStringValueBlock extends LocalSimpleStringBlock { + fromBuffer(inputBuffer) { + this.valueBlock.value = pvtsutils.Convert.ToUtf16String(inputBuffer); + this.valueBlock.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + } + fromString(inputString) { + this.valueBlock.value = inputString; + this.valueBlock.valueHexView = new Uint8Array(pvtsutils.Convert.FromUtf16String(inputString)); + } +} +LocalBmpStringValueBlock.NAME = "BmpStringValueBlock"; + +var _a$h; +class BmpString extends LocalBmpStringValueBlock { + constructor({ ...parameters } = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 30; + } +} +_a$h = BmpString; +(() => { + typeStore.BmpString = _a$h; +})(); +BmpString.NAME = "BMPString"; + +class LocalUniversalStringValueBlock extends LocalSimpleStringBlock { + fromBuffer(inputBuffer) { + const copyBuffer = ArrayBuffer.isView(inputBuffer) ? inputBuffer.slice().buffer : inputBuffer.slice(0); + const valueView = new Uint8Array(copyBuffer); + for (let i = 0; i < valueView.length; i += 4) { + valueView[i] = valueView[i + 3]; + valueView[i + 1] = valueView[i + 2]; + valueView[i + 2] = 0x00; + valueView[i + 3] = 0x00; + } + this.valueBlock.value = String.fromCharCode.apply(null, new Uint32Array(copyBuffer)); + } + fromString(inputString) { + const strLength = inputString.length; + const valueHexView = this.valueBlock.valueHexView = new Uint8Array(strLength * 4); + for (let i = 0; i < strLength; i++) { + const codeBuf = pvutils.utilToBase(inputString.charCodeAt(i), 8); + const codeView = new Uint8Array(codeBuf); + if (codeView.length > 4) + continue; + const dif = 4 - codeView.length; + for (let j = (codeView.length - 1); j >= 0; j--) + valueHexView[i * 4 + j + dif] = codeView[j]; + } + this.valueBlock.value = inputString; + } +} +LocalUniversalStringValueBlock.NAME = "UniversalStringValueBlock"; + +var _a$g; +class UniversalString extends LocalUniversalStringValueBlock { + constructor({ ...parameters } = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 28; + } +} +_a$g = UniversalString; +(() => { + typeStore.UniversalString = _a$g; +})(); +UniversalString.NAME = "UniversalString"; + +var _a$f; +class NumericString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 18; + } +} +_a$f = NumericString; +(() => { + typeStore.NumericString = _a$f; +})(); +NumericString.NAME = "NumericString"; + +var _a$e; +class PrintableString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 19; + } +} +_a$e = PrintableString; +(() => { + typeStore.PrintableString = _a$e; +})(); +PrintableString.NAME = "PrintableString"; + +var _a$d; +class TeletexString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 20; + } +} +_a$d = TeletexString; +(() => { + typeStore.TeletexString = _a$d; +})(); +TeletexString.NAME = "TeletexString"; + +var _a$c; +class VideotexString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 21; + } +} +_a$c = VideotexString; +(() => { + typeStore.VideotexString = _a$c; +})(); +VideotexString.NAME = "VideotexString"; + +var _a$b; +class IA5String extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 22; + } +} +_a$b = IA5String; +(() => { + typeStore.IA5String = _a$b; +})(); +IA5String.NAME = "IA5String"; + +var _a$a; +class GraphicString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 25; + } +} +_a$a = GraphicString; +(() => { + typeStore.GraphicString = _a$a; +})(); +GraphicString.NAME = "GraphicString"; + +var _a$9; +class VisibleString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 26; + } +} +_a$9 = VisibleString; +(() => { + typeStore.VisibleString = _a$9; +})(); +VisibleString.NAME = "VisibleString"; + +var _a$8; +class GeneralString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 27; + } +} +_a$8 = GeneralString; +(() => { + typeStore.GeneralString = _a$8; +})(); +GeneralString.NAME = "GeneralString"; + +var _a$7; +class CharacterString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 29; + } +} +_a$7 = CharacterString; +(() => { + typeStore.CharacterString = _a$7; +})(); +CharacterString.NAME = "CharacterString"; + +var _a$6; +class UTCTime extends VisibleString { + constructor({ value, valueDate, ...parameters } = {}) { + super(parameters); + this.year = 0; + this.month = 0; + this.day = 0; + this.hour = 0; + this.minute = 0; + this.second = 0; + if (value) { + this.fromString(value); + this.valueBlock.valueHexView = new Uint8Array(value.length); + for (let i = 0; i < value.length; i++) + this.valueBlock.valueHexView[i] = value.charCodeAt(i); + } + if (valueDate) { + this.fromDate(valueDate); + this.valueBlock.valueHexView = new Uint8Array(this.toBuffer()); + } + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 23; + } + fromBuffer(inputBuffer) { + this.fromString(String.fromCharCode.apply(null, pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer))); + } + toBuffer() { + const str = this.toString(); + const buffer = new ArrayBuffer(str.length); + const view = new Uint8Array(buffer); + for (let i = 0; i < str.length; i++) + view[i] = str.charCodeAt(i); + return buffer; + } + fromDate(inputDate) { + this.year = inputDate.getUTCFullYear(); + this.month = inputDate.getUTCMonth() + 1; + this.day = inputDate.getUTCDate(); + this.hour = inputDate.getUTCHours(); + this.minute = inputDate.getUTCMinutes(); + this.second = inputDate.getUTCSeconds(); + } + toDate() { + return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second))); + } + fromString(inputString) { + const parser = /(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig; + const parserArray = parser.exec(inputString); + if (parserArray === null) { + this.error = "Wrong input string for conversion"; + return; + } + const year = parseInt(parserArray[1], 10); + if (year >= 50) + this.year = 1900 + year; + else + this.year = 2000 + year; + this.month = parseInt(parserArray[2], 10); + this.day = parseInt(parserArray[3], 10); + this.hour = parseInt(parserArray[4], 10); + this.minute = parseInt(parserArray[5], 10); + this.second = parseInt(parserArray[6], 10); + } + toString(encoding = "iso") { + if (encoding === "iso") { + const outputArray = new Array(7); + outputArray[0] = pvutils.padNumber(((this.year < 2000) ? (this.year - 1900) : (this.year - 2000)), 2); + outputArray[1] = pvutils.padNumber(this.month, 2); + outputArray[2] = pvutils.padNumber(this.day, 2); + outputArray[3] = pvutils.padNumber(this.hour, 2); + outputArray[4] = pvutils.padNumber(this.minute, 2); + outputArray[5] = pvutils.padNumber(this.second, 2); + outputArray[6] = "Z"; + return outputArray.join(""); + } + return super.toString(encoding); + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.toDate().toISOString()}`; + } + toJSON() { + return { + ...super.toJSON(), + year: this.year, + month: this.month, + day: this.day, + hour: this.hour, + minute: this.minute, + second: this.second, + }; + } +} +_a$6 = UTCTime; +(() => { + typeStore.UTCTime = _a$6; +})(); +UTCTime.NAME = "UTCTime"; + +var _a$5; +class GeneralizedTime extends UTCTime { + constructor(parameters = {}) { + var _b; + super(parameters); + (_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 24; + } + fromDate(inputDate) { + super.fromDate(inputDate); + this.millisecond = inputDate.getUTCMilliseconds(); + } + toDate() { + const utcDate = Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond); + return (new Date(utcDate)); + } + fromString(inputString) { + let isUTC = false; + let timeString = ""; + let dateTimeString = ""; + let fractionPart = 0; + let parser; + let hourDifference = 0; + let minuteDifference = 0; + if (inputString[inputString.length - 1] === "Z") { + timeString = inputString.substring(0, inputString.length - 1); + isUTC = true; + } + else { + const number = new Number(inputString[inputString.length - 1]); + if (isNaN(number.valueOf())) + throw new Error("Wrong input string for conversion"); + timeString = inputString; + } + if (isUTC) { + if (timeString.indexOf("+") !== -1) + throw new Error("Wrong input string for conversion"); + if (timeString.indexOf("-") !== -1) + throw new Error("Wrong input string for conversion"); + } + else { + let multiplier = 1; + let differencePosition = timeString.indexOf("+"); + let differenceString = ""; + if (differencePosition === -1) { + differencePosition = timeString.indexOf("-"); + multiplier = -1; + } + if (differencePosition !== -1) { + differenceString = timeString.substring(differencePosition + 1); + timeString = timeString.substring(0, differencePosition); + if ((differenceString.length !== 2) && (differenceString.length !== 4)) + throw new Error("Wrong input string for conversion"); + let number = parseInt(differenceString.substring(0, 2), 10); + if (isNaN(number.valueOf())) + throw new Error("Wrong input string for conversion"); + hourDifference = multiplier * number; + if (differenceString.length === 4) { + number = parseInt(differenceString.substring(2, 4), 10); + if (isNaN(number.valueOf())) + throw new Error("Wrong input string for conversion"); + minuteDifference = multiplier * number; + } + } + } + let fractionPointPosition = timeString.indexOf("."); + if (fractionPointPosition === -1) + fractionPointPosition = timeString.indexOf(","); + if (fractionPointPosition !== -1) { + const fractionPartCheck = new Number(`0${timeString.substring(fractionPointPosition)}`); + if (isNaN(fractionPartCheck.valueOf())) + throw new Error("Wrong input string for conversion"); + fractionPart = fractionPartCheck.valueOf(); + dateTimeString = timeString.substring(0, fractionPointPosition); + } + else + dateTimeString = timeString; + switch (true) { + case (dateTimeString.length === 8): + parser = /(\d{4})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) + throw new Error("Wrong input string for conversion"); + break; + case (dateTimeString.length === 10): + parser = /(\d{4})(\d{2})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) { + let fractionResult = 60 * fractionPart; + this.minute = Math.floor(fractionResult); + fractionResult = 60 * (fractionResult - this.minute); + this.second = Math.floor(fractionResult); + fractionResult = 1000 * (fractionResult - this.second); + this.millisecond = Math.floor(fractionResult); + } + break; + case (dateTimeString.length === 12): + parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) { + let fractionResult = 60 * fractionPart; + this.second = Math.floor(fractionResult); + fractionResult = 1000 * (fractionResult - this.second); + this.millisecond = Math.floor(fractionResult); + } + break; + case (dateTimeString.length === 14): + parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) { + const fractionResult = 1000 * fractionPart; + this.millisecond = Math.floor(fractionResult); + } + break; + default: + throw new Error("Wrong input string for conversion"); + } + const parserArray = parser.exec(dateTimeString); + if (parserArray === null) + throw new Error("Wrong input string for conversion"); + for (let j = 1; j < parserArray.length; j++) { + switch (j) { + case 1: + this.year = parseInt(parserArray[j], 10); + break; + case 2: + this.month = parseInt(parserArray[j], 10); + break; + case 3: + this.day = parseInt(parserArray[j], 10); + break; + case 4: + this.hour = parseInt(parserArray[j], 10) + hourDifference; + break; + case 5: + this.minute = parseInt(parserArray[j], 10) + minuteDifference; + break; + case 6: + this.second = parseInt(parserArray[j], 10); + break; + default: + throw new Error("Wrong input string for conversion"); + } + } + if (isUTC === false) { + const tempDate = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond); + this.year = tempDate.getUTCFullYear(); + this.month = tempDate.getUTCMonth(); + this.day = tempDate.getUTCDay(); + this.hour = tempDate.getUTCHours(); + this.minute = tempDate.getUTCMinutes(); + this.second = tempDate.getUTCSeconds(); + this.millisecond = tempDate.getUTCMilliseconds(); + } + } + toString(encoding = "iso") { + if (encoding === "iso") { + const outputArray = []; + outputArray.push(pvutils.padNumber(this.year, 4)); + outputArray.push(pvutils.padNumber(this.month, 2)); + outputArray.push(pvutils.padNumber(this.day, 2)); + outputArray.push(pvutils.padNumber(this.hour, 2)); + outputArray.push(pvutils.padNumber(this.minute, 2)); + outputArray.push(pvutils.padNumber(this.second, 2)); + if (this.millisecond !== 0) { + outputArray.push("."); + outputArray.push(pvutils.padNumber(this.millisecond, 3)); + } + outputArray.push("Z"); + return outputArray.join(""); + } + return super.toString(encoding); + } + toJSON() { + return { + ...super.toJSON(), + millisecond: this.millisecond, + }; + } +} +_a$5 = GeneralizedTime; +(() => { + typeStore.GeneralizedTime = _a$5; +})(); +GeneralizedTime.NAME = "GeneralizedTime"; + +var _a$4; +class DATE extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 31; + } +} +_a$4 = DATE; +(() => { + typeStore.DATE = _a$4; +})(); +DATE.NAME = "DATE"; + +var _a$3; +class TimeOfDay extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 32; + } +} +_a$3 = TimeOfDay; +(() => { + typeStore.TimeOfDay = _a$3; +})(); +TimeOfDay.NAME = "TimeOfDay"; + +var _a$2; +class DateTime extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 33; + } +} +_a$2 = DateTime; +(() => { + typeStore.DateTime = _a$2; +})(); +DateTime.NAME = "DateTime"; + +var _a$1; +class Duration extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 34; + } +} +_a$1 = Duration; +(() => { + typeStore.Duration = _a$1; +})(); +Duration.NAME = "Duration"; + +var _a; +class TIME extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 14; + } +} +_a = TIME; +(() => { + typeStore.TIME = _a; +})(); +TIME.NAME = "TIME"; + +class Any { + constructor({ name = EMPTY_STRING, optional = false } = {}) { + this.name = name; + this.optional = optional; + } +} + +class Choice extends Any { + constructor({ value = [], ...parameters } = {}) { + super(parameters); + this.value = value; + } +} + +class Repeated extends Any { + constructor({ value = new Any(), local = false, ...parameters } = {}) { + super(parameters); + this.value = value; + this.local = local; + } +} + +class RawData { + get data() { + return this.dataView.slice().buffer; + } + set data(value) { + this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(value); + } + constructor({ data = EMPTY_VIEW } = {}) { + this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(data); + } + fromBER(inputBuffer, inputOffset, inputLength) { + const endLength = inputOffset + inputLength; + this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer).subarray(inputOffset, endLength); + return endLength; + } + toBER(_sizeOnly) { + return this.dataView.slice().buffer; + } +} + +function compareSchema(root, inputData, inputSchema) { + if (inputSchema instanceof Choice) { + for (const element of inputSchema.value) { + const result = compareSchema(root, inputData, element); + if (result.verified) { + return { + verified: true, + result: root, + }; + } + } + { + const _result = { + verified: false, + result: { error: "Wrong values for Choice type" }, + }; + if (inputSchema.hasOwnProperty(NAME)) + _result.name = inputSchema.name; + return _result; + } + } + if (inputSchema instanceof Any) { + if (inputSchema.hasOwnProperty(NAME)) + root[inputSchema.name] = inputData; + return { + verified: true, + result: root, + }; + } + if ((root instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong root object" }, + }; + } + if ((inputData instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 data" }, + }; + } + if ((inputSchema instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if ((ID_BLOCK in inputSchema) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if ((FROM_BER in inputSchema.idBlock) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if ((TO_BER in inputSchema.idBlock) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + const encodedId = inputSchema.idBlock.toBER(false); + if (encodedId.byteLength === 0) { + return { + verified: false, + result: { error: "Error encoding idBlock for ASN.1 schema" }, + }; + } + const decodedOffset = inputSchema.idBlock.fromBER(encodedId, 0, encodedId.byteLength); + if (decodedOffset === -1) { + return { + verified: false, + result: { error: "Error decoding idBlock for ASN.1 schema" }, + }; + } + if (inputSchema.idBlock.hasOwnProperty(TAG_CLASS) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if (inputSchema.idBlock.tagClass !== inputData.idBlock.tagClass) { + return { + verified: false, + result: root, + }; + } + if (inputSchema.idBlock.hasOwnProperty(TAG_NUMBER) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if (inputSchema.idBlock.tagNumber !== inputData.idBlock.tagNumber) { + return { + verified: false, + result: root, + }; + } + if (inputSchema.idBlock.hasOwnProperty(IS_CONSTRUCTED) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if (inputSchema.idBlock.isConstructed !== inputData.idBlock.isConstructed) { + return { + verified: false, + result: root, + }; + } + if (!(IS_HEX_ONLY in inputSchema.idBlock)) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if (inputSchema.idBlock.isHexOnly !== inputData.idBlock.isHexOnly) { + return { + verified: false, + result: root, + }; + } + if (inputSchema.idBlock.isHexOnly) { + if ((VALUE_HEX_VIEW in inputSchema.idBlock) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + const schemaView = inputSchema.idBlock.valueHexView; + const asn1View = inputData.idBlock.valueHexView; + if (schemaView.length !== asn1View.length) { + return { + verified: false, + result: root, + }; + } + for (let i = 0; i < schemaView.length; i++) { + if (schemaView[i] !== asn1View[1]) { + return { + verified: false, + result: root, + }; + } + } + } + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) + root[inputSchema.name] = inputData; + } + if (inputSchema instanceof typeStore.Constructed) { + let admission = 0; + let result = { + verified: false, + result: { error: "Unknown error" }, + }; + let maxLength = inputSchema.valueBlock.value.length; + if (maxLength > 0) { + if (inputSchema.valueBlock.value[0] instanceof Repeated) { + maxLength = inputData.valueBlock.value.length; + } + } + if (maxLength === 0) { + return { + verified: true, + result: root, + }; + } + if ((inputData.valueBlock.value.length === 0) + && (inputSchema.valueBlock.value.length !== 0)) { + let _optional = true; + for (let i = 0; i < inputSchema.valueBlock.value.length; i++) + _optional = _optional && (inputSchema.valueBlock.value[i].optional || false); + if (_optional) { + return { + verified: true, + result: root, + }; + } + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) + delete root[inputSchema.name]; + } + root.error = "Inconsistent object length"; + return { + verified: false, + result: root, + }; + } + for (let i = 0; i < maxLength; i++) { + if ((i - admission) >= inputData.valueBlock.value.length) { + if (inputSchema.valueBlock.value[i].optional === false) { + const _result = { + verified: false, + result: root, + }; + root.error = "Inconsistent length between ASN.1 data and schema"; + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) { + delete root[inputSchema.name]; + _result.name = inputSchema.name; + } + } + return _result; + } + } + else { + if (inputSchema.valueBlock.value[0] instanceof Repeated) { + result = compareSchema(root, inputData.valueBlock.value[i], inputSchema.valueBlock.value[0].value); + if (result.verified === false) { + if (inputSchema.valueBlock.value[0].optional) + admission++; + else { + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) + delete root[inputSchema.name]; + } + return result; + } + } + if ((NAME in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].name.length > 0)) { + let arrayRoot = {}; + if ((LOCAL in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].local)) + arrayRoot = inputData; + else + arrayRoot = root; + if (typeof arrayRoot[inputSchema.valueBlock.value[0].name] === "undefined") + arrayRoot[inputSchema.valueBlock.value[0].name] = []; + arrayRoot[inputSchema.valueBlock.value[0].name].push(inputData.valueBlock.value[i]); + } + } + else { + result = compareSchema(root, inputData.valueBlock.value[i - admission], inputSchema.valueBlock.value[i]); + if (result.verified === false) { + if (inputSchema.valueBlock.value[i].optional) + admission++; + else { + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) + delete root[inputSchema.name]; + } + return result; + } + } + } + } + } + if (result.verified === false) { + const _result = { + verified: false, + result: root, + }; + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) { + delete root[inputSchema.name]; + _result.name = inputSchema.name; + } + } + return _result; + } + return { + verified: true, + result: root, + }; + } + if (inputSchema.primitiveSchema + && (VALUE_HEX_VIEW in inputData.valueBlock)) { + const asn1 = localFromBER(inputData.valueBlock.valueHexView); + if (asn1.offset === -1) { + const _result = { + verified: false, + result: asn1.result, + }; + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) { + delete root[inputSchema.name]; + _result.name = inputSchema.name; + } + } + return _result; + } + return compareSchema(root, asn1.result, inputSchema.primitiveSchema); + } + return { + verified: true, + result: root, + }; +} +function verifySchema(inputBuffer, inputSchema) { + if ((inputSchema instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema type" }, + }; + } + const asn1 = localFromBER(pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer)); + if (asn1.offset === -1) { + return { + verified: false, + result: asn1.result, + }; + } + return compareSchema(asn1.result, asn1.result, inputSchema); +} + +export { Any, BaseBlock, BaseStringBlock, BitString, BmpString, Boolean, CharacterString, Choice, Constructed, DATE, DEFAULT_MAX_CONTENT_LENGTH, DEFAULT_MAX_DEPTH, DEFAULT_MAX_NODES, DateTime, Duration, EndOfContent, Enumerated, GeneralString, GeneralizedTime, GraphicString, HexBlock, IA5String, Integer, Null, NumericString, ObjectIdentifier, OctetString, Primitive, PrintableString, RawData, RelativeObjectIdentifier, Repeated, Sequence, Set, TIME, TeletexString, TimeOfDay, UTCTime, UniversalString, Utf8String, ValueBlock, VideotexString, ViewWriter, VisibleString, compareSchema, fromBER, verifySchema }; diff --git a/node_modules/asn1js/build/index.js b/node_modules/asn1js/build/index.js new file mode 100644 index 0000000000000000000000000000000000000000..822b21c89243f3cbfcd95e26286db25d41b53cec --- /dev/null +++ b/node_modules/asn1js/build/index.js @@ -0,0 +1,3266 @@ +/*! + * Copyright (c) 2014, GMO GlobalSign + * Copyright (c) 2015-2022, Peculiar Ventures + * All rights reserved. + * + * Author 2014-2019, Yury Strozhevsky + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * * Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +'use strict'; + +var pvtsutils = require('pvtsutils'); +var pvutils = require('pvutils'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var pvtsutils__namespace = /*#__PURE__*/_interopNamespaceDefault(pvtsutils); +var pvutils__namespace = /*#__PURE__*/_interopNamespaceDefault(pvutils); + +function assertBigInt() { + if (typeof BigInt === "undefined") { + throw new Error("BigInt is not defined. Your environment doesn't implement BigInt."); + } +} +function concat(buffers) { + let outputLength = 0; + let prevLength = 0; + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + outputLength += buffer.byteLength; + } + const retView = new Uint8Array(outputLength); + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + retView.set(new Uint8Array(buffer), prevLength); + prevLength += buffer.byteLength; + } + return retView.buffer; +} +function checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) { + if (!(inputBuffer instanceof Uint8Array)) { + baseBlock.error = "Wrong parameter: inputBuffer must be 'Uint8Array'"; + return false; + } + if (!inputBuffer.byteLength) { + baseBlock.error = "Wrong parameter: inputBuffer has zero length"; + return false; + } + if (inputOffset < 0) { + baseBlock.error = "Wrong parameter: inputOffset less than zero"; + return false; + } + if (inputLength < 0) { + baseBlock.error = "Wrong parameter: inputLength less than zero"; + return false; + } + if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) { + baseBlock.error = "End of input reached before message was fully decoded (inconsistent offset and length values)"; + return false; + } + return true; +} + +class ViewWriter { + constructor() { + this.items = []; + } + write(buf) { + this.items.push(buf); + } + final() { + return concat(this.items); + } +} + +const powers2 = [new Uint8Array([1])]; +const digitsString = "0123456789"; +const NAME = "name"; +const VALUE_HEX_VIEW = "valueHexView"; +const IS_HEX_ONLY = "isHexOnly"; +const ID_BLOCK = "idBlock"; +const TAG_CLASS = "tagClass"; +const TAG_NUMBER = "tagNumber"; +const IS_CONSTRUCTED = "isConstructed"; +const FROM_BER = "fromBER"; +const TO_BER = "toBER"; +const LOCAL = "local"; +const EMPTY_STRING = ""; +const EMPTY_BUFFER = new ArrayBuffer(0); +const EMPTY_VIEW = new Uint8Array(0); +const END_OF_CONTENT_NAME = "EndOfContent"; +const OCTET_STRING_NAME = "OCTET STRING"; +const BIT_STRING_NAME = "BIT STRING"; + +function HexBlock(BaseClass) { + var _a; + return _a = class Some extends BaseClass { + get valueHex() { + return this.valueHexView.slice().buffer; + } + set valueHex(value) { + this.valueHexView = new Uint8Array(value); + } + constructor(...args) { + var _b; + super(...args); + const params = args[0] || {}; + this.isHexOnly = (_b = params.isHexOnly) !== null && _b !== void 0 ? _b : false; + this.valueHexView = params.valueHex ? pvtsutils__namespace.BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW; + } + fromBER(inputBuffer, inputOffset, inputLength, _context) { + const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer; + if (!checkBufferParams(this, view, inputOffset, inputLength)) { + return -1; + } + const endLength = inputOffset + inputLength; + this.valueHexView = view.subarray(inputOffset, endLength); + if (!this.valueHexView.length) { + this.warnings.push("Zero buffer length"); + return inputOffset; + } + this.blockLength = inputLength; + return endLength; + } + toBER(sizeOnly = false) { + if (!this.isHexOnly) { + this.error = "Flag 'isHexOnly' is not set, abort"; + return EMPTY_BUFFER; + } + if (sizeOnly) { + return new ArrayBuffer(this.valueHexView.byteLength); + } + return (this.valueHexView.byteLength === this.valueHexView.buffer.byteLength) + ? this.valueHexView.buffer + : this.valueHexView.slice().buffer; + } + toJSON() { + return { + ...super.toJSON(), + isHexOnly: this.isHexOnly, + valueHex: pvtsutils__namespace.Convert.ToHex(this.valueHexView), + }; + } + }, + _a.NAME = "hexBlock", + _a; +} + +class LocalBaseBlock { + static blockName() { + return this.NAME; + } + get valueBeforeDecode() { + return this.valueBeforeDecodeView.slice().buffer; + } + set valueBeforeDecode(value) { + this.valueBeforeDecodeView = new Uint8Array(value); + } + constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW, } = {}) { + this.blockLength = blockLength; + this.error = error; + this.warnings = warnings; + this.valueBeforeDecodeView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(valueBeforeDecode); + } + toJSON() { + return { + blockName: this.constructor.NAME, + blockLength: this.blockLength, + error: this.error, + warnings: this.warnings, + valueBeforeDecode: pvtsutils__namespace.Convert.ToHex(this.valueBeforeDecodeView), + }; + } +} +LocalBaseBlock.NAME = "baseBlock"; + +class ValueBlock extends LocalBaseBlock { + fromBER(_inputBuffer, _inputOffset, _inputLength, _context) { + throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'"); + } + toBER(_sizeOnly, _writer) { + throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'"); + } +} +ValueBlock.NAME = "valueBlock"; + +class LocalIdentificationBlock extends HexBlock(LocalBaseBlock) { + constructor({ idBlock = {} } = {}) { + var _a, _b, _c, _d; + super(); + if (idBlock) { + this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false; + this.valueHexView = idBlock.valueHex + ? pvtsutils__namespace.BufferSourceConverter.toUint8Array(idBlock.valueHex) + : EMPTY_VIEW; + this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1; + this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1; + this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false; + } + else { + this.tagClass = -1; + this.tagNumber = -1; + this.isConstructed = false; + } + } + toBER(sizeOnly = false) { + let firstOctet = 0; + switch (this.tagClass) { + case 1: + firstOctet |= 0x00; + break; + case 2: + firstOctet |= 0x40; + break; + case 3: + firstOctet |= 0x80; + break; + case 4: + firstOctet |= 0xC0; + break; + default: + this.error = "Unknown tag class"; + return EMPTY_BUFFER; + } + if (this.isConstructed) + firstOctet |= 0x20; + if (this.tagNumber < 31 && !this.isHexOnly) { + const retView = new Uint8Array(1); + if (!sizeOnly) { + let number = this.tagNumber; + number &= 0x1F; + firstOctet |= number; + retView[0] = firstOctet; + } + return retView.buffer; + } + if (!this.isHexOnly) { + const encodedBuf = pvutils__namespace.utilToBase(this.tagNumber, 7); + const encodedView = new Uint8Array(encodedBuf); + const size = encodedBuf.byteLength; + const retView = new Uint8Array(size + 1); + retView[0] = (firstOctet | 0x1F); + if (!sizeOnly) { + for (let i = 0; i < (size - 1); i++) + retView[i + 1] = encodedView[i] | 0x80; + retView[size] = encodedView[size - 1]; + } + return retView.buffer; + } + const retView = new Uint8Array(this.valueHexView.byteLength + 1); + retView[0] = (firstOctet | 0x1F); + if (!sizeOnly) { + const curView = this.valueHexView; + for (let i = 0; i < (curView.length - 1); i++) + retView[i + 1] = curView[i] | 0x80; + retView[this.valueHexView.byteLength] = curView[curView.length - 1]; + } + return retView.buffer; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const inputView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + if (intBuffer.length === 0) { + this.error = "Zero buffer length"; + return -1; + } + const tagClassMask = intBuffer[0] & 0xC0; + switch (tagClassMask) { + case 0x00: + this.tagClass = (1); + break; + case 0x40: + this.tagClass = (2); + break; + case 0x80: + this.tagClass = (3); + break; + case 0xC0: + this.tagClass = (4); + break; + default: + this.error = "Unknown tag class"; + return -1; + } + this.isConstructed = (intBuffer[0] & 0x20) === 0x20; + this.isHexOnly = false; + const tagNumberMask = intBuffer[0] & 0x1F; + if (tagNumberMask !== 0x1F) { + this.tagNumber = (tagNumberMask); + this.blockLength = 1; + } + else { + let count = 0; + while (true) { + const tagByteIndex = count + 1; + if (tagByteIndex >= intBuffer.length) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + count++; + if ((intBuffer[tagByteIndex] & 0x80) === 0x00) + break; + } + this.blockLength = (count + 1); + const intTagNumberBuffer = this.valueHexView = new Uint8Array(count); + for (let i = 0; i < count; i++) + intTagNumberBuffer[i] = intBuffer[i + 1] & 0x7F; + if (this.blockLength <= 9) + this.tagNumber = pvutils__namespace.utilFromBase(intTagNumberBuffer, 7); + else { + this.isHexOnly = true; + this.warnings.push("Tag too long, represented as hex-coded"); + } + } + if (((this.tagClass === 1)) + && (this.isConstructed)) { + switch (this.tagNumber) { + case 1: + case 2: + case 5: + case 6: + case 9: + case 13: + case 14: + case 23: + case 24: + case 31: + case 32: + case 33: + case 34: + this.error = "Constructed encoding used for primitive type"; + return -1; + } + } + return (inputOffset + this.blockLength); + } + toJSON() { + return { + ...super.toJSON(), + tagClass: this.tagClass, + tagNumber: this.tagNumber, + isConstructed: this.isConstructed, + }; + } +} +LocalIdentificationBlock.NAME = "identificationBlock"; + +class LocalLengthBlock extends LocalBaseBlock { + constructor({ lenBlock = {} } = {}) { + var _a, _b, _c; + super(); + this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false; + this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false; + this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const view = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, view, inputOffset, inputLength)) { + return -1; + } + const intBuffer = view.subarray(inputOffset, inputOffset + inputLength); + if (intBuffer.length === 0) { + this.error = "Zero buffer length"; + return -1; + } + if (intBuffer[0] === 0xFF) { + this.error = "Length block 0xFF is reserved by standard"; + return -1; + } + this.isIndefiniteForm = intBuffer[0] === 0x80; + if (this.isIndefiniteForm) { + this.blockLength = 1; + return (inputOffset + this.blockLength); + } + this.longFormUsed = !!(intBuffer[0] & 0x80); + if (this.longFormUsed === false) { + this.length = (intBuffer[0]); + this.blockLength = 1; + return (inputOffset + this.blockLength); + } + const count = intBuffer[0] & 0x7F; + if (count > 8) { + this.error = "Too big integer"; + return -1; + } + if ((count + 1) > intBuffer.length) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + const lenOffset = inputOffset + 1; + const lengthBufferView = view.subarray(lenOffset, lenOffset + count); + if (lengthBufferView[count - 1] === 0x00) + this.warnings.push("Needlessly long encoded length"); + this.length = pvutils__namespace.utilFromBase(lengthBufferView, 8); + if (this.longFormUsed && (this.length <= 127)) + this.warnings.push("Unnecessary usage of long length form"); + this.blockLength = count + 1; + return (inputOffset + this.blockLength); + } + toBER(sizeOnly = false) { + let retBuf; + let retView; + if (this.length > 127) + this.longFormUsed = true; + if (this.isIndefiniteForm) { + retBuf = new ArrayBuffer(1); + if (sizeOnly === false) { + retView = new Uint8Array(retBuf); + retView[0] = 0x80; + } + return retBuf; + } + if (this.longFormUsed) { + const encodedBuf = pvutils__namespace.utilToBase(this.length, 8); + if (encodedBuf.byteLength > 127) { + this.error = "Too big length"; + return (EMPTY_BUFFER); + } + retBuf = new ArrayBuffer(encodedBuf.byteLength + 1); + if (sizeOnly) + return retBuf; + const encodedView = new Uint8Array(encodedBuf); + retView = new Uint8Array(retBuf); + retView[0] = encodedBuf.byteLength | 0x80; + for (let i = 0; i < encodedBuf.byteLength; i++) + retView[i + 1] = encodedView[i]; + return retBuf; + } + retBuf = new ArrayBuffer(1); + if (sizeOnly === false) { + retView = new Uint8Array(retBuf); + retView[0] = this.length; + } + return retBuf; + } + toJSON() { + return { + ...super.toJSON(), + isIndefiniteForm: this.isIndefiniteForm, + longFormUsed: this.longFormUsed, + length: this.length, + }; + } +} +LocalLengthBlock.NAME = "lengthBlock"; + +const typeStore = {}; + +class BaseBlock extends LocalBaseBlock { + constructor({ name = EMPTY_STRING, optional = false, primitiveSchema, ...parameters } = {}, valueBlockType) { + super(parameters); + this.name = name; + this.optional = optional; + if (primitiveSchema) { + this.primitiveSchema = primitiveSchema; + } + this.idBlock = new LocalIdentificationBlock(parameters); + this.lenBlock = new LocalLengthBlock(parameters); + this.valueBlock = valueBlockType ? new valueBlockType(parameters) : new ValueBlock(parameters); + } + fromBER(inputBuffer, inputOffset, inputLength, context) { + const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) + ? inputLength + : this.lenBlock.length, context); + if (resultOffset === -1) { + this.error = this.valueBlock.error; + return resultOffset; + } + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + if (!this.valueBlock.error.length) + this.blockLength += this.valueBlock.blockLength; + return resultOffset; + } + toBER(sizeOnly, writer) { + const _writer = writer || new ViewWriter(); + if (!writer) { + prepareIndefiniteForm(this); + } + const idBlockBuf = this.idBlock.toBER(sizeOnly); + _writer.write(idBlockBuf); + if (this.lenBlock.isIndefiniteForm) { + _writer.write(new Uint8Array([0x80]).buffer); + this.valueBlock.toBER(sizeOnly, _writer); + _writer.write(new ArrayBuffer(2)); + } + else { + const valueBlockBuf = this.valueBlock.toBER(sizeOnly); + this.lenBlock.length = valueBlockBuf.byteLength; + const lenBlockBuf = this.lenBlock.toBER(sizeOnly); + _writer.write(lenBlockBuf); + _writer.write(valueBlockBuf); + } + if (!writer) { + return _writer.final(); + } + return EMPTY_BUFFER; + } + toJSON() { + const object = { + ...super.toJSON(), + idBlock: this.idBlock.toJSON(), + lenBlock: this.lenBlock.toJSON(), + valueBlock: this.valueBlock.toJSON(), + name: this.name, + optional: this.optional, + }; + if (this.primitiveSchema) + object.primitiveSchema = this.primitiveSchema.toJSON(); + return object; + } + toString(encoding = "ascii") { + if (encoding === "ascii") { + return this.onAsciiEncoding(); + } + return pvtsutils__namespace.Convert.ToHex(this.toBER()); + } + onAsciiEncoding() { + const name = this.constructor.NAME; + const value = pvtsutils__namespace.Convert.ToHex(this.valueBlock.valueBeforeDecodeView); + return `${name} : ${value}`; + } + isEqual(other) { + if (this === other) { + return true; + } + if (!(other instanceof this.constructor)) { + return false; + } + const thisRaw = this.toBER(); + const otherRaw = other.toBER(); + return pvutils__namespace.isEqualBuffer(thisRaw, otherRaw); + } +} +BaseBlock.NAME = "BaseBlock"; +function prepareIndefiniteForm(baseBlock) { + var _a; + if (baseBlock instanceof typeStore.Constructed) { + for (const value of baseBlock.valueBlock.value) { + if (prepareIndefiniteForm(value)) { + baseBlock.lenBlock.isIndefiniteForm = true; + } + } + } + return !!((_a = baseBlock.lenBlock) === null || _a === void 0 ? void 0 : _a.isIndefiniteForm); +} + +class BaseStringBlock extends BaseBlock { + getValue() { + return this.valueBlock.value; + } + setValue(value) { + this.valueBlock.value = value; + } + constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) { + super(parameters, stringValueBlockType); + if (value) { + this.fromString(value); + } + } + fromBER(inputBuffer, inputOffset, inputLength) { + const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) + ? inputLength + : this.lenBlock.length); + if (resultOffset === -1) { + this.error = this.valueBlock.error; + return resultOffset; + } + this.fromBuffer(this.valueBlock.valueHexView); + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + if (!this.valueBlock.error.length) + this.blockLength += this.valueBlock.blockLength; + return resultOffset; + } + onAsciiEncoding() { + return `${this.constructor.NAME} : '${this.valueBlock.value}'`; + } +} +BaseStringBlock.NAME = "BaseStringBlock"; + +class LocalPrimitiveValueBlock extends HexBlock(ValueBlock) { + constructor({ isHexOnly = true, ...parameters } = {}) { + super(parameters); + this.isHexOnly = isHexOnly; + } +} +LocalPrimitiveValueBlock.NAME = "PrimitiveValueBlock"; + +var _a$w; +class Primitive extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalPrimitiveValueBlock); + this.idBlock.isConstructed = false; + } +} +_a$w = Primitive; +(() => { + typeStore.Primitive = _a$w; +})(); +Primitive.NAME = "PRIMITIVE"; + +const DEFAULT_MAX_DEPTH = 100; +const DEFAULT_MAX_NODES = 10000; +const DEFAULT_MAX_CONTENT_LENGTH = 16 * 1024 * 1024; +const MAX_DEPTH_EXCEEDED_ERROR = "Maximum ASN.1 nesting depth exceeded"; +const MAX_NODES_EXCEEDED_ERROR = "Maximum ASN.1 node count exceeded"; +const MAX_CONTENT_LENGTH_EXCEEDED_ERROR = "Maximum ASN.1 content length exceeded"; +function createFromBerContext(options = {}) { + var _a, _b, _c; + return { + depth: 0, + maxDepth: (_a = options.maxDepth) !== null && _a !== void 0 ? _a : DEFAULT_MAX_DEPTH, + nodesCount: 0, + maxNodes: (_b = options.maxNodes) !== null && _b !== void 0 ? _b : DEFAULT_MAX_NODES, + maxContentLength: (_c = options.maxContentLength) !== null && _c !== void 0 ? _c : DEFAULT_MAX_CONTENT_LENGTH, + }; +} +function createErrorResult(error) { + const result = new BaseBlock({}, ValueBlock); + result.error = error; + return { + offset: -1, + result, + }; +} +function checkNodesLimit(context) { + context.nodesCount += 1; + if (context.nodesCount > context.maxNodes) { + return MAX_NODES_EXCEEDED_ERROR; + } + return undefined; +} +function checkContentLengthLimit(inputLength, context) { + if (inputLength > context.maxContentLength) { + return MAX_CONTENT_LENGTH_EXCEEDED_ERROR; + } + return undefined; +} +function localFromBERWithChildContext(inputBuffer, inputOffset, inputLength, context) { + const childDepth = context.depth + 1; + if (childDepth > context.maxDepth) { + return createErrorResult(MAX_DEPTH_EXCEEDED_ERROR); + } + context.depth = childDepth; + try { + return localFromBER(inputBuffer, inputOffset, inputLength, context); + } + finally { + context.depth -= 1; + } +} +function localChangeType(inputObject, newType) { + if (inputObject instanceof newType) { + return inputObject; + } + const newObject = new newType(); + newObject.idBlock = inputObject.idBlock; + newObject.lenBlock = inputObject.lenBlock; + newObject.warnings = inputObject.warnings; + newObject.valueBeforeDecodeView = inputObject.valueBeforeDecodeView; + return newObject; +} +function localFromBER(inputBuffer, inputOffset = 0, inputLength = inputBuffer.length, context = createFromBerContext()) { + const incomingOffset = inputOffset; + let returnObject = new BaseBlock({}, ValueBlock); + const baseBlock = new LocalBaseBlock(); + if (!checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength)) { + returnObject.error = baseBlock.error; + return { + offset: -1, + result: returnObject, + }; + } + const intBuffer = inputBuffer.subarray(inputOffset, inputOffset + inputLength); + if (!intBuffer.length) { + returnObject.error = "Zero buffer length"; + return { + offset: -1, + result: returnObject, + }; + } + const nodesLimitError = checkNodesLimit(context); + if (nodesLimitError) { + returnObject.error = nodesLimitError; + return { + offset: -1, + result: returnObject, + }; + } + let resultOffset = returnObject.idBlock.fromBER(inputBuffer, inputOffset, inputLength); + if (returnObject.idBlock.warnings.length) { + returnObject.warnings.concat(returnObject.idBlock.warnings); + } + if (resultOffset === -1) { + returnObject.error = returnObject.idBlock.error; + return { + offset: -1, + result: returnObject, + }; + } + inputOffset = resultOffset; + inputLength -= returnObject.idBlock.blockLength; + resultOffset = returnObject.lenBlock.fromBER(inputBuffer, inputOffset, inputLength); + if (returnObject.lenBlock.warnings.length) { + returnObject.warnings.concat(returnObject.lenBlock.warnings); + } + if (resultOffset === -1) { + returnObject.error = returnObject.lenBlock.error; + return { + offset: -1, + result: returnObject, + }; + } + inputOffset = resultOffset; + inputLength -= returnObject.lenBlock.blockLength; + const valueLength = returnObject.lenBlock.isIndefiniteForm ? inputLength : returnObject.lenBlock.length; + const contentLengthError = checkContentLengthLimit(valueLength, context); + if (contentLengthError) { + returnObject.error = contentLengthError; + return { + offset: -1, + result: returnObject, + }; + } + if (!returnObject.idBlock.isConstructed + && returnObject.lenBlock.isIndefiniteForm) { + returnObject.error = "Indefinite length form used for primitive encoding form"; + return { + offset: -1, + result: returnObject, + }; + } + let newASN1Type = BaseBlock; + switch (returnObject.idBlock.tagClass) { + case 1: + if ((returnObject.idBlock.tagNumber >= 37) + && (returnObject.idBlock.isHexOnly === false)) { + returnObject.error = "UNIVERSAL 37 and upper tags are reserved by ASN.1 standard"; + return { + offset: -1, + result: returnObject, + }; + } + switch (returnObject.idBlock.tagNumber) { + case 0: + if ((returnObject.idBlock.isConstructed) + && (returnObject.lenBlock.length > 0)) { + returnObject.error = "Type [UNIVERSAL 0] is reserved"; + return { + offset: -1, + result: returnObject, + }; + } + newASN1Type = typeStore.EndOfContent; + break; + case 1: + newASN1Type = typeStore.Boolean; + break; + case 2: + newASN1Type = typeStore.Integer; + break; + case 3: + newASN1Type = typeStore.BitString; + break; + case 4: + newASN1Type = typeStore.OctetString; + break; + case 5: + newASN1Type = typeStore.Null; + break; + case 6: + newASN1Type = typeStore.ObjectIdentifier; + break; + case 10: + newASN1Type = typeStore.Enumerated; + break; + case 12: + newASN1Type = typeStore.Utf8String; + break; + case 13: + newASN1Type = typeStore.RelativeObjectIdentifier; + break; + case 14: + newASN1Type = typeStore.TIME; + break; + case 15: + returnObject.error = "[UNIVERSAL 15] is reserved by ASN.1 standard"; + return { + offset: -1, + result: returnObject, + }; + case 16: + newASN1Type = typeStore.Sequence; + break; + case 17: + newASN1Type = typeStore.Set; + break; + case 18: + newASN1Type = typeStore.NumericString; + break; + case 19: + newASN1Type = typeStore.PrintableString; + break; + case 20: + newASN1Type = typeStore.TeletexString; + break; + case 21: + newASN1Type = typeStore.VideotexString; + break; + case 22: + newASN1Type = typeStore.IA5String; + break; + case 23: + newASN1Type = typeStore.UTCTime; + break; + case 24: + newASN1Type = typeStore.GeneralizedTime; + break; + case 25: + newASN1Type = typeStore.GraphicString; + break; + case 26: + newASN1Type = typeStore.VisibleString; + break; + case 27: + newASN1Type = typeStore.GeneralString; + break; + case 28: + newASN1Type = typeStore.UniversalString; + break; + case 29: + newASN1Type = typeStore.CharacterString; + break; + case 30: + newASN1Type = typeStore.BmpString; + break; + case 31: + newASN1Type = typeStore.DATE; + break; + case 32: + newASN1Type = typeStore.TimeOfDay; + break; + case 33: + newASN1Type = typeStore.DateTime; + break; + case 34: + newASN1Type = typeStore.Duration; + break; + default: { + const newObject = returnObject.idBlock.isConstructed + ? new typeStore.Constructed() + : new typeStore.Primitive(); + newObject.idBlock = returnObject.idBlock; + newObject.lenBlock = returnObject.lenBlock; + newObject.warnings = returnObject.warnings; + returnObject = newObject; + } + } + break; + case 2: + case 3: + case 4: + default: { + newASN1Type = returnObject.idBlock.isConstructed + ? typeStore.Constructed + : typeStore.Primitive; + } + } + returnObject = localChangeType(returnObject, newASN1Type); + resultOffset = returnObject.fromBER(inputBuffer, inputOffset, valueLength, context); + returnObject.valueBeforeDecodeView = inputBuffer.subarray(incomingOffset, incomingOffset + returnObject.blockLength); + return { + offset: resultOffset, + result: returnObject, + }; +} +function fromBER(inputBuffer, options = {}) { + if (!inputBuffer.byteLength) { + const result = new BaseBlock({}, ValueBlock); + result.error = "Input buffer has zero length"; + return { + offset: -1, + result, + }; + } + return localFromBER(pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer).slice(), 0, inputBuffer.byteLength, createFromBerContext(options)); +} + +function checkLen(indefiniteLength, length) { + if (indefiniteLength) { + return 1; + } + return length; +} +class LocalConstructedValueBlock extends ValueBlock { + constructor({ value = [], isIndefiniteForm = false, ...parameters } = {}) { + super(parameters); + this.value = value; + this.isIndefiniteForm = isIndefiniteForm; + } + fromBER(inputBuffer, inputOffset, inputLength, context) { + const view = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + const parseContext = context !== null && context !== void 0 ? context : createFromBerContext(); + if (!checkBufferParams(this, view, inputOffset, inputLength)) { + return -1; + } + this.valueBeforeDecodeView = view.subarray(inputOffset, inputOffset + inputLength); + if (this.valueBeforeDecodeView.length === 0) { + this.warnings.push("Zero buffer length"); + return inputOffset; + } + let currentOffset = inputOffset; + while (checkLen(this.isIndefiniteForm, inputLength) > 0) { + const returnObject = localFromBERWithChildContext(view, currentOffset, inputLength, parseContext); + if (returnObject.offset === -1) { + this.error = returnObject.result.error; + this.warnings.concat(returnObject.result.warnings); + return -1; + } + currentOffset = returnObject.offset; + this.blockLength += returnObject.result.blockLength; + inputLength -= returnObject.result.blockLength; + this.value.push(returnObject.result); + if (this.isIndefiniteForm && returnObject.result.constructor.NAME === END_OF_CONTENT_NAME) { + break; + } + } + if (this.isIndefiniteForm) { + if (this.value[this.value.length - 1].constructor.NAME === END_OF_CONTENT_NAME) { + this.value.pop(); + } + else { + this.warnings.push("No EndOfContent block encoded"); + } + } + return currentOffset; + } + toBER(sizeOnly, writer) { + const _writer = writer || new ViewWriter(); + for (let i = 0; i < this.value.length; i++) { + this.value[i].toBER(sizeOnly, _writer); + } + if (!writer) { + return _writer.final(); + } + return EMPTY_BUFFER; + } + toJSON() { + const object = { + ...super.toJSON(), + isIndefiniteForm: this.isIndefiniteForm, + value: [], + }; + for (const value of this.value) { + object.value.push(value.toJSON()); + } + return object; + } +} +LocalConstructedValueBlock.NAME = "ConstructedValueBlock"; + +var _a$v; +class Constructed extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalConstructedValueBlock); + this.idBlock.isConstructed = true; + } + fromBER(inputBuffer, inputOffset, inputLength, context) { + this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; + const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length, context); + if (resultOffset === -1) { + this.error = this.valueBlock.error; + return resultOffset; + } + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + if (!this.valueBlock.error.length) + this.blockLength += this.valueBlock.blockLength; + return resultOffset; + } + onAsciiEncoding() { + const values = []; + for (const value of this.valueBlock.value) { + values.push(value.toString("ascii").split("\n").map((o) => ` ${o}`).join("\n")); + } + const blockName = this.idBlock.tagClass === 3 + ? `[${this.idBlock.tagNumber}]` + : this.constructor.NAME; + return values.length + ? `${blockName} :\n${values.join("\n")}` + : `${blockName} :`; + } +} +_a$v = Constructed; +(() => { + typeStore.Constructed = _a$v; +})(); +Constructed.NAME = "CONSTRUCTED"; + +class LocalEndOfContentValueBlock extends ValueBlock { + fromBER(inputBuffer, inputOffset, _inputLength) { + return inputOffset; + } + toBER(_sizeOnly) { + return EMPTY_BUFFER; + } +} +LocalEndOfContentValueBlock.override = "EndOfContentValueBlock"; + +var _a$u; +class EndOfContent extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalEndOfContentValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 0; + } +} +_a$u = EndOfContent; +(() => { + typeStore.EndOfContent = _a$u; +})(); +EndOfContent.NAME = END_OF_CONTENT_NAME; + +var _a$t; +class Null extends BaseBlock { + constructor(parameters = {}) { + super(parameters, ValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 5; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (this.lenBlock.length > 0) + this.warnings.push("Non-zero length of value block for Null type"); + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + this.blockLength += inputLength; + if ((inputOffset + inputLength) > inputBuffer.byteLength) { + this.error = "End of input reached before message was fully decoded (inconsistent offset and length values)"; + return -1; + } + return (inputOffset + inputLength); + } + toBER(sizeOnly, writer) { + const retBuf = new ArrayBuffer(2); + if (!sizeOnly) { + const retView = new Uint8Array(retBuf); + retView[0] = 0x05; + retView[1] = 0x00; + } + if (writer) { + writer.write(retBuf); + } + return retBuf; + } + onAsciiEncoding() { + return `${this.constructor.NAME}`; + } +} +_a$t = Null; +(() => { + typeStore.Null = _a$t; +})(); +Null.NAME = "NULL"; + +class LocalBooleanValueBlock extends HexBlock(ValueBlock) { + get value() { + for (const octet of this.valueHexView) { + if (octet > 0) { + return true; + } + } + return false; + } + set value(value) { + this.valueHexView[0] = value ? 0xFF : 0x00; + } + constructor({ value, ...parameters } = {}) { + super(parameters); + if (parameters.valueHex) { + this.valueHexView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(parameters.valueHex); + } + else { + this.valueHexView = new Uint8Array(1); + } + if (value) { + this.value = value; + } + } + fromBER(inputBuffer, inputOffset, inputLength) { + const inputView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + this.valueHexView = inputView.subarray(inputOffset, inputOffset + inputLength); + if (inputLength > 1) + this.warnings.push("Boolean value encoded in more then 1 octet"); + this.isHexOnly = true; + pvutils__namespace.utilDecodeTC.call(this); + this.blockLength = inputLength; + return (inputOffset + inputLength); + } + toBER() { + return this.valueHexView.slice(); + } + toJSON() { + return { + ...super.toJSON(), + value: this.value, + }; + } +} +LocalBooleanValueBlock.NAME = "BooleanValueBlock"; + +var _a$s; +class Boolean extends BaseBlock { + getValue() { + return this.valueBlock.value; + } + setValue(value) { + this.valueBlock.value = value; + } + constructor(parameters = {}) { + super(parameters, LocalBooleanValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 1; + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.getValue}`; + } +} +_a$s = Boolean; +(() => { + typeStore.Boolean = _a$s; +})(); +Boolean.NAME = "BOOLEAN"; + +class LocalOctetStringValueBlock extends HexBlock(LocalConstructedValueBlock) { + constructor({ isConstructed = false, ...parameters } = {}) { + super(parameters); + this.isConstructed = isConstructed; + } + fromBER(inputBuffer, inputOffset, inputLength, context) { + let resultOffset = 0; + if (this.isConstructed) { + this.isHexOnly = false; + resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength, context); + if (resultOffset === -1) + return resultOffset; + for (let i = 0; i < this.value.length; i++) { + const currentBlockName = this.value[i].constructor.NAME; + if (currentBlockName === END_OF_CONTENT_NAME) { + if (this.isIndefiniteForm) + break; + else { + this.error = "EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only"; + return -1; + } + } + if (currentBlockName !== OCTET_STRING_NAME) { + this.error = "OCTET STRING may consists of OCTET STRINGs only"; + return -1; + } + } + } + else { + this.isHexOnly = true; + resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength); + this.blockLength = inputLength; + } + return resultOffset; + } + toBER(sizeOnly, writer) { + if (this.isConstructed) + return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer); + return sizeOnly + ? new ArrayBuffer(this.valueHexView.byteLength) + : this.valueHexView.slice().buffer; + } + toJSON() { + return { + ...super.toJSON(), + isConstructed: this.isConstructed, + }; + } +} +LocalOctetStringValueBlock.NAME = "OctetStringValueBlock"; + +var _a$r; +class OctetString extends BaseBlock { + constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) { + var _b, _c; + (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length)); + super({ + idBlock: { + isConstructed: parameters.isConstructed, + ...idBlock, + }, + lenBlock: { + ...lenBlock, + isIndefiniteForm: !!parameters.isIndefiniteForm, + }, + ...parameters, + }, LocalOctetStringValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 4; + } + fromBER(inputBuffer, inputOffset, inputLength, context) { + this.valueBlock.isConstructed = this.idBlock.isConstructed; + this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; + if (inputLength === 0) { + if (this.idBlock.error.length === 0) + this.blockLength += this.idBlock.blockLength; + if (this.lenBlock.error.length === 0) + this.blockLength += this.lenBlock.blockLength; + return inputOffset; + } + if (!this.valueBlock.isConstructed) { + const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer; + const buf = view.subarray(inputOffset, inputOffset + inputLength); + try { + if (buf.byteLength) { + const parseContext = context !== null && context !== void 0 ? context : createFromBerContext(); + const asn = localFromBERWithChildContext(buf, 0, buf.byteLength, parseContext); + if (asn.offset !== -1 && asn.offset === inputLength) { + this.valueBlock.value = [asn.result]; + } + } + } + catch { + } + } + return super.fromBER(inputBuffer, inputOffset, inputLength, context); + } + onAsciiEncoding() { + if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) { + return Constructed.prototype.onAsciiEncoding.call(this); + } + const name = this.constructor.NAME; + const value = pvtsutils__namespace.Convert.ToHex(this.valueBlock.valueHexView); + return `${name} : ${value}`; + } + getValue() { + if (!this.idBlock.isConstructed) { + return this.valueBlock.valueHexView.slice().buffer; + } + const array = []; + for (const content of this.valueBlock.value) { + if (content instanceof _a$r) { + array.push(content.valueBlock.valueHexView); + } + } + return pvtsutils__namespace.BufferSourceConverter.concat(array); + } +} +_a$r = OctetString; +(() => { + typeStore.OctetString = _a$r; +})(); +OctetString.NAME = OCTET_STRING_NAME; + +class LocalBitStringValueBlock extends HexBlock(LocalConstructedValueBlock) { + constructor({ unusedBits = 0, isConstructed = false, ...parameters } = {}) { + super(parameters); + this.unusedBits = unusedBits; + this.isConstructed = isConstructed; + this.blockLength = this.valueHexView.byteLength; + } + fromBER(inputBuffer, inputOffset, inputLength, context) { + if (!inputLength) { + return inputOffset; + } + let resultOffset = -1; + if (this.isConstructed) { + resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength, context); + if (resultOffset === -1) + return resultOffset; + for (const value of this.value) { + const currentBlockName = value.constructor.NAME; + if (currentBlockName === END_OF_CONTENT_NAME) { + if (this.isIndefiniteForm) + break; + else { + this.error = "EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only"; + return -1; + } + } + if (currentBlockName !== BIT_STRING_NAME) { + this.error = "BIT STRING may consists of BIT STRINGs only"; + return -1; + } + const valueBlock = value.valueBlock; + if ((this.unusedBits > 0) && (valueBlock.unusedBits > 0)) { + this.error = "Using of \"unused bits\" inside constructive BIT STRING allowed for least one only"; + return -1; + } + this.unusedBits = valueBlock.unusedBits; + } + return resultOffset; + } + const inputView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + this.unusedBits = intBuffer[0]; + if (this.unusedBits > 7) { + this.error = "Unused bits for BitString must be in range 0-7"; + return -1; + } + if (!this.unusedBits) { + const buf = intBuffer.subarray(1); + try { + if (buf.byteLength) { + const parseContext = context !== null && context !== void 0 ? context : createFromBerContext(); + const asn = localFromBERWithChildContext(buf, 0, buf.byteLength, parseContext); + if (asn.offset !== -1 && asn.offset === (inputLength - 1)) { + this.value = [asn.result]; + } + } + } + catch { + } + } + this.valueHexView = intBuffer.subarray(1); + this.blockLength = intBuffer.length; + return (inputOffset + inputLength); + } + toBER(sizeOnly, writer) { + if (this.isConstructed) { + return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer); + } + if (sizeOnly) { + return new ArrayBuffer(this.valueHexView.byteLength + 1); + } + if (!this.valueHexView.byteLength) { + const empty = new Uint8Array(1); + empty[0] = 0; + return empty.buffer; + } + const retView = new Uint8Array(this.valueHexView.length + 1); + retView[0] = this.unusedBits; + retView.set(this.valueHexView, 1); + return retView.buffer; + } + toJSON() { + return { + ...super.toJSON(), + unusedBits: this.unusedBits, + isConstructed: this.isConstructed, + }; + } +} +LocalBitStringValueBlock.NAME = "BitStringValueBlock"; + +var _a$q; +class BitString extends BaseBlock { + constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) { + var _b, _c; + (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length)); + super({ + idBlock: { + isConstructed: parameters.isConstructed, + ...idBlock, + }, + lenBlock: { + ...lenBlock, + isIndefiniteForm: !!parameters.isIndefiniteForm, + }, + ...parameters, + }, LocalBitStringValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 3; + } + fromBER(inputBuffer, inputOffset, inputLength, context) { + this.valueBlock.isConstructed = this.idBlock.isConstructed; + this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; + return super.fromBER(inputBuffer, inputOffset, inputLength, context); + } + onAsciiEncoding() { + if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) { + return Constructed.prototype.onAsciiEncoding.call(this); + } + else { + const bits = []; + const valueHex = this.valueBlock.valueHexView; + for (const byte of valueHex) { + bits.push(byte.toString(2).padStart(8, "0")); + } + const bitsStr = bits.join(""); + const name = this.constructor.NAME; + const value = bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits); + return `${name} : ${value}`; + } + } +} +_a$q = BitString; +(() => { + typeStore.BitString = _a$q; +})(); +BitString.NAME = BIT_STRING_NAME; + +var _a$p; +function viewAdd(first, second) { + const c = new Uint8Array([0]); + const firstView = new Uint8Array(first); + const secondView = new Uint8Array(second); + let firstViewCopy = firstView.slice(0); + const firstViewCopyLength = firstViewCopy.length - 1; + const secondViewCopy = secondView.slice(0); + const secondViewCopyLength = secondViewCopy.length - 1; + let value = 0; + const max = (secondViewCopyLength < firstViewCopyLength) ? firstViewCopyLength : secondViewCopyLength; + let counter = 0; + for (let i = max; i >= 0; i--, counter++) { + switch (true) { + case (counter < secondViewCopy.length): + value = firstViewCopy[firstViewCopyLength - counter] + secondViewCopy[secondViewCopyLength - counter] + c[0]; + break; + default: + value = firstViewCopy[firstViewCopyLength - counter] + c[0]; + } + c[0] = value / 10; + switch (true) { + case (counter >= firstViewCopy.length): + firstViewCopy = pvutils__namespace.utilConcatView(new Uint8Array([value % 10]), firstViewCopy); + break; + default: + firstViewCopy[firstViewCopyLength - counter] = value % 10; + } + } + if (c[0] > 0) + firstViewCopy = pvutils__namespace.utilConcatView(c, firstViewCopy); + return firstViewCopy; +} +function power2(n) { + if (n >= powers2.length) { + for (let p = powers2.length; p <= n; p++) { + const c = new Uint8Array([0]); + let digits = (powers2[p - 1]).slice(0); + for (let i = (digits.length - 1); i >= 0; i--) { + const newValue = new Uint8Array([(digits[i] << 1) + c[0]]); + c[0] = newValue[0] / 10; + digits[i] = newValue[0] % 10; + } + if (c[0] > 0) + digits = pvutils__namespace.utilConcatView(c, digits); + powers2.push(digits); + } + } + return powers2[n]; +} +function viewSub(first, second) { + let b = 0; + const firstView = new Uint8Array(first); + const secondView = new Uint8Array(second); + const firstViewCopy = firstView.slice(0); + const firstViewCopyLength = firstViewCopy.length - 1; + const secondViewCopy = secondView.slice(0); + const secondViewCopyLength = secondViewCopy.length - 1; + let value; + let counter = 0; + for (let i = secondViewCopyLength; i >= 0; i--, counter++) { + value = firstViewCopy[firstViewCopyLength - counter] - secondViewCopy[secondViewCopyLength - counter] - b; + switch (true) { + case (value < 0): + b = 1; + firstViewCopy[firstViewCopyLength - counter] = value + 10; + break; + default: + b = 0; + firstViewCopy[firstViewCopyLength - counter] = value; + } + } + if (b > 0) { + for (let i = (firstViewCopyLength - secondViewCopyLength + 1); i >= 0; i--, counter++) { + value = firstViewCopy[firstViewCopyLength - counter] - b; + if (value < 0) { + b = 1; + firstViewCopy[firstViewCopyLength - counter] = value + 10; + } + else { + b = 0; + firstViewCopy[firstViewCopyLength - counter] = value; + break; + } + } + } + return firstViewCopy.slice(); +} +class LocalIntegerValueBlock extends HexBlock(ValueBlock) { + setValueHex() { + if (this.valueHexView.length >= 4) { + this.warnings.push("Too big Integer for decoding, hex only"); + this.isHexOnly = true; + this._valueDec = 0; + } + else { + this.isHexOnly = false; + if (this.valueHexView.length > 0) { + this._valueDec = pvutils__namespace.utilDecodeTC.call(this); + } + } + } + constructor({ value, ...parameters } = {}) { + super(parameters); + this._valueDec = 0; + if (parameters.valueHex) { + this.setValueHex(); + } + if (value !== undefined) { + this.valueDec = value; + } + } + set valueDec(v) { + this._valueDec = v; + this.isHexOnly = false; + this.valueHexView = new Uint8Array(pvutils__namespace.utilEncodeTC(v)); + } + get valueDec() { + return this._valueDec; + } + fromDER(inputBuffer, inputOffset, inputLength, expectedLength = 0) { + const offset = this.fromBER(inputBuffer, inputOffset, inputLength); + if (offset === -1) + return offset; + const view = this.valueHexView; + if ((view[0] === 0x00) && ((view[1] & 0x80) !== 0)) { + this.valueHexView = view.subarray(1); + } + else { + if (expectedLength !== 0) { + if (view.length < expectedLength) { + if ((expectedLength - view.length) > 1) + expectedLength = view.length + 1; + this.valueHexView = view.subarray(expectedLength - view.length); + } + } + } + return offset; + } + toDER(sizeOnly = false) { + const view = this.valueHexView; + switch (true) { + case ((view[0] & 0x80) !== 0): + { + const updatedView = new Uint8Array(this.valueHexView.length + 1); + updatedView[0] = 0x00; + updatedView.set(view, 1); + this.valueHexView = updatedView; + } + break; + case ((view[0] === 0x00) && ((view[1] & 0x80) === 0)): + { + this.valueHexView = this.valueHexView.subarray(1); + } + break; + } + return this.toBER(sizeOnly); + } + fromBER(inputBuffer, inputOffset, inputLength) { + const resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength); + if (resultOffset === -1) { + return resultOffset; + } + this.setValueHex(); + return resultOffset; + } + toBER(sizeOnly) { + return sizeOnly + ? new ArrayBuffer(this.valueHexView.length) + : this.valueHexView.slice().buffer; + } + toJSON() { + return { + ...super.toJSON(), + valueDec: this.valueDec, + }; + } + toString() { + const firstBit = (this.valueHexView.length * 8) - 1; + let digits = new Uint8Array((this.valueHexView.length * 8) / 3); + let bitNumber = 0; + let currentByte; + const asn1View = this.valueHexView; + let result = ""; + let flag = false; + for (let byteNumber = (asn1View.byteLength - 1); byteNumber >= 0; byteNumber--) { + currentByte = asn1View[byteNumber]; + for (let i = 0; i < 8; i++) { + if ((currentByte & 1) === 1) { + switch (bitNumber) { + case firstBit: + digits = viewSub(power2(bitNumber), digits); + result = "-"; + break; + default: + digits = viewAdd(digits, power2(bitNumber)); + } + } + bitNumber++; + currentByte >>= 1; + } + } + for (let i = 0; i < digits.length; i++) { + if (digits[i]) + flag = true; + if (flag) + result += digitsString.charAt(digits[i]); + } + if (flag === false) + result += digitsString.charAt(0); + return result; + } +} +_a$p = LocalIntegerValueBlock; +LocalIntegerValueBlock.NAME = "IntegerValueBlock"; +(() => { + Object.defineProperty(_a$p.prototype, "valueHex", { + set: function (v) { + this.valueHexView = new Uint8Array(v); + this.setValueHex(); + }, + get: function () { + return this.valueHexView.slice().buffer; + }, + }); +})(); + +var _a$o; +class Integer extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalIntegerValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 2; + } + toBigInt() { + assertBigInt(); + return BigInt(this.valueBlock.toString()); + } + static fromBigInt(value) { + assertBigInt(); + const bigIntValue = BigInt(value); + const writer = new ViewWriter(); + const hex = bigIntValue.toString(16).replace(/^-/, ""); + const view = new Uint8Array(pvtsutils__namespace.Convert.FromHex(hex)); + if (bigIntValue < 0) { + const first = new Uint8Array(view.length + (view[0] & 0x80 ? 1 : 0)); + first[0] |= 0x80; + const firstInt = BigInt(`0x${pvtsutils__namespace.Convert.ToHex(first)}`); + const secondInt = firstInt + bigIntValue; + const second = pvtsutils__namespace.BufferSourceConverter.toUint8Array(pvtsutils__namespace.Convert.FromHex(secondInt.toString(16))); + second[0] |= 0x80; + writer.write(second); + } + else { + if (view[0] & 0x80) { + writer.write(new Uint8Array([0])); + } + writer.write(view); + } + const res = new _a$o({ valueHex: writer.final() }); + return res; + } + convertToDER() { + const integer = new _a$o({ valueHex: this.valueBlock.valueHexView }); + integer.valueBlock.toDER(); + return integer; + } + convertFromDER() { + return new _a$o({ + valueHex: this.valueBlock.valueHexView[0] === 0 + ? this.valueBlock.valueHexView.subarray(1) + : this.valueBlock.valueHexView, + }); + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.valueBlock.toString()}`; + } +} +_a$o = Integer; +(() => { + typeStore.Integer = _a$o; +})(); +Integer.NAME = "INTEGER"; + +var _a$n; +class Enumerated extends Integer { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 10; + } +} +_a$n = Enumerated; +(() => { + typeStore.Enumerated = _a$n; +})(); +Enumerated.NAME = "ENUMERATED"; + +class LocalSidValueBlock extends HexBlock(ValueBlock) { + constructor({ valueDec = -1, isFirstSid = false, ...parameters } = {}) { + super(parameters); + this.valueDec = valueDec; + this.isFirstSid = isFirstSid; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (!inputLength) { + return inputOffset; + } + const inputView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + this.valueHexView = new Uint8Array(inputLength); + for (let i = 0; i < inputLength; i++) { + this.valueHexView[i] = intBuffer[i] & 0x7F; + this.blockLength++; + if ((intBuffer[i] & 0x80) === 0x00) + break; + } + const tempView = new Uint8Array(this.blockLength); + for (let i = 0; i < this.blockLength; i++) { + tempView[i] = this.valueHexView[i]; + } + this.valueHexView = tempView; + if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + if (this.valueHexView[0] === 0x00) + this.warnings.push("Needlessly long format of SID encoding"); + if (this.blockLength <= 8) + this.valueDec = pvutils__namespace.utilFromBase(this.valueHexView, 7); + else { + this.isHexOnly = true; + this.warnings.push("Too big SID for decoding, hex only"); + } + return (inputOffset + this.blockLength); + } + set valueBigInt(value) { + assertBigInt(); + let bits = BigInt(value).toString(2); + while (bits.length % 7) { + bits = "0" + bits; + } + const bytes = new Uint8Array(bits.length / 7); + for (let i = 0; i < bytes.length; i++) { + bytes[i] = parseInt(bits.slice(i * 7, i * 7 + 7), 2) + (i + 1 < bytes.length ? 0x80 : 0); + } + this.fromBER(bytes.buffer, 0, bytes.length); + } + toBER(sizeOnly) { + if (this.isHexOnly) { + if (sizeOnly) + return (new ArrayBuffer(this.valueHexView.byteLength)); + const curView = this.valueHexView; + const retView = new Uint8Array(this.blockLength); + for (let i = 0; i < (this.blockLength - 1); i++) + retView[i] = curView[i] | 0x80; + retView[this.blockLength - 1] = curView[this.blockLength - 1]; + return retView.buffer; + } + const encodedBuf = pvutils__namespace.utilToBase(this.valueDec, 7); + if (encodedBuf.byteLength === 0) { + this.error = "Error during encoding SID value"; + return EMPTY_BUFFER; + } + const retView = new Uint8Array(encodedBuf.byteLength); + if (!sizeOnly) { + const encodedView = new Uint8Array(encodedBuf); + const len = encodedBuf.byteLength - 1; + for (let i = 0; i < len; i++) + retView[i] = encodedView[i] | 0x80; + retView[len] = encodedView[len]; + } + return retView; + } + toString() { + let result = ""; + if (this.isHexOnly) + result = pvtsutils__namespace.Convert.ToHex(this.valueHexView); + else { + if (this.isFirstSid) { + let sidValue = this.valueDec; + if (this.valueDec <= 39) + result = "0."; + else { + if (this.valueDec <= 79) { + result = "1."; + sidValue -= 40; + } + else { + result = "2."; + sidValue -= 80; + } + } + result += sidValue.toString(); + } + else + result = this.valueDec.toString(); + } + return result; + } + toJSON() { + return { + ...super.toJSON(), + valueDec: this.valueDec, + isFirstSid: this.isFirstSid, + }; + } +} +LocalSidValueBlock.NAME = "sidBlock"; + +class LocalObjectIdentifierValueBlock extends ValueBlock { + constructor({ value = EMPTY_STRING, ...parameters } = {}) { + super(parameters); + this.value = []; + if (value) { + this.fromString(value); + } + } + fromBER(inputBuffer, inputOffset, inputLength) { + let resultOffset = inputOffset; + while (inputLength > 0) { + const sidBlock = new LocalSidValueBlock(); + resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength); + if (resultOffset === -1) { + this.blockLength = 0; + this.error = sidBlock.error; + return resultOffset; + } + if (this.value.length === 0) + sidBlock.isFirstSid = true; + this.blockLength += sidBlock.blockLength; + inputLength -= sidBlock.blockLength; + this.value.push(sidBlock); + } + return resultOffset; + } + toBER(sizeOnly) { + const retBuffers = []; + for (let i = 0; i < this.value.length; i++) { + const valueBuf = this.value[i].toBER(sizeOnly); + if (valueBuf.byteLength === 0) { + this.error = this.value[i].error; + return EMPTY_BUFFER; + } + retBuffers.push(valueBuf); + } + return concat(retBuffers); + } + fromString(string) { + this.value = []; + let pos1 = 0; + let pos2 = 0; + let sid = ""; + let flag = false; + do { + pos2 = string.indexOf(".", pos1); + if (pos2 === -1) + sid = string.substring(pos1); + else + sid = string.substring(pos1, pos2); + pos1 = pos2 + 1; + if (flag) { + const sidBlock = this.value[0]; + let plus = 0; + switch (sidBlock.valueDec) { + case 0: + break; + case 1: + plus = 40; + break; + case 2: + plus = 80; + break; + default: + this.value = []; + return; + } + const parsedSID = parseInt(sid, 10); + if (isNaN(parsedSID)) + return; + sidBlock.valueDec = parsedSID + plus; + flag = false; + } + else { + const sidBlock = new LocalSidValueBlock(); + if (sid > Number.MAX_SAFE_INTEGER) { + assertBigInt(); + const sidValue = BigInt(sid); + sidBlock.valueBigInt = sidValue; + } + else { + sidBlock.valueDec = parseInt(sid, 10); + if (isNaN(sidBlock.valueDec)) + return; + } + if (!this.value.length) { + sidBlock.isFirstSid = true; + flag = true; + } + this.value.push(sidBlock); + } + } while (pos2 !== -1); + } + toString() { + let result = ""; + let isHexOnly = false; + for (let i = 0; i < this.value.length; i++) { + isHexOnly = this.value[i].isHexOnly; + let sidStr = this.value[i].toString(); + if (i !== 0) + result = `${result}.`; + if (isHexOnly) { + sidStr = `{${sidStr}}`; + if (this.value[i].isFirstSid) + result = `2.{${sidStr} - 80}`; + else + result += sidStr; + } + else + result += sidStr; + } + return result; + } + toJSON() { + const object = { + ...super.toJSON(), + value: this.toString(), + sidArray: [], + }; + for (let i = 0; i < this.value.length; i++) { + object.sidArray.push(this.value[i].toJSON()); + } + return object; + } +} +LocalObjectIdentifierValueBlock.NAME = "ObjectIdentifierValueBlock"; + +var _a$m; +class ObjectIdentifier extends BaseBlock { + getValue() { + return this.valueBlock.toString(); + } + setValue(value) { + this.valueBlock.fromString(value); + } + constructor(parameters = {}) { + super(parameters, LocalObjectIdentifierValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 6; + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`; + } + toJSON() { + return { + ...super.toJSON(), + value: this.getValue(), + }; + } +} +_a$m = ObjectIdentifier; +(() => { + typeStore.ObjectIdentifier = _a$m; +})(); +ObjectIdentifier.NAME = "OBJECT IDENTIFIER"; + +class LocalRelativeSidValueBlock extends HexBlock(LocalBaseBlock) { + constructor({ valueDec = 0, ...parameters } = {}) { + super(parameters); + this.valueDec = valueDec; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (inputLength === 0) + return inputOffset; + const inputView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) + return -1; + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + this.valueHexView = new Uint8Array(inputLength); + for (let i = 0; i < inputLength; i++) { + this.valueHexView[i] = intBuffer[i] & 0x7F; + this.blockLength++; + if ((intBuffer[i] & 0x80) === 0x00) + break; + } + const tempView = new Uint8Array(this.blockLength); + for (let i = 0; i < this.blockLength; i++) + tempView[i] = this.valueHexView[i]; + this.valueHexView = tempView; + if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + if (this.valueHexView[0] === 0x00) + this.warnings.push("Needlessly long format of SID encoding"); + if (this.blockLength <= 8) + this.valueDec = pvutils__namespace.utilFromBase(this.valueHexView, 7); + else { + this.isHexOnly = true; + this.warnings.push("Too big SID for decoding, hex only"); + } + return (inputOffset + this.blockLength); + } + toBER(sizeOnly) { + if (this.isHexOnly) { + if (sizeOnly) + return (new ArrayBuffer(this.valueHexView.byteLength)); + const curView = this.valueHexView; + const retView = new Uint8Array(this.blockLength); + for (let i = 0; i < (this.blockLength - 1); i++) + retView[i] = curView[i] | 0x80; + retView[this.blockLength - 1] = curView[this.blockLength - 1]; + return retView.buffer; + } + const encodedBuf = pvutils__namespace.utilToBase(this.valueDec, 7); + if (encodedBuf.byteLength === 0) { + this.error = "Error during encoding SID value"; + return EMPTY_BUFFER; + } + const retView = new Uint8Array(encodedBuf.byteLength); + if (!sizeOnly) { + const encodedView = new Uint8Array(encodedBuf); + const len = encodedBuf.byteLength - 1; + for (let i = 0; i < len; i++) + retView[i] = encodedView[i] | 0x80; + retView[len] = encodedView[len]; + } + return retView.buffer; + } + toString() { + let result = ""; + if (this.isHexOnly) + result = pvtsutils__namespace.Convert.ToHex(this.valueHexView); + else { + result = this.valueDec.toString(); + } + return result; + } + toJSON() { + return { + ...super.toJSON(), + valueDec: this.valueDec, + }; + } +} +LocalRelativeSidValueBlock.NAME = "relativeSidBlock"; + +class LocalRelativeObjectIdentifierValueBlock extends ValueBlock { + constructor({ value = EMPTY_STRING, ...parameters } = {}) { + super(parameters); + this.value = []; + if (value) { + this.fromString(value); + } + } + fromBER(inputBuffer, inputOffset, inputLength) { + let resultOffset = inputOffset; + while (inputLength > 0) { + const sidBlock = new LocalRelativeSidValueBlock(); + resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength); + if (resultOffset === -1) { + this.blockLength = 0; + this.error = sidBlock.error; + return resultOffset; + } + this.blockLength += sidBlock.blockLength; + inputLength -= sidBlock.blockLength; + this.value.push(sidBlock); + } + return resultOffset; + } + toBER(sizeOnly, _writer) { + const retBuffers = []; + for (let i = 0; i < this.value.length; i++) { + const valueBuf = this.value[i].toBER(sizeOnly); + if (valueBuf.byteLength === 0) { + this.error = this.value[i].error; + return EMPTY_BUFFER; + } + retBuffers.push(valueBuf); + } + return concat(retBuffers); + } + fromString(string) { + this.value = []; + let pos1 = 0; + let pos2 = 0; + let sid = ""; + do { + pos2 = string.indexOf(".", pos1); + if (pos2 === -1) + sid = string.substring(pos1); + else + sid = string.substring(pos1, pos2); + pos1 = pos2 + 1; + const sidBlock = new LocalRelativeSidValueBlock(); + sidBlock.valueDec = parseInt(sid, 10); + if (isNaN(sidBlock.valueDec)) + return true; + this.value.push(sidBlock); + } while (pos2 !== -1); + return true; + } + toString() { + let result = ""; + let isHexOnly = false; + for (let i = 0; i < this.value.length; i++) { + isHexOnly = this.value[i].isHexOnly; + let sidStr = this.value[i].toString(); + if (i !== 0) + result = `${result}.`; + if (isHexOnly) { + sidStr = `{${sidStr}}`; + result += sidStr; + } + else + result += sidStr; + } + return result; + } + toJSON() { + const object = { + ...super.toJSON(), + value: this.toString(), + sidArray: [], + }; + for (let i = 0; i < this.value.length; i++) + object.sidArray.push(this.value[i].toJSON()); + return object; + } +} +LocalRelativeObjectIdentifierValueBlock.NAME = "RelativeObjectIdentifierValueBlock"; + +var _a$l; +class RelativeObjectIdentifier extends BaseBlock { + getValue() { + return this.valueBlock.toString(); + } + setValue(value) { + this.valueBlock.fromString(value); + } + constructor(parameters = {}) { + super(parameters, LocalRelativeObjectIdentifierValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 13; + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`; + } + toJSON() { + return { + ...super.toJSON(), + value: this.getValue(), + }; + } +} +_a$l = RelativeObjectIdentifier; +(() => { + typeStore.RelativeObjectIdentifier = _a$l; +})(); +RelativeObjectIdentifier.NAME = "RelativeObjectIdentifier"; + +var _a$k; +class Sequence extends Constructed { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 16; + } +} +_a$k = Sequence; +(() => { + typeStore.Sequence = _a$k; +})(); +Sequence.NAME = "SEQUENCE"; + +var _a$j; +class Set extends Constructed { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 17; + } +} +_a$j = Set; +(() => { + typeStore.Set = _a$j; +})(); +Set.NAME = "SET"; + +class LocalStringValueBlock extends HexBlock(ValueBlock) { + constructor({ ...parameters } = {}) { + super(parameters); + this.isHexOnly = true; + this.value = EMPTY_STRING; + } + toJSON() { + return { + ...super.toJSON(), + value: this.value, + }; + } +} +LocalStringValueBlock.NAME = "StringValueBlock"; + +class LocalSimpleStringValueBlock extends LocalStringValueBlock { +} +LocalSimpleStringValueBlock.NAME = "SimpleStringValueBlock"; + +class LocalSimpleStringBlock extends BaseStringBlock { + constructor({ ...parameters } = {}) { + super(parameters, LocalSimpleStringValueBlock); + } + fromBuffer(inputBuffer) { + this.valueBlock.value = String.fromCharCode.apply(null, pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer)); + } + fromString(inputString) { + const strLen = inputString.length; + const view = this.valueBlock.valueHexView = new Uint8Array(strLen); + for (let i = 0; i < strLen; i++) + view[i] = inputString.charCodeAt(i); + this.valueBlock.value = inputString; + } +} +LocalSimpleStringBlock.NAME = "SIMPLE STRING"; + +class LocalUtf8StringValueBlock extends LocalSimpleStringBlock { + fromBuffer(inputBuffer) { + this.valueBlock.valueHexView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + try { + this.valueBlock.value = pvtsutils__namespace.Convert.ToUtf8String(inputBuffer); + } + catch (ex) { + this.warnings.push(`Error during "decodeURIComponent": ${ex}, using raw string`); + this.valueBlock.value = pvtsutils__namespace.Convert.ToBinary(inputBuffer); + } + } + fromString(inputString) { + this.valueBlock.valueHexView = new Uint8Array(pvtsutils__namespace.Convert.FromUtf8String(inputString)); + this.valueBlock.value = inputString; + } +} +LocalUtf8StringValueBlock.NAME = "Utf8StringValueBlock"; + +var _a$i; +class Utf8String extends LocalUtf8StringValueBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 12; + } +} +_a$i = Utf8String; +(() => { + typeStore.Utf8String = _a$i; +})(); +Utf8String.NAME = "UTF8String"; + +class LocalBmpStringValueBlock extends LocalSimpleStringBlock { + fromBuffer(inputBuffer) { + this.valueBlock.value = pvtsutils__namespace.Convert.ToUtf16String(inputBuffer); + this.valueBlock.valueHexView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + } + fromString(inputString) { + this.valueBlock.value = inputString; + this.valueBlock.valueHexView = new Uint8Array(pvtsutils__namespace.Convert.FromUtf16String(inputString)); + } +} +LocalBmpStringValueBlock.NAME = "BmpStringValueBlock"; + +var _a$h; +class BmpString extends LocalBmpStringValueBlock { + constructor({ ...parameters } = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 30; + } +} +_a$h = BmpString; +(() => { + typeStore.BmpString = _a$h; +})(); +BmpString.NAME = "BMPString"; + +class LocalUniversalStringValueBlock extends LocalSimpleStringBlock { + fromBuffer(inputBuffer) { + const copyBuffer = ArrayBuffer.isView(inputBuffer) ? inputBuffer.slice().buffer : inputBuffer.slice(0); + const valueView = new Uint8Array(copyBuffer); + for (let i = 0; i < valueView.length; i += 4) { + valueView[i] = valueView[i + 3]; + valueView[i + 1] = valueView[i + 2]; + valueView[i + 2] = 0x00; + valueView[i + 3] = 0x00; + } + this.valueBlock.value = String.fromCharCode.apply(null, new Uint32Array(copyBuffer)); + } + fromString(inputString) { + const strLength = inputString.length; + const valueHexView = this.valueBlock.valueHexView = new Uint8Array(strLength * 4); + for (let i = 0; i < strLength; i++) { + const codeBuf = pvutils__namespace.utilToBase(inputString.charCodeAt(i), 8); + const codeView = new Uint8Array(codeBuf); + if (codeView.length > 4) + continue; + const dif = 4 - codeView.length; + for (let j = (codeView.length - 1); j >= 0; j--) + valueHexView[i * 4 + j + dif] = codeView[j]; + } + this.valueBlock.value = inputString; + } +} +LocalUniversalStringValueBlock.NAME = "UniversalStringValueBlock"; + +var _a$g; +class UniversalString extends LocalUniversalStringValueBlock { + constructor({ ...parameters } = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 28; + } +} +_a$g = UniversalString; +(() => { + typeStore.UniversalString = _a$g; +})(); +UniversalString.NAME = "UniversalString"; + +var _a$f; +class NumericString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 18; + } +} +_a$f = NumericString; +(() => { + typeStore.NumericString = _a$f; +})(); +NumericString.NAME = "NumericString"; + +var _a$e; +class PrintableString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 19; + } +} +_a$e = PrintableString; +(() => { + typeStore.PrintableString = _a$e; +})(); +PrintableString.NAME = "PrintableString"; + +var _a$d; +class TeletexString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 20; + } +} +_a$d = TeletexString; +(() => { + typeStore.TeletexString = _a$d; +})(); +TeletexString.NAME = "TeletexString"; + +var _a$c; +class VideotexString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 21; + } +} +_a$c = VideotexString; +(() => { + typeStore.VideotexString = _a$c; +})(); +VideotexString.NAME = "VideotexString"; + +var _a$b; +class IA5String extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 22; + } +} +_a$b = IA5String; +(() => { + typeStore.IA5String = _a$b; +})(); +IA5String.NAME = "IA5String"; + +var _a$a; +class GraphicString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 25; + } +} +_a$a = GraphicString; +(() => { + typeStore.GraphicString = _a$a; +})(); +GraphicString.NAME = "GraphicString"; + +var _a$9; +class VisibleString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 26; + } +} +_a$9 = VisibleString; +(() => { + typeStore.VisibleString = _a$9; +})(); +VisibleString.NAME = "VisibleString"; + +var _a$8; +class GeneralString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 27; + } +} +_a$8 = GeneralString; +(() => { + typeStore.GeneralString = _a$8; +})(); +GeneralString.NAME = "GeneralString"; + +var _a$7; +class CharacterString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 29; + } +} +_a$7 = CharacterString; +(() => { + typeStore.CharacterString = _a$7; +})(); +CharacterString.NAME = "CharacterString"; + +var _a$6; +class UTCTime extends VisibleString { + constructor({ value, valueDate, ...parameters } = {}) { + super(parameters); + this.year = 0; + this.month = 0; + this.day = 0; + this.hour = 0; + this.minute = 0; + this.second = 0; + if (value) { + this.fromString(value); + this.valueBlock.valueHexView = new Uint8Array(value.length); + for (let i = 0; i < value.length; i++) + this.valueBlock.valueHexView[i] = value.charCodeAt(i); + } + if (valueDate) { + this.fromDate(valueDate); + this.valueBlock.valueHexView = new Uint8Array(this.toBuffer()); + } + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 23; + } + fromBuffer(inputBuffer) { + this.fromString(String.fromCharCode.apply(null, pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer))); + } + toBuffer() { + const str = this.toString(); + const buffer = new ArrayBuffer(str.length); + const view = new Uint8Array(buffer); + for (let i = 0; i < str.length; i++) + view[i] = str.charCodeAt(i); + return buffer; + } + fromDate(inputDate) { + this.year = inputDate.getUTCFullYear(); + this.month = inputDate.getUTCMonth() + 1; + this.day = inputDate.getUTCDate(); + this.hour = inputDate.getUTCHours(); + this.minute = inputDate.getUTCMinutes(); + this.second = inputDate.getUTCSeconds(); + } + toDate() { + return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second))); + } + fromString(inputString) { + const parser = /(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig; + const parserArray = parser.exec(inputString); + if (parserArray === null) { + this.error = "Wrong input string for conversion"; + return; + } + const year = parseInt(parserArray[1], 10); + if (year >= 50) + this.year = 1900 + year; + else + this.year = 2000 + year; + this.month = parseInt(parserArray[2], 10); + this.day = parseInt(parserArray[3], 10); + this.hour = parseInt(parserArray[4], 10); + this.minute = parseInt(parserArray[5], 10); + this.second = parseInt(parserArray[6], 10); + } + toString(encoding = "iso") { + if (encoding === "iso") { + const outputArray = new Array(7); + outputArray[0] = pvutils__namespace.padNumber(((this.year < 2000) ? (this.year - 1900) : (this.year - 2000)), 2); + outputArray[1] = pvutils__namespace.padNumber(this.month, 2); + outputArray[2] = pvutils__namespace.padNumber(this.day, 2); + outputArray[3] = pvutils__namespace.padNumber(this.hour, 2); + outputArray[4] = pvutils__namespace.padNumber(this.minute, 2); + outputArray[5] = pvutils__namespace.padNumber(this.second, 2); + outputArray[6] = "Z"; + return outputArray.join(""); + } + return super.toString(encoding); + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.toDate().toISOString()}`; + } + toJSON() { + return { + ...super.toJSON(), + year: this.year, + month: this.month, + day: this.day, + hour: this.hour, + minute: this.minute, + second: this.second, + }; + } +} +_a$6 = UTCTime; +(() => { + typeStore.UTCTime = _a$6; +})(); +UTCTime.NAME = "UTCTime"; + +var _a$5; +class GeneralizedTime extends UTCTime { + constructor(parameters = {}) { + var _b; + super(parameters); + (_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 24; + } + fromDate(inputDate) { + super.fromDate(inputDate); + this.millisecond = inputDate.getUTCMilliseconds(); + } + toDate() { + const utcDate = Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond); + return (new Date(utcDate)); + } + fromString(inputString) { + let isUTC = false; + let timeString = ""; + let dateTimeString = ""; + let fractionPart = 0; + let parser; + let hourDifference = 0; + let minuteDifference = 0; + if (inputString[inputString.length - 1] === "Z") { + timeString = inputString.substring(0, inputString.length - 1); + isUTC = true; + } + else { + const number = new Number(inputString[inputString.length - 1]); + if (isNaN(number.valueOf())) + throw new Error("Wrong input string for conversion"); + timeString = inputString; + } + if (isUTC) { + if (timeString.indexOf("+") !== -1) + throw new Error("Wrong input string for conversion"); + if (timeString.indexOf("-") !== -1) + throw new Error("Wrong input string for conversion"); + } + else { + let multiplier = 1; + let differencePosition = timeString.indexOf("+"); + let differenceString = ""; + if (differencePosition === -1) { + differencePosition = timeString.indexOf("-"); + multiplier = -1; + } + if (differencePosition !== -1) { + differenceString = timeString.substring(differencePosition + 1); + timeString = timeString.substring(0, differencePosition); + if ((differenceString.length !== 2) && (differenceString.length !== 4)) + throw new Error("Wrong input string for conversion"); + let number = parseInt(differenceString.substring(0, 2), 10); + if (isNaN(number.valueOf())) + throw new Error("Wrong input string for conversion"); + hourDifference = multiplier * number; + if (differenceString.length === 4) { + number = parseInt(differenceString.substring(2, 4), 10); + if (isNaN(number.valueOf())) + throw new Error("Wrong input string for conversion"); + minuteDifference = multiplier * number; + } + } + } + let fractionPointPosition = timeString.indexOf("."); + if (fractionPointPosition === -1) + fractionPointPosition = timeString.indexOf(","); + if (fractionPointPosition !== -1) { + const fractionPartCheck = new Number(`0${timeString.substring(fractionPointPosition)}`); + if (isNaN(fractionPartCheck.valueOf())) + throw new Error("Wrong input string for conversion"); + fractionPart = fractionPartCheck.valueOf(); + dateTimeString = timeString.substring(0, fractionPointPosition); + } + else + dateTimeString = timeString; + switch (true) { + case (dateTimeString.length === 8): + parser = /(\d{4})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) + throw new Error("Wrong input string for conversion"); + break; + case (dateTimeString.length === 10): + parser = /(\d{4})(\d{2})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) { + let fractionResult = 60 * fractionPart; + this.minute = Math.floor(fractionResult); + fractionResult = 60 * (fractionResult - this.minute); + this.second = Math.floor(fractionResult); + fractionResult = 1000 * (fractionResult - this.second); + this.millisecond = Math.floor(fractionResult); + } + break; + case (dateTimeString.length === 12): + parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) { + let fractionResult = 60 * fractionPart; + this.second = Math.floor(fractionResult); + fractionResult = 1000 * (fractionResult - this.second); + this.millisecond = Math.floor(fractionResult); + } + break; + case (dateTimeString.length === 14): + parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) { + const fractionResult = 1000 * fractionPart; + this.millisecond = Math.floor(fractionResult); + } + break; + default: + throw new Error("Wrong input string for conversion"); + } + const parserArray = parser.exec(dateTimeString); + if (parserArray === null) + throw new Error("Wrong input string for conversion"); + for (let j = 1; j < parserArray.length; j++) { + switch (j) { + case 1: + this.year = parseInt(parserArray[j], 10); + break; + case 2: + this.month = parseInt(parserArray[j], 10); + break; + case 3: + this.day = parseInt(parserArray[j], 10); + break; + case 4: + this.hour = parseInt(parserArray[j], 10) + hourDifference; + break; + case 5: + this.minute = parseInt(parserArray[j], 10) + minuteDifference; + break; + case 6: + this.second = parseInt(parserArray[j], 10); + break; + default: + throw new Error("Wrong input string for conversion"); + } + } + if (isUTC === false) { + const tempDate = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond); + this.year = tempDate.getUTCFullYear(); + this.month = tempDate.getUTCMonth(); + this.day = tempDate.getUTCDay(); + this.hour = tempDate.getUTCHours(); + this.minute = tempDate.getUTCMinutes(); + this.second = tempDate.getUTCSeconds(); + this.millisecond = tempDate.getUTCMilliseconds(); + } + } + toString(encoding = "iso") { + if (encoding === "iso") { + const outputArray = []; + outputArray.push(pvutils__namespace.padNumber(this.year, 4)); + outputArray.push(pvutils__namespace.padNumber(this.month, 2)); + outputArray.push(pvutils__namespace.padNumber(this.day, 2)); + outputArray.push(pvutils__namespace.padNumber(this.hour, 2)); + outputArray.push(pvutils__namespace.padNumber(this.minute, 2)); + outputArray.push(pvutils__namespace.padNumber(this.second, 2)); + if (this.millisecond !== 0) { + outputArray.push("."); + outputArray.push(pvutils__namespace.padNumber(this.millisecond, 3)); + } + outputArray.push("Z"); + return outputArray.join(""); + } + return super.toString(encoding); + } + toJSON() { + return { + ...super.toJSON(), + millisecond: this.millisecond, + }; + } +} +_a$5 = GeneralizedTime; +(() => { + typeStore.GeneralizedTime = _a$5; +})(); +GeneralizedTime.NAME = "GeneralizedTime"; + +var _a$4; +class DATE extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 31; + } +} +_a$4 = DATE; +(() => { + typeStore.DATE = _a$4; +})(); +DATE.NAME = "DATE"; + +var _a$3; +class TimeOfDay extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 32; + } +} +_a$3 = TimeOfDay; +(() => { + typeStore.TimeOfDay = _a$3; +})(); +TimeOfDay.NAME = "TimeOfDay"; + +var _a$2; +class DateTime extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 33; + } +} +_a$2 = DateTime; +(() => { + typeStore.DateTime = _a$2; +})(); +DateTime.NAME = "DateTime"; + +var _a$1; +class Duration extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 34; + } +} +_a$1 = Duration; +(() => { + typeStore.Duration = _a$1; +})(); +Duration.NAME = "Duration"; + +var _a; +class TIME extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 14; + } +} +_a = TIME; +(() => { + typeStore.TIME = _a; +})(); +TIME.NAME = "TIME"; + +class Any { + constructor({ name = EMPTY_STRING, optional = false } = {}) { + this.name = name; + this.optional = optional; + } +} + +class Choice extends Any { + constructor({ value = [], ...parameters } = {}) { + super(parameters); + this.value = value; + } +} + +class Repeated extends Any { + constructor({ value = new Any(), local = false, ...parameters } = {}) { + super(parameters); + this.value = value; + this.local = local; + } +} + +class RawData { + get data() { + return this.dataView.slice().buffer; + } + set data(value) { + this.dataView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(value); + } + constructor({ data = EMPTY_VIEW } = {}) { + this.dataView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(data); + } + fromBER(inputBuffer, inputOffset, inputLength) { + const endLength = inputOffset + inputLength; + this.dataView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer).subarray(inputOffset, endLength); + return endLength; + } + toBER(_sizeOnly) { + return this.dataView.slice().buffer; + } +} + +function compareSchema(root, inputData, inputSchema) { + if (inputSchema instanceof Choice) { + for (const element of inputSchema.value) { + const result = compareSchema(root, inputData, element); + if (result.verified) { + return { + verified: true, + result: root, + }; + } + } + { + const _result = { + verified: false, + result: { error: "Wrong values for Choice type" }, + }; + if (inputSchema.hasOwnProperty(NAME)) + _result.name = inputSchema.name; + return _result; + } + } + if (inputSchema instanceof Any) { + if (inputSchema.hasOwnProperty(NAME)) + root[inputSchema.name] = inputData; + return { + verified: true, + result: root, + }; + } + if ((root instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong root object" }, + }; + } + if ((inputData instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 data" }, + }; + } + if ((inputSchema instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if ((ID_BLOCK in inputSchema) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if ((FROM_BER in inputSchema.idBlock) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if ((TO_BER in inputSchema.idBlock) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + const encodedId = inputSchema.idBlock.toBER(false); + if (encodedId.byteLength === 0) { + return { + verified: false, + result: { error: "Error encoding idBlock for ASN.1 schema" }, + }; + } + const decodedOffset = inputSchema.idBlock.fromBER(encodedId, 0, encodedId.byteLength); + if (decodedOffset === -1) { + return { + verified: false, + result: { error: "Error decoding idBlock for ASN.1 schema" }, + }; + } + if (inputSchema.idBlock.hasOwnProperty(TAG_CLASS) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if (inputSchema.idBlock.tagClass !== inputData.idBlock.tagClass) { + return { + verified: false, + result: root, + }; + } + if (inputSchema.idBlock.hasOwnProperty(TAG_NUMBER) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if (inputSchema.idBlock.tagNumber !== inputData.idBlock.tagNumber) { + return { + verified: false, + result: root, + }; + } + if (inputSchema.idBlock.hasOwnProperty(IS_CONSTRUCTED) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if (inputSchema.idBlock.isConstructed !== inputData.idBlock.isConstructed) { + return { + verified: false, + result: root, + }; + } + if (!(IS_HEX_ONLY in inputSchema.idBlock)) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if (inputSchema.idBlock.isHexOnly !== inputData.idBlock.isHexOnly) { + return { + verified: false, + result: root, + }; + } + if (inputSchema.idBlock.isHexOnly) { + if ((VALUE_HEX_VIEW in inputSchema.idBlock) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + const schemaView = inputSchema.idBlock.valueHexView; + const asn1View = inputData.idBlock.valueHexView; + if (schemaView.length !== asn1View.length) { + return { + verified: false, + result: root, + }; + } + for (let i = 0; i < schemaView.length; i++) { + if (schemaView[i] !== asn1View[1]) { + return { + verified: false, + result: root, + }; + } + } + } + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) + root[inputSchema.name] = inputData; + } + if (inputSchema instanceof typeStore.Constructed) { + let admission = 0; + let result = { + verified: false, + result: { error: "Unknown error" }, + }; + let maxLength = inputSchema.valueBlock.value.length; + if (maxLength > 0) { + if (inputSchema.valueBlock.value[0] instanceof Repeated) { + maxLength = inputData.valueBlock.value.length; + } + } + if (maxLength === 0) { + return { + verified: true, + result: root, + }; + } + if ((inputData.valueBlock.value.length === 0) + && (inputSchema.valueBlock.value.length !== 0)) { + let _optional = true; + for (let i = 0; i < inputSchema.valueBlock.value.length; i++) + _optional = _optional && (inputSchema.valueBlock.value[i].optional || false); + if (_optional) { + return { + verified: true, + result: root, + }; + } + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) + delete root[inputSchema.name]; + } + root.error = "Inconsistent object length"; + return { + verified: false, + result: root, + }; + } + for (let i = 0; i < maxLength; i++) { + if ((i - admission) >= inputData.valueBlock.value.length) { + if (inputSchema.valueBlock.value[i].optional === false) { + const _result = { + verified: false, + result: root, + }; + root.error = "Inconsistent length between ASN.1 data and schema"; + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) { + delete root[inputSchema.name]; + _result.name = inputSchema.name; + } + } + return _result; + } + } + else { + if (inputSchema.valueBlock.value[0] instanceof Repeated) { + result = compareSchema(root, inputData.valueBlock.value[i], inputSchema.valueBlock.value[0].value); + if (result.verified === false) { + if (inputSchema.valueBlock.value[0].optional) + admission++; + else { + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) + delete root[inputSchema.name]; + } + return result; + } + } + if ((NAME in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].name.length > 0)) { + let arrayRoot = {}; + if ((LOCAL in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].local)) + arrayRoot = inputData; + else + arrayRoot = root; + if (typeof arrayRoot[inputSchema.valueBlock.value[0].name] === "undefined") + arrayRoot[inputSchema.valueBlock.value[0].name] = []; + arrayRoot[inputSchema.valueBlock.value[0].name].push(inputData.valueBlock.value[i]); + } + } + else { + result = compareSchema(root, inputData.valueBlock.value[i - admission], inputSchema.valueBlock.value[i]); + if (result.verified === false) { + if (inputSchema.valueBlock.value[i].optional) + admission++; + else { + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) + delete root[inputSchema.name]; + } + return result; + } + } + } + } + } + if (result.verified === false) { + const _result = { + verified: false, + result: root, + }; + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) { + delete root[inputSchema.name]; + _result.name = inputSchema.name; + } + } + return _result; + } + return { + verified: true, + result: root, + }; + } + if (inputSchema.primitiveSchema + && (VALUE_HEX_VIEW in inputData.valueBlock)) { + const asn1 = localFromBER(inputData.valueBlock.valueHexView); + if (asn1.offset === -1) { + const _result = { + verified: false, + result: asn1.result, + }; + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) { + delete root[inputSchema.name]; + _result.name = inputSchema.name; + } + } + return _result; + } + return compareSchema(root, asn1.result, inputSchema.primitiveSchema); + } + return { + verified: true, + result: root, + }; +} +function verifySchema(inputBuffer, inputSchema) { + if ((inputSchema instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema type" }, + }; + } + const asn1 = localFromBER(pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer)); + if (asn1.offset === -1) { + return { + verified: false, + result: asn1.result, + }; + } + return compareSchema(asn1.result, asn1.result, inputSchema); +} + +exports.Any = Any; +exports.BaseBlock = BaseBlock; +exports.BaseStringBlock = BaseStringBlock; +exports.BitString = BitString; +exports.BmpString = BmpString; +exports.Boolean = Boolean; +exports.CharacterString = CharacterString; +exports.Choice = Choice; +exports.Constructed = Constructed; +exports.DATE = DATE; +exports.DEFAULT_MAX_CONTENT_LENGTH = DEFAULT_MAX_CONTENT_LENGTH; +exports.DEFAULT_MAX_DEPTH = DEFAULT_MAX_DEPTH; +exports.DEFAULT_MAX_NODES = DEFAULT_MAX_NODES; +exports.DateTime = DateTime; +exports.Duration = Duration; +exports.EndOfContent = EndOfContent; +exports.Enumerated = Enumerated; +exports.GeneralString = GeneralString; +exports.GeneralizedTime = GeneralizedTime; +exports.GraphicString = GraphicString; +exports.HexBlock = HexBlock; +exports.IA5String = IA5String; +exports.Integer = Integer; +exports.Null = Null; +exports.NumericString = NumericString; +exports.ObjectIdentifier = ObjectIdentifier; +exports.OctetString = OctetString; +exports.Primitive = Primitive; +exports.PrintableString = PrintableString; +exports.RawData = RawData; +exports.RelativeObjectIdentifier = RelativeObjectIdentifier; +exports.Repeated = Repeated; +exports.Sequence = Sequence; +exports.Set = Set; +exports.TIME = TIME; +exports.TeletexString = TeletexString; +exports.TimeOfDay = TimeOfDay; +exports.UTCTime = UTCTime; +exports.UniversalString = UniversalString; +exports.Utf8String = Utf8String; +exports.ValueBlock = ValueBlock; +exports.VideotexString = VideotexString; +exports.ViewWriter = ViewWriter; +exports.VisibleString = VisibleString; +exports.compareSchema = compareSchema; +exports.fromBER = fromBER; +exports.verifySchema = verifySchema; diff --git a/node_modules/asn1js/package.json b/node_modules/asn1js/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c05b96b064b9620cb368d00b6ac344f8637a3ad0 --- /dev/null +++ b/node_modules/asn1js/package.json @@ -0,0 +1,86 @@ +{ + "author": { + "email": "yury@strozhevsky.com", + "name": "Yury Strozhevsky" + }, + "contributors": [ + { + "email": "rmh@unmitigatedrisk.com", + "name": "Ryan Hurst" + } + ], + "engines": { + "node": ">=12.0.0" + }, + "devDependencies": { + "@peculiar/eslint-config-base": "^0.2.9", + "@types/jest": "^30.0.0", + "@types/node": "^25.6.0", + "asn1-test-suite": "^1.0.2", + "eslint": "^10.2.1", + "jest": "^30.3.0", + "rollup": "^4.60.2", + "rollup-plugin-dts": "^6.4.1", + "rollup-plugin-typescript2": "^0.37.0", + "ts-jest": "^29.4.9", + "typescript": "^5.6.3", + "typescript-eslint": "^8.58.2" + }, + "repository": { + "type": "git", + "url": "https://github.com/PeculiarVentures/ASN1.js" + }, + "dependencies": { + "pvtsutils": "^1.3.6", + "pvutils": "^1.1.5", + "tslib": "^2.8.1" + }, + "description": "asn1js is a pure JavaScript library implementing this standard. ASN.1 is the basis of all X.509 related data structures and numerous other protocols used on the web", + "keywords": [ + "asn1", + "parser", + "asn.1", + "ber", + "der", + "sequence", + "set", + "bitstring", + "octetstring", + "utctime", + "utf8string", + "bmpstring", + "universalstring", + "generalizedtime" + ], + "main": "build/index.js", + "module": "build/index.es.js", + "types": "build/index.d.ts", + "name": "asn1js", + "files": [ + "build", + "LICENSE", + "README.md" + ], + "scripts": { + "build": "rollup -c", + "test": "jest", + "prepublishOnly": "npm run build", + "lint": "eslint . --ext .ts", + "lint:fix": "eslint --fix . --ext .ts", + "coverage": "jest --coverage" + }, + "version": "3.0.10", + "license": "BSD-3-Clause", + "devEngines": { + "runtime": { + "name": "node", + "version": ">=24.5.0", + "onFail": "warn" + }, + "packageManager": { + "name": "npm", + "version": "11.7.0", + "onFail": "warn" + } + } +} diff --git a/node_modules/assertion-error/LICENSE b/node_modules/assertion-error/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5e9f3ac637bf65413e58f692249f6138c4ad0172 --- /dev/null +++ b/node_modules/assertion-error/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Jake Luer jake@qualiancy.com (http://qualiancy.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/assertion-error/README.md b/node_modules/assertion-error/README.md new file mode 100644 index 0000000000000000000000000000000000000000..37c392879ab0340727c15ac2860cf965a4aa0362 --- /dev/null +++ b/node_modules/assertion-error/README.md @@ -0,0 +1,68 @@ +

+ AssertionError and AssertionResult classes. +

+ +

+ + build:? + + downloads:? + + devDependencies:none + +

+ +## What is AssertionError? + +Assertion Error is a module that contains two classes: `AssertionError`, which +is an instance of an `Error`, and `AssertionResult` which is not an instance of +Error. + +These can be useful for returning from a function - if the function "succeeds" +return an `AssertionResult` and if the function fails return (or throw) an +`AssertionError`. + +Both `AssertionError` and `AssertionResult` implement the `Result` interface: + +```typescript +interface Result { + name: "AssertionError" | "AssertionResult"; + ok: boolean; + toJSON(...args: unknown[]): Record; +} +``` + +So if a function returns `AssertionResult | AssertionError` it is easy to check +_which_ one is returned by checking either `.name` or `.ok`, or check +`instanceof Error`. + +## Installation + +### Node.js + +`assertion-error` is available on [npm](http://npmjs.org). + +``` +$ npm install --save assertion-error +``` + +### Deno + +`assertion_error` is available on +[Deno.land](https://deno.land/x/assertion_error) + +```typescript +import { + AssertionError, + AssertionResult, +} from "https://deno.land/x/assertion_error@2.0.0/mod.ts"; +``` diff --git a/node_modules/assertion-error/index.d.ts b/node_modules/assertion-error/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d8fda2c783699a14b450070815b4ae070417c8e4 --- /dev/null +++ b/node_modules/assertion-error/index.d.ts @@ -0,0 +1,27 @@ +interface Result { + name: "AssertionError" | "AssertionResult"; + ok: boolean; + toJSON(...args: unknown[]): Record; +} + +declare class AssertionError extends Error implements Result { + [key: string]: unknown + name: "AssertionError"; + ok: false; + message: string; + // deno-lint-ignore ban-types + constructor(message: string, props?: T, ssf?: Function); + stack: string; + toJSON(stack?: boolean): Record; +} + +declare class AssertionResult implements Result { + [key: string]: unknown + name: "AssertionResult"; + ok: true; + message: string; + constructor(props?: T); + toJSON(): Record; +} + +export { AssertionError, AssertionResult, Result }; diff --git a/node_modules/assertion-error/index.js b/node_modules/assertion-error/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2bfcb81ed4731d59533729c5e3d1bd5c33e89e2c --- /dev/null +++ b/node_modules/assertion-error/index.js @@ -0,0 +1,60 @@ +// deno-fmt-ignore-file +// deno-lint-ignore-file +// This code was bundled using `deno bundle` and it's not recommended to edit it manually + +const canElideFrames = "captureStackTrace" in Error; +class AssertionError extends Error { + message; + get name() { + return "AssertionError"; + } + get ok() { + return false; + } + constructor(message = "Unspecified AssertionError", props, ssf){ + super(message); + this.message = message; + if (canElideFrames) { + Error.captureStackTrace(this, ssf || AssertionError); + } + for(const key in props){ + if (!(key in this)) { + this[key] = props[key]; + } + } + } + toJSON(stack) { + return { + ...this, + name: this.name, + message: this.message, + ok: false, + stack: stack !== false ? this.stack : undefined + }; + } +} +class AssertionResult { + get name() { + return "AssertionResult"; + } + get ok() { + return true; + } + constructor(props){ + for(const key in props){ + if (!(key in this)) { + this[key] = props[key]; + } + } + } + toJSON() { + return { + ...this, + name: this.name, + ok: this.ok + }; + } +} +export { AssertionError as AssertionError }; +export { AssertionResult as AssertionResult }; + diff --git a/node_modules/assertion-error/package.json b/node_modules/assertion-error/package.json new file mode 100644 index 0000000000000000000000000000000000000000..02dc0f5b6bb4d0a6c5d6e6419c138d45dbe33dfb --- /dev/null +++ b/node_modules/assertion-error/package.json @@ -0,0 +1,32 @@ +{ + "name": "assertion-error", + "version": "2.0.1", + "description": "Error constructor for test and validation frameworks that implements standardized AssertionError specification.", + "author": "Jake Luer (http://qualiancy.com)", + "license": "MIT", + "types": "./index.d.ts", + "keywords": [ + "test", + "assertion", + "assertion-error" + ], + "repository": { + "type": "git", + "url": "git@github.com:chaijs/assertion-error.git" + }, + "engines": { + "node": ">=12" + }, + "files": [ + "index.d.ts" + ], + "type": "module", + "module": "index.js", + "main": "index.js", + "scripts": { + "build": "deno bundle mod.ts > index.js", + "pretest": "rm -rf coverage/", + "test": "deno test --coverage=coverage", + "posttest": "deno coverage coverage --lcov > coverage/lcov.info && lcov --summary coverage/lcov.info" + } +} diff --git a/node_modules/ast-kit/LICENSE b/node_modules/ast-kit/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e2f33e394e47a75c3823acba787de8dafe700806 --- /dev/null +++ b/node_modules/ast-kit/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright © 2023-PRESENT Kevin Deng (https://github.com/sxzz) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/ast-kit/README.md b/node_modules/ast-kit/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1f13b045d46656d2f140b45fdee71786aad568fc --- /dev/null +++ b/node_modules/ast-kit/README.md @@ -0,0 +1,55 @@ +# ast-kit + +[![npm version][npm-version-src]][npm-version-href] +[![npm downloads][npm-downloads-src]][npm-downloads-href] +[![JSR][jsr-src]][jsr-href] +[![Unit Test][unit-test-src]][unit-test-href] +[![codecov][codecov-src]][codecov-href] + +A toolkit for easy Babel AST generation and manipulation. + +[📖 API Reference](https://jsr.io/@sxzz/ast-kit/doc) + +## Features + +- **😇 Easy to Use**: Parse and resolve Babel AST with a straightforward API. +- **🦾 Type-Friendly**: Built in TypeScript with complete type definitions. +- **💯 Coverage**: 100% test coverage. +- **🪶 Lightweight**: Tree-shakable with only two dependencies. + +## Install + +```bash +npm i ast-kit +``` + +Requires Node.js 20.19.0 or higher. + +## AST Explorer + +You can explore your code's AST using the [AST Explorer](https://ast-explorer.dev/). + +## Sponsors + +

+ + + +

+ +## License + +[MIT](./LICENSE) License © 2023-PRESENT [Kevin Deng](https://github.com/sxzz) + + + +[npm-version-src]: https://img.shields.io/npm/v/ast-kit.svg +[npm-version-href]: https://npmjs.com/package/ast-kit +[npm-downloads-src]: https://img.shields.io/npm/dm/ast-kit +[npm-downloads-href]: https://www.npmcharts.com/compare/ast-kit?interval=30 +[jsr-src]: https://jsr.io/badges/@sxzz/ast-kit +[jsr-href]: https://jsr.io/@sxzz/ast-kit +[unit-test-src]: https://github.com/sxzz/ast-kit/actions/workflows/unit-test.yml/badge.svg +[unit-test-href]: https://github.com/sxzz/ast-kit/actions/workflows/unit-test.yml +[codecov-src]: https://codecov.io/gh/sxzz/ast-kit/graph/badge.svg?token=MHTCPNMZAK +[codecov-href]: https://codecov.io/gh/sxzz/ast-kit diff --git a/node_modules/ast-kit/package.json b/node_modules/ast-kit/package.json new file mode 100644 index 0000000000000000000000000000000000000000..68e2d8b0f6a0c54ae98bd076e407879e69de6443 --- /dev/null +++ b/node_modules/ast-kit/package.json @@ -0,0 +1,64 @@ +{ + "name": "ast-kit", + "type": "module", + "version": "3.0.0-beta.1", + "description": "A toolkit for easy Babel AST generation and manipulation.", + "author": "Kevin Deng ", + "license": "MIT", + "funding": "https://github.com/sponsors/sxzz", + "homepage": "https://github.com/sxzz/ast-kit#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/sxzz/ast-kit.git" + }, + "bugs": { + "url": "https://github.com/sxzz/ast-kit/issues" + }, + "exports": { + ".": "./dist/index.js", + "./package.json": "./package.json" + }, + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "publishConfig": { + "access": "public" + }, + "engines": { + "node": ">=20.19.0" + }, + "dependencies": { + "@babel/parser": "^8.0.0-beta.4", + "estree-walker": "^3.0.3", + "pathe": "^2.0.3" + }, + "devDependencies": { + "@babel/types": "^8.0.0-beta.4", + "@sxzz/eslint-config": "^7.5.0", + "@sxzz/prettier-config": "^2.2.6", + "@types/node": "^25.0.9", + "@typescript/native-preview": "7.0.0-dev.20260119.1", + "@vitest/coverage-v8": "^4.0.17", + "@vitest/ui": "^4.0.17", + "bumpp": "^10.4.0", + "eslint": "^9.39.2", + "prettier": "^3.8.0", + "tsdown": "^0.20.0-beta.3", + "tsdown-preset-sxzz": "^0.3.0", + "typescript": "5.9.3", + "vitest": "^4.0.17" + }, + "resolutions": { + "vite": "^8.0.0-beta.7" + }, + "prettier": "@sxzz/prettier-config", + "scripts": { + "lint": "eslint .", + "lint:fix": "pnpm run lint --fix", + "build": "tsdown", + "test": "vitest", + "release": "bumpp", + "typecheck": "tsgo --noEmit" + } +} \ No newline at end of file diff --git a/node_modules/ast-v8-to-istanbul/LICENSE b/node_modules/ast-v8-to-istanbul/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..073bd2a614d7886bf3a015c29be8817a37ebd675 --- /dev/null +++ b/node_modules/ast-v8-to-istanbul/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Ari Perkkiö + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/ast-v8-to-istanbul/README.md b/node_modules/ast-v8-to-istanbul/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e4aa256e484c25d512226e58de38652b5ecb9068 --- /dev/null +++ b/node_modules/ast-v8-to-istanbul/README.md @@ -0,0 +1,278 @@ +# `ast-v8-to-istanbul` + +[![Version][version-badge]][npm-url] +[![Downloads][downloads-url]][npm-url] + +> - Speed of V8 coverage 🏎 +> - Accuracy of Istanbul coverage 🔍 + +[Ignoring code](#ignoring-code) | [Source maps](#source-maps) | [Istanbul Compatibility](#istanbul-compatibility) | [Limitations](#limitations) + +--- + +AST-aware [`v8-to-istanbul`](https://www.npmjs.com/package/v8-to-istanbul). + +Unopinionated - _bring-your-own_ AST parser and source maps. + +Passes all 195 tests[*](#istanbul-compatibility) of [`istanbul-lib-instrument`](https://github.com/istanbuljs/istanbuljs/tree/main/packages/istanbul-lib-instrument/test/specs). ✅ + +Test cases run against: +- `vite/parseAst` ✅ +- `acorn` ✅ +- `oxc-parser` ✅ +- `@babel/parser` ✅ + +See example report at https://ariperkkio.github.io/ast-v8-to-istanbul. + +```ts +import { convert } from "ast-v8-to-istanbul"; +import { parseAstAsync } from "vite"; +import type { CoverageMapData } from "istanbul-lib-coverage"; + +const data: CoverageMapData = await convert({ + // Bring-your-own AST parser + ast: parseAstAsync(), + + // Code of the executed file (not the source file) + code: "function sum(a, b) {\n return a + b ...", + + // Execution wrapper offset + wrapperLength: 0, + + // Script coverage of the executed file + coverage: { + scriptId: "123", + url: "file:///absolute/path/to/dist/index.js", + functions: [ + { + functionName: "sum", + ranges: [{ startOffset: 223, endOffset: 261, count: 0 }], + isBlockCoverage: false, + }, + // ... etc + ], + }, + + // Source map of the executed file + sourceMap: { + version: 3, + sources: ["../sources.ts"], + sourcesContent: ["export function sum(a: number, b: number) {\n..."], + mappings: ";AAAO,SAAS,...", + names: [], + }, +}); +``` + +## Ignoring code + +### Ignoring source code + +#### Ignore hints + +See live example at https://ariperkkio.github.io/ast-v8-to-istanbul/ignore-examples.html. + +The typical ignore hints from `nyc` are supported: https://github.com/istanbuljs/nyc?tab=readme-ov-file#parsing-hints-ignoring-lines: + +> * `/* istanbul ignore if */`: ignore the next if statement. +> * `/* istanbul ignore else */`: ignore the else portion of an if statement. +> * `/* istanbul ignore next */`: ignore the next _thing_ in the source-code (functions, if statements, classes, you name it). +> * `/* istanbul ignore file */`: ignore an entire source-file (this should be placed at the top of the file). + +In addition to `istanbul` keyword, you can use `v8`, `c8` and `node:coverage`: + +- `/* istanbul ignore if */` +- `/* v8 ignore else */` +- `/* c8 ignore file */` +- `/* node:coverage ignore next */` + +Also `start` and `stop` ignore hints from original [`v8-to-istanbul`](https://www.npmjs.com/package/v8-to-istanbul) are supported. +These ignore hints are checked from the original sources instead of transpiled code. + +> * `/* v8 ignore start */`: start ignoring lines +> * `/* v8 ignore stop */`: stop ignoring lines +> * ``: start ignoring lines +> * ``: stop ignoring lines +> * `anything /* v8 ignore start */ anything`: start ignoring lines +> * `anything /* v8 ignore stop */ anything`: stop ignoring lines + +#### Class methods + +The `ignore-class-method` from `nyc` is also supported: https://github.com/istanbuljs/nyc?tab=readme-ov-file#ignoring-methods + +> You can ignore every instance of a method simply by adding its name to the `ignore-class-method` array in your `nyc` config. + +```ts +import { convert } from "ast-v8-to-istanbul"; + +await convert({ + ignoreClassMethods: ['render'] +}); +``` + +#### Ignore after remapping + +You can ignore source code after coverage results have been remapped back to original sources using `ignoreSourceCode`. +This is a high level API that can be exposed to end-users by tooling developers. + +It's mostly intended for excluding code that is incorrectly shown in coverage report when compilers add generated code in the source maps. + +Note that as the exclusion happens after remapping, this option is slower than [`ignoreNode`](#ignoring-generated-code) option. + +```ts +function ignoreSourceCode( + code: string, + type: "function" | "statement" | "branch", + location: Record<"start" | "end", { line: number; column: number }>, +): boolean | void; +``` + +```ts +import { convert } from "ast-v8-to-istanbul"; + +await convert({ + ignoreSourceCode: (code, type, location) => { + // Ignore all "noop()" calls + if(type === "function" && code.includes("noop(")) { + return true; + } + + // In Vue " +``` + +Using unpkg CDN: + +```html + +``` + +## Example + +```js +import axios from 'axios'; +//const axios = require('axios'); // legacy way + +try { + const response = await axios.get('/user?ID=12345'); + console.log(response); +} catch (error) { + console.error(error); +} + +// Optionally the request above could also be done as +axios + .get('/user', { + params: { + ID: 12345, + }, + timeout: 5000, // 5 seconds. See "Handling Timeouts" below for matching error handling + }) + .then(function (response) { + console.log(response); + }) + .catch(function (error) { + console.log(error); + }) + .finally(function () { + // always executed + }); + +// Want to use async/await? Add the `async` keyword to your outer function/method. +async function getUser() { + try { +// Example: GET request with query parameters +const response = await axios.get('/user', { + params: { + ID: 12345 + } +}); + +// Using the `params` option improves readability and automatically formats query strings + +console.log(response); + } catch (error) { + console.error(error); + } +} +``` + +> Note: Set a `timeout` in production. Without one, a stalled request can hang +> indefinitely. See [Handling Timeouts](#handling-timeouts) for the matching error handling. + +> Note: `async/await` is part of ECMAScript 2017 and is not supported in Internet +> Explorer and older browsers, so use with caution. + +Performing a `POST` request + +```js +const response = await axios.post('/user', { + firstName: 'Fred', + lastName: 'Flintstone', +}); +console.log(response); +``` + +Performing multiple concurrent requests + +```js +function getUserAccount() { + return axios.get('/user/12345'); +} + +function getUserPermissions() { + return axios.get('/user/12345/permissions'); +} + +Promise.all([getUserAccount(), getUserPermissions()]).then(function (results) { + const acct = results[0]; + const perm = results[1]; +}); +``` + +## axios API + +Requests can be made by passing the relevant config to `axios`. + +##### axios(config) + +```js +// Send a POST request +axios({ + method: 'post', + url: '/user/12345', + data: { + firstName: 'Fred', + lastName: 'Flintstone', + }, +}); +``` + +```js +// GET request for remote image in node.js +const response = await axios({ + method: 'get', + url: 'https://bit.ly/2mTM3nY', + responseType: 'stream', +}); +response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')); +``` + +##### axios(url[, config]) + +```js +// Send a GET request (default method) +axios('/user/12345'); +``` + +### Request method aliases + +For convenience, aliases have been provided for all common request methods. + +##### axios.request(config) + +##### axios.get(url[, config]) + +##### axios.delete(url[, config]) + +##### axios.head(url[, config]) + +##### axios.options(url[, config]) + +##### axios.post(url[, data[, config]]) + +##### axios.put(url[, data[, config]]) + +##### axios.patch(url[, data[, config]]) + +###### Note + +When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config. + +### Concurrency (deprecated) + +Use `Promise.all` instead of these helpers. + +Helper functions for dealing with concurrent requests. + +axios.all(iterable) +axios.spread(callback) + +### Creating an instance + +You can create a new instance of axios with a custom config. + +##### axios.create([config]) + +```js +const instance = axios.create({ + baseURL: 'https://some-domain.com/api/', + timeout: 1000, + headers: { 'X-Custom-Header': 'foobar' }, +}); +``` + +### Instance methods + +The following instance methods are available. Axios merges the specified config with the instance config. + +##### axios#request(config) + +##### axios#get(url[, config]) + +##### axios#delete(url[, config]) + +##### axios#head(url[, config]) + +##### axios#options(url[, config]) + +##### axios#post(url[, data[, config]]) + +##### axios#put(url[, data[, config]]) + +##### axios#patch(url[, data[, config]]) + +##### axios#getUri([config]) + +## Request config + +### Security notice: decompression-bomb protection is opt-in + +By default `maxContentLength` and `maxBodyLength` are `-1` (unlimited). A malicious or compromised server can return a tiny gzip/deflate/brotli/zstd body that expands to gigabytes and exhaust the Node.js process. + +If you call servers you do not fully trust, **set a cap**: + +```js +axios.defaults.maxContentLength = 10 * 1024 * 1024; // 10 MB +axios.defaults.maxBodyLength = 10 * 1024 * 1024; +``` + +See the [security guide](https://axios.rest/pages/misc/security.html) for details. + +These config options are available for requests. Only `url` is required. Requests default to `GET` when `method` is not set. + +```js +{ + // `url` is the server URL for the request + url: '/user', + + // `method` is the request method to be used when making the request + method: 'get', // default + + // Axios prepends `baseURL` to `url` unless `url` is absolute and `allowAbsoluteUrls` is set to true. + // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs + // to the methods of that instance. + baseURL: 'https://some-domain.com/api/', + + // `allowAbsoluteUrls` determines whether or not absolute URLs will override a configured `baseUrl`. + // When set to true (default), absolute values for `url` will override `baseUrl`. + // When set to false, absolute values for `url` will always be prepended by `baseUrl`. + allowAbsoluteUrls: true, + + // `transformRequest` allows changes to the request data before it is sent to the server + // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE' + // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, + // FormData or Stream + // You may modify the headers object. + transformRequest: [function (data, headers) { + // Do whatever you want to transform the data + + return data; + }], + + // `transformResponse` allows changes to the response data to be made before + // it is passed to then/catch + transformResponse: [function (data) { + // Do whatever you want to transform the data + + return data; + }], + + // `parseReviver` is an optional function passed as the + // second argument (reviver) to JSON.parse() + parseReviver: function (key, value, context) { + // In modern environments, context.source provides the raw JSON string + // allowing for precision-safe parsing of BigInt + if (typeof value === 'number' && context?.source) { + const isInteger = Number.isInteger(value); + const isUnsafe = !Number.isSafeInteger(value); + const isValidIntegerString = /^-?\d+$/.test(context.source); + + if (isInteger && isUnsafe && isValidIntegerString) { + try { + return BigInt(context.source); + } catch { + // Fallback: return original value if parsing fails + } + } + } + return value; + }, + + // `headers` are custom headers to be sent + headers: {'X-Requested-With': 'XMLHttpRequest'}, + + // `params` are the URL parameters to be sent with the request + // Must be a plain object or a URLSearchParams object + params: { + ID: 12345 + }, + + // `paramsSerializer` is an optional config that allows you to customize serializing `params`. + paramsSerializer: { + + // Custom encoder function which sends key/value pairs in an iterative fashion. + encode?: (param: string): string => { /* Do custom operations here and return transformed string */ }, + + // Custom serializer function for the entire parameter. Allows the user to mimic pre 1.x behaviour. + serialize?: (params: Record, options?: ParamsSerializerOptions ), + + // Configuration for formatting array indexes in the params. + indexes: false, // Three available options: (1) indexes: null (leads to no brackets), (2) (default) indexes: false (leads to empty brackets), (3) indexes: true (leads to brackets with indexes). + + // Maximum object nesting depth when serializing params. Payloads deeper than this throw an + // AxiosError with code ERR_FORM_DATA_DEPTH_EXCEEDED. Default: 100. Set to Infinity to disable. + maxDepth: 100 + + }, + + // `data` is the data to be sent as the request body + // Only applicable for request methods 'PUT', 'POST', 'DELETE', and 'PATCH' + // When no `transformRequest` is set, it must be of one of the following types: + // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams + // - Browser only: FormData, File, Blob + // - React Native: FormData + // - Node only: Stream, Buffer, FormData (form-data package) + data: { + firstName: 'Fred' + }, + + // `formDataHeaderPolicy` controls how node.js FormData#getHeaders() is copied. + // 'legacy' (default) copies all returned headers for v1 compatibility. + // 'content-only' copies only Content-Type and Content-Length. + formDataHeaderPolicy: 'legacy', + + // syntax alternative to send data into the body + // method post + // only the value is sent, not the key + data: 'Country=Brasil&City=Belo Horizonte', + + // `timeout` specifies the number of milliseconds before the request times out. + // If the request takes longer than `timeout`, Axios aborts it. + timeout: 1000, // default is `0` (no timeout) + + // `withCredentials` indicates whether or not cross-site Access-Control requests + // should be made using credentials + // This only controls whether the browser sends credentials. + // It does not control whether the XSRF header is added. + withCredentials: false, // default + + // `adapter` allows custom handling of requests which makes testing easier. + // Return a promise and supply a valid response (see lib/adapters/README.md) + adapter: function (config) { + /* ... */ + }, + // Also, you can set the name of the built-in adapter, or provide an array with their names + // to choose the first available in the environment + adapter: 'xhr', // 'fetch' | 'http' | ['xhr', 'http', 'fetch'] + + // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. + // This will set an `Authorization` header, overwriting any existing + // `Authorization` custom headers you have set using `headers`. + // If `auth` is omitted, the Node.js HTTP and fetch adapters can read + // HTTP Basic auth credentials from the request URL, for example + // `https://user:pass@example.com`. Axios decodes percent-encoded URL + // credentials, and `auth` takes precedence over URL-embedded credentials. + // The Node.js HTTP adapter preserves Basic auth on same-origin redirects + // and strips it on cross-origin redirects. + // Please note that only HTTP Basic auth is configurable through this parameter. + // For Bearer tokens and such, use `Authorization` custom headers instead. + auth: { + username: 'janedoe', + password: 's00pers3cret' + }, + + // `responseType` indicates the type of data that the server will respond with + // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' + // browser only: 'blob' + responseType: 'json', // default + + // `responseEncoding` indicates encoding to use for decoding responses (Node.js only) + // Note: Ignored for `responseType` of 'stream' or client-side requests + // options are: 'ascii', 'ASCII', 'ansi', 'ANSI', 'binary', 'BINARY', 'base64', 'BASE64', 'base64url', + // 'BASE64URL', 'hex', 'HEX', 'latin1', 'LATIN1', 'ucs-2', 'UCS-2', 'ucs2', 'UCS2', 'utf-8', 'UTF-8', + // 'utf8', 'UTF8', 'utf16le', 'UTF16LE' + responseEncoding: 'utf8', // default + + // `xsrfCookieName` is the name of the cookie to use as a value for the xsrf token + xsrfCookieName: 'XSRF-TOKEN', // default + + // `xsrfHeaderName` is the name of the http header that carries the xsrf token value + xsrfHeaderName: 'X-XSRF-TOKEN', // default + + // `withXSRFToken` defines whether to send the XSRF header in browser requests. + // `undefined` (default) - set XSRF header only for the same origin requests + // `true` - always set XSRF header, including for cross-origin requests + // `false` - never set XSRF header + // function - resolve with custom logic; receives the internal config object + withXSRFToken: boolean | undefined | ((config: InternalAxiosRequestConfig) => boolean | undefined), + + // `withXSRFToken` controls whether Axios reads the XSRF cookie and sets the XSRF header. + // - `undefined` (default): the XSRF header is set only for same-origin requests. + // - `true`: attempt to set the XSRF header for all requests (including cross-origin). + // - `false`: never set the XSRF header. + // - function: a callback that receives the request `config` and returns `true`, + // `false`, or `undefined` to decide per-request behavior. + // + // Note about `withCredentials`: `withCredentials` controls whether cross-site + // requests include credentials (cookies and HTTP auth). In older Axios versions, + // setting `withCredentials: true` implicitly caused Axios to set the XSRF header + // for cross-origin requests. Newer Axios separates these concerns: to allow the + // XSRF header to be sent for cross-origin requests you should set both + // `withCredentials: true` and `withXSRFToken: true`. + // + // Example: + // axios.get('/user', { withCredentials: true, withXSRFToken: true }); + + // `onUploadProgress` allows handling of progress events for uploads + // browser & node.js + onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) { + // Do whatever you want with the Axios progress event + }, + + // `onDownloadProgress` allows handling of progress events for downloads + // browser & node.js + onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) { + // Do whatever you want with the Axios progress event + }, + + // `maxContentLength` defines the max size of the response content in bytes. + // It is enforced by the Node.js HTTP adapter and the fetch adapter. + maxContentLength: 2000, + + // `maxBodyLength` defines the max size of the request content in bytes. + // It is enforced by the Node.js HTTP adapter and the fetch adapter when the body length can be determined. + maxBodyLength: 2000, + + // `redact` masks matching config keys when AxiosError#toJSON() is called. + // Matching is case-insensitive and recursive. It does not change the request. + redact: ['authorization', 'password'], + + // `validateStatus` defines whether to resolve or reject the promise for a given + // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` + // or `undefined`), Axios resolves the promise; otherwise, Axios rejects it. + validateStatus: function (status) { + return status >= 200 && status < 300; // default + }, + + // `maxRedirects` defines the maximum number of redirects to follow in node.js. + // If set to 0, Axios follows no redirects. + maxRedirects: 21, // default + + // `sensitiveHeaders` (Node only option) lists custom secret-bearing headers + // to remove from cross-origin redirects. Matching is case-insensitive. + // Same-origin redirects keep these headers. If `maxRedirects` is 0, this + // option is not used. + sensitiveHeaders: ['X-API-Key'], + + // `beforeRedirect` defines a function that Axios calls before redirect. + // Use this to adjust the request options upon redirecting, + // to inspect the latest response headers, + // or to cancel the request by throwing an error + // If maxRedirects is set to 0, `beforeRedirect` is not used. + + beforeRedirect: (options, { headers }) => { + if ( + options.hostname === "example.com" && + options.protocol === "https:" + ) { + options.auth = "user:password"; + } + }, + // Security note: + // The `beforeRedirect` hook runs after sensitive headers are stripped during redirects. + // `follow-redirects` removes credentials on protocol downgrades + // (HTTPS to HTTP). Because `beforeRedirect` runs after that step, + // re-injecting credentials without checking the destination can expose + // sensitive data. Only add credentials for trusted HTTPS destinations. + + // `socketPath` defines a UNIX Socket to be used in node.js. + // e.g. '/var/run/docker.sock' to send requests to the docker daemon. + // Only either `socketPath` or `proxy` can be specified. + // If both are specified, `socketPath` is used. + // + // Security: when `socketPath` is set, hostname/port of the URL are ignored, + // which bypasses hostname-based SSRF protections. Never derive `socketPath` + // from untrusted input. Use `allowedSocketPaths` (below) to restrict accepted + // socket paths for defense-in-depth. + socketPath: null, // default + + // `allowedSocketPaths` restricts which `socketPath` values are accepted. + // Accepts a string or array of strings. Entries and the incoming socketPath + // are compared after path.resolve(). A mismatch throws AxiosError with code + // `ERR_BAD_OPTION_VALUE`. When null/undefined, no restriction is applied. + allowedSocketPaths: null, // default + + // `transport` determines the transport method for the request. + // If defined, Axios uses it. Otherwise, if `maxRedirects` is 0, + // Axios uses the default `http` or `https` library, depending on the protocol specified in `protocol`. + // Otherwise, Axios uses the `httpFollow` or `httpsFollow` library, again depending on the protocol, + // which can handle redirects. + transport: undefined, // default + + // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http + // and https requests, respectively, in node.js. This allows options to be added like + // `keepAlive` that are not enabled by default before Node.js v19.0.0. After Node.js + // v19.0.0, you no longer need to customize the agent to enable `keepAlive` because + // `http.globalAgent` has `keepAlive` enabled by default. + httpAgent: new http.Agent({ keepAlive: true }), + httpsAgent: new https.Agent({ keepAlive: true }), + + // `proxy` defines the hostname, port, and protocol of the proxy server. + // You can also define your proxy using the conventional `http_proxy` and + // `https_proxy` environment variables. If you are using environment variables + // for your proxy configuration, you can also define a `no_proxy` environment + // variable as a comma-separated list of domains that should not be proxied. + // Use `false` to disable proxies, ignoring environment variables. + // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and + // supplies credentials. + // For `http://` targets, axios sends the request to the proxy in + // forward-proxy mode and stamps `Proxy-Authorization` onto the request + // headers (overwriting any user-supplied `Proxy-Authorization` header). + // For `https://` targets, axios establishes a CONNECT tunnel through the + // proxy and performs TLS end-to-end with the origin; `Proxy-Authorization` + // is sent on the CONNECT request only, never on the wrapped TLS request, + // so the proxy never sees the URL, headers, or body. Axios forwards + // `httpsAgent` TLS options such as `ca`, `cert`, `key`, and + // `rejectUnauthorized` to the generated tunneling agent, so they still apply + // to the origin TLS connection. + // If you supply an `HttpsProxyAgent`, axios leaves tunneling to that agent. + // If the proxy server uses HTTPS, then you must set the protocol to `https`. + // A user-supplied `Host` header in `headers` is preserved when forwarding + // through a proxy (case-insensitive match on `host`/`Host`/`HOST`); this + // lets you target a virtual host that differs from the request URL, for + // example, hitting `127.0.0.1:4000` while having the proxy treat the + // request as `example.com`. If no `Host` header is supplied, axios + // defaults it to the request URL's `hostname:port` as before. The Host + // header is only set in forward-proxy mode (HTTP targets); for HTTPS + // tunneling the Host header is sent inside the TLS connection, not seen + // by the proxy. + proxy: { + protocol: 'https', + host: '127.0.0.1', + // hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined + port: 9000, + auth: { + username: 'mikeymike', + password: 'rapunz3l' + } + }, + + // `cancelToken` specifies a cancel token that can be used to cancel the request + // (see Cancellation section below for details) + cancelToken: new CancelToken(function (cancel) { + }), + + // an alternative way to cancel Axios requests using AbortController + signal: new AbortController().signal, + + // `decompress` indicates whether or not the response body should be decompressed + // automatically. If set to `true` will also remove the 'content-encoding' header + // from the responses objects of all decompressed responses + // Axios supports gzip, deflate, brotli, and zstd when the current Node.js + // runtime provides the corresponding zlib decompressor. + // - Node only (XHR cannot turn off decompression) + decompress: true, // default + + // `insecureHTTPParser` boolean. + // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers. + // This may allow interoperability with non-conformant HTTP implementations. + // Using the insecure parser should be avoided. + // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback + // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none + insecureHTTPParser: undefined, // default + + // transitional options for backward compatibility that may be removed in the newer versions + transitional: { + // silent JSON parsing mode + // `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour) + // `false` - throw SyntaxError if JSON parsing failed + // Important: this option only takes effect when `responseType` is explicitly set to 'json'. + // When `responseType` is omitted (defaults to no value), axios uses `forcedJSONParsing` + // to attempt JSON parsing, but will silently return the raw string on failure regardless + // of this setting. To have invalid JSON throw errors, use: + // { responseType: 'json', transitional: { silentJSONParsing: false } } + silentJSONParsing: true, // default value for the current Axios version + + // try to parse the response string as JSON even if `responseType` is not 'json' + forcedJSONParsing: true, + + // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts + clarifyTimeoutError: false, + + // advertise `zstd` in the default Accept-Encoding header when the current + // Node.js runtime supports zstd decompression. Axios still decompresses + // zstd responses when support exists and `decompress` is true. + advertiseZstdAcceptEncoding: false, + + // use the legacy interceptor request/response ordering + legacyInterceptorReqResOrdering: true, // default + }, + + env: { + // The FormData class to be used to automatically serialize the payload into a FormData object + FormData: window?.FormData || global?.FormData + }, + + formSerializer: { + visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values + dots: boolean; // use dots instead of brackets format + metaTokens: boolean; // keep special endings like {} in parameter key + indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes + maxDepth: 100; // maximum object nesting depth; throws AxiosError (ERR_FORM_DATA_DEPTH_EXCEEDED) if exceeded. Set to Infinity to disable. + }, + + // http adapter only (node.js) + maxRate: [ + 100 * 1024, // 100KB/s upload limit, + 100 * 1024 // 100KB/s download limit + ] +} +``` + +### Strict RFC 3986 percent-encoding for query params + +By default, axios decodes `%3A`, `%24`, `%2C` and `%20` back to `:`, `$`, `,` and `+` for readability (the `+` follows the `application/x-www-form-urlencoded` convention for spaces in query strings). These characters are valid in a query component under [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986#section-3.4), so the default output is correct, but some backends require strict percent-encoding and reject the readable form. + +Override the default encoder via `paramsSerializer.encode`: + +```js +// Per-request: emit strict RFC 3986 percent-encoding for query values +axios.get('/foo', { + params: { filter: JSON.stringify({ startedAt: '2026-01-23' }) }, + paramsSerializer: { encode: encodeURIComponent } +}); + +// Or set it on the instance defaults +const client = axios.create({ + paramsSerializer: { encode: encodeURIComponent } +}); +``` + +## HTTP/2 support + +Axios has experimental HTTP/2 support in the Node.js HTTP adapter. + +Support depends on the runtime environment and Node.js version. Redirects and some adapter behavior may differ from HTTP/1.1. + +Options like `httpVersion` and `http2Options` are adapter-specific and may not work the same way in every environment. + +If you need HTTP/2, check runtime support or use a custom adapter. + +## Response schema + +The response to a request contains the following information. + +```js +{ + // `data` is the response that was provided by the server + data: {}, + + // `status` is the HTTP status code from the server response + status: 200, + + // `statusText` is the HTTP status message from the server response + statusText: 'OK', + + // `headers` the HTTP headers that the server responded with + // All header names are lowercase and can be accessed using the bracket notation. + // Example: `response.headers['content-type']` + headers: {}, + + // `config` is the config that was provided to `axios` for the request + config: {}, + + // `request` is the request that generated this response + // It is the last ClientRequest instance in node.js (in redirects) + // and an XMLHttpRequest instance in the browser + request: {} +} +``` + +When using `then`, you receive the response like this: + +```js +const response = await axios.get('/user/12345'); +console.log(response.data); +console.log(response.status); +console.log(response.statusText); +console.log(response.headers); +console.log(response.config); +``` + +When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as the second parameter of `then`, read the response from the `error` object. See [Handling errors](#handling-errors). + +## Config defaults + +Config defaults apply to every request. + +### Global axios defaults + +```js +axios.defaults.baseURL = 'https://api.example.com'; + +// Important: If you use axios with multiple domains, Axios sends AUTH_TOKEN to all of them. +// See below for an example using Custom instance defaults instead. +axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; + +axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; +``` + +### Custom instance defaults + +```js +// Set config defaults when creating the instance +const instance = axios.create({ + baseURL: 'https://api.example.com', +}); + +// Alter defaults after instance has been created +instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; +``` + +### Config order of precedence + +Axios merges config in this order: library defaults from [lib/defaults/index.js](https://github.com/axios/axios/blob/main/lib/defaults/index.js#L49), the instance `defaults` property, and the request `config` argument. Later values take precedence over earlier ones. + +```js +// Create an instance using the config defaults provided by the library +// At this point the timeout config value is `0` as is the default for the library +const instance = axios.create(); + +// Override timeout default for the library +// Now all requests using this instance will wait 2.5 seconds before timing out +instance.defaults.timeout = 2500; + +// Override timeout for this request as it's known to take a long time +instance.get('/longRequest', { + timeout: 5000, +}); +``` + +## Interceptors + +You can intercept requests or responses before methods like `.get()` or `.post()` +resolve their promises (before code inside `then` or `catch`, or after `await`) + +```js +const instance = axios.create(); + +// Add a request interceptor +instance.interceptors.request.use( + function (config) { + // Do something before the request is sent + return config; + }, + function (error) { + // Do something with the request error + return Promise.reject(error); + } +); + +// Add a response interceptor +instance.interceptors.response.use( + function (response) { + // Any status code that lies within the range of 2xx causes this function to trigger + // Do something with response data + return response; + }, + function (error) { + // Any status codes that fall outside the range of 2xx cause this function to trigger + // Do something with response error + return Promise.reject(error); + } +); +``` + +If you need to remove an interceptor later you can. + +```js +const instance = axios.create(); +const myInterceptor = instance.interceptors.request.use(function () { + /*...*/ +}); +instance.interceptors.request.eject(myInterceptor); +``` + +You can also clear all interceptors for requests or responses. + +```js +const instance = axios.create(); +instance.interceptors.request.use(function () { + /*...*/ +}); +instance.interceptors.request.clear(); // Removes interceptors from requests +instance.interceptors.response.use(function () { + /*...*/ +}); +instance.interceptors.response.clear(); // Removes interceptors from responses +``` + +You can add interceptors to a custom instance of axios. + +```js +const instance = axios.create(); +instance.interceptors.request.use(function () { + /*...*/ +}); +``` + +When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay +in the execution of your axios request when the main thread is blocked (a promise is created under the hood for +the interceptor and your request gets put at the bottom of the call stack). If your request interceptors are synchronous you can add a flag +to the options object that will tell axios to run the code synchronously and avoid any delays in request execution. + +```js +axios.interceptors.request.use( + function (config) { + config.headers.test = 'I am only a header!'; + return config; + }, + null, + { synchronous: true } +); +``` + +If you want to execute a particular interceptor based on a runtime check, +you can add a `runWhen` function to the options object. The request interceptor will not run **if and only if** the return +of `runWhen` is `false`. Axios calls the function with the config +object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an +asynchronous request interceptor that only needs to run at certain times. + +```js +function onGetCall(config) { + return config.method === 'get'; +} +axios.interceptors.request.use( + function (config) { + config.headers.test = 'special get headers'; + return config; + }, + null, + { runWhen: onGetCall } +); +``` + +> Note: The options parameter (with `synchronous` and `runWhen` properties) is only supported for request interceptors at the moment. + +### Interceptor execution order + +Request and response interceptors use different execution orders. + +Request interceptors run in reverse order (LIFO: last in, first out). The last interceptor added runs first. + +Response interceptors run in the order they were added (FIFO: first in, first out). The first interceptor added runs first. + +Example: + +```js +const instance = axios.create(); + +const interceptor = (id) => (base) => { + console.log(id); + return base; +}; + +instance.interceptors.request.use(interceptor('Request Interceptor 1')); +instance.interceptors.request.use(interceptor('Request Interceptor 2')); +instance.interceptors.request.use(interceptor('Request Interceptor 3')); +instance.interceptors.response.use(interceptor('Response Interceptor 1')); +instance.interceptors.response.use(interceptor('Response Interceptor 2')); +instance.interceptors.response.use(interceptor('Response Interceptor 3')); + +// Console output: +// Request Interceptor 3 +// Request Interceptor 2 +// Request Interceptor 1 +// [HTTP request is made] +// Response Interceptor 1 +// Response Interceptor 2 +// Response Interceptor 3 +``` + +### Multiple interceptors + +When a response is fulfilled and multiple response interceptors are registered: + +- Each interceptor runs in registration order. +- Each interceptor receives the result from the previous interceptor. +- The chain returns the result from the last interceptor. +- If a fulfillment interceptor throws, Axios skips the next fulfillment interceptor and calls the next rejection interceptor. +- After the error is caught, later fulfillment interceptors run again, just like in a promise chain. + +Read [the interceptor tests](./test/specs/interceptors.spec.js) to see all this in code. + +## Error types + +Axios error messages include details that can help you debug the request. + +Axios errors use this structure: +| Property | Definition | +| -------- | ---------- | +| message | A quick summary of the error message and the status it failed with. | +| name | This defines where the error originated from. For axios, it will always be an 'AxiosError'. | +| stack | Stack trace for the error. | +| config | An axios config object with specific instance configurations defined by the user from when the request was made | +| code | Axios error code. The table below lists internal Axios error codes. | +| status | HTTP response status code. See [here](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) for common HTTP response status code meanings. + +These are the internal Axios error codes: + +| Code | Definition | +| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| ERR_BAD_OPTION_VALUE | Invalid value provided in axios configuration. | +| ERR_BAD_OPTION | Invalid option provided in axios configuration. | +| ERR_NOT_SUPPORT | Feature or method not supported in the current axios environment. | +| ERR_DEPRECATED | Deprecated feature or method used in axios. | +| ERR_INVALID_URL | Invalid URL provided for axios request. | +| ECONNABORTED | Typically indicates that the request has been timed out (unless `transitional.clarifyTimeoutError` is set) or aborted by the browser or its plugin. | +| ERR_CANCELED | The user explicitly canceled the request with an AbortSignal or CancelToken. | +| ETIMEDOUT | Request timed out after exceeding the configured Axios timeout. Set `transitional.clarifyTimeoutError` to `true`; otherwise Axios throws a generic `ECONNABORTED` error. | +| ERR_NETWORK | Network-related issue. In the browser, this error can also be caused by a [CORS](https://developer.mozilla.org/ru/docs/Web/HTTP/Guides/CORS) or [Mixed Content](https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content) policy violation. The browser does not allow the JS code to clarify the real reason for the error caused by security issues, so please check the console. | +| ERR_FR_TOO_MANY_REDIRECTS | Request exceeded the configured maximum number of redirects. | +| ERR_BAD_RESPONSE | Response cannot be parsed properly or is in an unexpected format. Usually related to a response with `5xx` status code. | +| ERR_BAD_REQUEST | The request has an unexpected format or is missing required parameters. Usually related to a response with `4xx` status code. | + +## Handling errors + +By default, Axios rejects responses with status codes outside the 2xx range. + +```js +axios.get('/user/12345').catch(function (error) { + if (error.response) { + // The request was made and the server responded with a status code + // that falls out of the range of 2xx + console.log(error.response.data); + console.log(error.response.status); + console.log(error.response.headers); + } else if (error.request) { + // The request was made but no response was received + // `error.request` is an instance of XMLHttpRequest in the browser and an instance of + // http.ClientRequest in node.js + console.log(error.request); + } else { + // Something happened in setting up the request that triggered an Error + console.log('Error', error.message); + } + console.log(error.config); +}); +``` + +Use `validateStatus` to override the default condition (`status >= 200 && status < 300`) and choose which HTTP status codes should reject. + +```js +axios.get('/user/12345', { + validateStatus: function (status) { + return status < 500; // Resolve only if the status code is less than 500 + }, +}); +``` + +Use `toJSON` to get more information about the HTTP error. + +```js +axios.get('/user/12345').catch(function (error) { + console.log(error.toJSON()); +}); +``` + +To avoid logging secrets from `error.config`, pass a `redact` array in the request config. Matching config keys are masked case-insensitively at any depth when `AxiosError#toJSON()` is called. + +```js +axios.get('/user/12345', { + headers: { Authorization: 'Bearer token' }, + redact: ['authorization'] +}).catch(function (error) { + console.log(error.toJSON().config.headers.Authorization); // [REDACTED ****] +}); +``` + +## Handling timeouts + +```js +async function fetchWithTimeout() { + try { + const response = await axios.get('https://example.com/data', { + timeout: 5000, // 5 seconds + transitional: { + // set to true if you prefer ETIMEDOUT over ECONNABORTED + clarifyTimeoutError: false, + }, + }); + + console.log('Response:', response.data); + } catch (error) { + if (axios.isAxiosError(error)) { + if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') { + console.error('Request timed out. Please try again.'); + return; + } + + console.error('Axios error:', error.message); + return; + } + + console.error('Unexpected error:', error); + } +} +``` + +## Cancellation + +### AbortController + +Since `v0.22.0`, Axios supports AbortController: + +```js +const controller = new AbortController(); + +axios + .get('/foo/bar', { + signal: controller.signal, + }) + .then(function (response) { + //... + }); +// cancel the request +controller.abort(); +``` + +### CancelToken (deprecated) + +You can also cancel a request using a _CancelToken_. + +> The axios cancel token API is based on the withdrawn [cancellable promises proposal](https://github.com/tc39/proposal-cancelable-promises). + +> This API is deprecated since v0.22.0 and should not be used in new projects. + +Create a cancel token with the `CancelToken.source` factory: + +```js +const CancelToken = axios.CancelToken; +const source = CancelToken.source(); + +axios + .get('/user/12345', { + cancelToken: source.token, + }) + .catch(function (thrown) { + if (axios.isCancel(thrown)) { + console.log('Request canceled', thrown.message); + } else { + // handle error + } + }); + +axios.post( + '/user/12345', + { + name: 'new name', + }, + { + cancelToken: source.token, + } +); + +// cancel the request (the message parameter is optional) +source.cancel('Operation canceled by the user.'); +``` + +You can also pass an executor function to the `CancelToken` constructor: + +```js +const CancelToken = axios.CancelToken; +let cancel; + +axios.get('/user/12345', { + cancelToken: new CancelToken(function executor(c) { + // An executor function receives a cancel function as a parameter + cancel = c; + }), +}); + +// cancel the request +cancel(); +``` + +> Note: You can cancel several requests with the same cancel token or abort controller. +> If a cancellation token is already cancelled when an Axios request starts, Axios cancels the request immediately without making a real request. + +> During the transition period, you can use both cancellation APIs, even for the same request: + +## Using `application/x-www-form-urlencoded` format + +### URLSearchParams + +By default, axios serializes JavaScript objects to `JSON`. To send data as [`application/x-www-form-urlencoded`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST), use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API. It works in most browsers and in [Node](https://nodejs.org/api/url.html#url_class_urlsearchparams) v10 and later. + +```js +const params = new URLSearchParams({ foo: 'bar' }); +params.append('extraparam', 'value'); +axios.post('/foo', params); +``` + +### Query string (older browsers) + +For very old browsers, use a [polyfill](https://github.com/WebReflection/url-search-params) and make sure it patches the global environment. + +Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library: + +```js +const qs = require('qs'); +axios.post('/foo', qs.stringify({ bar: 123 })); +``` + +With ES modules: + +```js +import qs from 'qs'; +const data = { bar: 123 }; +const options = { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + data: qs.stringify(data), + url, +}; +axios(options); +``` + +### Older Node.js versions + +For older Node.js engines, use the [`querystring`](https://nodejs.org/api/querystring.html) module: + +```js +const querystring = require('querystring'); +axios.post('https://something.com/', querystring.stringify({ foo: 'bar' })); +``` + +You can also use the [`qs`](https://github.com/ljharb/qs) library. + +> Note: The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has [known issues](https://github.com/nodejs/node-v0.x-archive/issues/1665) with that use case. + +### Automatic serialization to URLSearchParams + +Axios automatically serializes the data object to urlencoded format if the content-type header is set to "application/x-www-form-urlencoded". + +```js +const data = { + x: 1, + arr: [1, 2, 3], + arr2: [1, [2], 3], + users: [ + { name: 'Peter', surname: 'Griffin' }, + { name: 'Thomas', surname: 'Anderson' }, + ], +}; + +await axios.postForm('https://postman-echo.com/post', data, { + headers: { 'content-type': 'application/x-www-form-urlencoded' }, +}); +``` + +The server receives these fields: + +```js + { + x: '1', + 'arr[]': [ '1', '2', '3' ], + 'arr2[0]': '1', + 'arr2[1][0]': '2', + 'arr2[2]': '3', + 'arr3[]': [ '1', '2', '3' ], + 'users[0][name]': 'Peter', + 'users[0][surname]': 'griffin', + 'users[1][name]': 'Thomas', + 'users[1][surname]': 'Anderson' + } +``` + +If your backend body parser, such as `body-parser` for `express.js`, supports nested object decoding, the server receives the same object structure: + +```js +const app = express(); + +app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies + +app.post('/', function (req, res, next) { + // echo body as JSON + res.send(JSON.stringify(req.body)); +}); + +server = app.listen(3000); +``` + +## Using `multipart/form-data` format + +### FormData + +To send data as `multipart/form-data`, pass a FormData instance as the payload. +You do not need to set the `Content-Type` header. Axios detects it from the payload type. +For browser, web worker, and React Native `FormData`, leave `Content-Type` unset so the runtime can add the multipart boundary. + +```js +const formData = new FormData(); +formData.append('foo', 'bar'); + +axios.post('https://httpbin.org/post', formData); +``` + +In node.js, use the [`form-data`](https://github.com/form-data/form-data) library: + +```js +const FormData = require('form-data'); + +const form = new FormData(); +form.append('my_field', 'my value'); +form.append('my_buffer', Buffer.alloc(10)); +form.append('my_file', fs.createReadStream('/foo/bar.jpg')); + +axios.post('https://example.com', form); +``` + +In node.js, when a `FormData` object provides `getHeaders()`, axios copies all returned headers by default for v1 compatibility. If the `FormData` object is custom or not fully trusted, set `formDataHeaderPolicy: 'content-only'` to copy only `Content-Type` and `Content-Length`, and set any other request headers explicitly with the request `headers` config. + +### Automatic serialization to FormData + +Since `v0.27.0`, Axios can serialize an object to FormData if the request `Content-Type` +header is set to `multipart/form-data`. + +This request submits data as FormData in browsers and Node.js: + +```js +import axios from 'axios'; + +axios + .post( + 'https://httpbin.org/post', + { x: 1 }, + { + headers: { + 'Content-Type': 'multipart/form-data', + }, + } + ) + .then(({ data }) => console.log(data)); +``` + +The Node.js build uses the [`form-data`](https://github.com/form-data/form-data) polyfill by default. + +You can override the FormData class with the `env.FormData` config option, but most applications do not need this: + +```js +const axios = require('axios'); +var FormData = require('form-data'); + +axios + .post( + 'https://httpbin.org/post', + { x: 1, buf: Buffer.alloc(10) }, + { + headers: { + 'Content-Type': 'multipart/form-data', + }, + } + ) + .then(({ data }) => console.log(data)); +``` + +The Axios FormData serializer supports these special endings: + +- `{}` - serialize the value with JSON.stringify +- `[]` - unwrap the array-like object as separate fields with the same key + +> Note: Arrays and FileList objects are unwrapped by default. + +FormData serializer supports additional options via `config.formSerializer: object` property to handle rare cases: + +- `visitor: Function` - user-defined visitor function that Axios calls recursively to serialize the data object + to a `FormData` object by following custom rules. + +- `dots: boolean = false` - use dot notation instead of brackets to serialize arrays and objects; + +- `metaTokens: boolean = true` - add the special ending (e.g `user{}: '{"name": "John"}'`) in the FormData key. + A backend body parser can use this meta-information to parse the value as JSON. + +- `indexes: null|false|true = false` - controls how Axios adds indexes to unwrapped keys of `flat` array-like objects. + - `null` - don't add brackets (`arr: 1`, `arr: 2`, `arr: 3`) + - `false`(default) - add empty brackets (`arr[]: 1`, `arr[]: 2`, `arr[]: 3`) + - `true` - add brackets with indexes (`arr[0]: 1`, `arr[1]: 2`, `arr[2]: 3`) +- `maxDepth: number = 100` - maximum object nesting depth the serializer will recurse into. If the + input object exceeds this depth, an `AxiosError` with `code: 'ERR_FORM_DATA_DEPTH_EXCEEDED'` is + thrown instead of overflowing the call stack. This protects server applications from DoS + attacks via deeply nested payloads. Set to `Infinity` to disable the limit and restore pre-fix behaviour. + +```js +// Raise the limit for a schema that genuinely nests deeper than 100 levels: +axios.postForm('/api', data, { formSerializer: { maxDepth: 200 } }); + +// Same protection applies to params serialization: +axios.get('/api', { params: data, paramsSerializer: { maxDepth: 200 } }); +``` + +Given this object: + +```js +const obj = { + x: 1, + arr: [1, 2, 3], + arr2: [1, [2], 3], + users: [ + { name: 'Peter', surname: 'Griffin' }, + { name: 'Thomas', surname: 'Anderson' }, + ], + 'obj2{}': [{ x: 1 }], +}; +``` + +The Axios serializer appends these fields: + +```js +const formData = new FormData(); +formData.append('x', '1'); +formData.append('arr[]', '1'); +formData.append('arr[]', '2'); +formData.append('arr[]', '3'); +formData.append('arr2[0]', '1'); +formData.append('arr2[1][0]', '2'); +formData.append('arr2[2]', '3'); +formData.append('users[0][name]', 'Peter'); +formData.append('users[0][surname]', 'Griffin'); +formData.append('users[1][name]', 'Thomas'); +formData.append('users[1][surname]', 'Anderson'); +formData.append('obj2{}', '[{"x":1}]'); +``` + +Axios supports `postForm`, `putForm`, and `patchForm` as shortcuts for the matching HTTP methods with the `Content-Type` header preset to `multipart/form-data`. + +## Posting files + +Submit a single file: + +```js +await axios.postForm('https://httpbin.org/post', { + myVar: 'foo', + file: document.querySelector('#fileInput').files[0], +}); +``` + +or multiple files as `multipart/form-data`: + +```js +await axios.postForm('https://httpbin.org/post', { + 'files[]': document.querySelector('#fileInput').files, +}); +``` + +`FileList` object can be passed directly: + +```js +await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files); +``` + +Axios sends all files with the same field name: `files[]`. + +## HTML form posting (browser) + +Pass an HTML Form element as a payload to submit it as `multipart/form-data` content. + +```js +await axios.postForm('https://httpbin.org/post', document.querySelector('#htmlForm')); +``` + +`FormData` and `HTMLForm` objects can also be posted as `JSON` by explicitly setting the `Content-Type` header to `application/json`: + +```js +await axios.post('https://httpbin.org/post', document.querySelector('#htmlForm'), { + headers: { + 'Content-Type': 'application/json', + }, +}); +``` + +For example, the Form + +```html +
+ + + + + + + + + +
+``` + +submits this JSON object: + +```js +{ + "foo": "1", + "deep": { + "prop": { + "spaced": "3" + } + }, + "baz": [ + "4", + "5" + ], + "user": { + "age": "value2" + } +} +``` + +Sending `Blobs`/`Files` as JSON (`base64`) is not currently supported. + +## Progress capturing + +Axios can capture request upload and download progress in browsers and Node.js. +Progress events are limited to `3` times per second. + +```js +await axios.post(url, data, { + onUploadProgress: function (axiosProgressEvent) { + /*{ + loaded: number; + total?: number; + progress?: number; // in range [0..1] + bytes: number; // how many bytes have been transferred since the last trigger (delta) + estimated?: number; // estimated time in seconds + rate?: number; // upload speed in bytes + upload: true; // upload sign + }*/ + }, + + onDownloadProgress: function (axiosProgressEvent) { + /*{ + loaded: number; + total?: number; + progress?: number; + bytes: number; + estimated?: number; + rate?: number; // download speed in bytes + download: true; // download sign + }*/ + }, +}); +``` + +You can also track stream upload/download progress in node.js: + +```js +const { data } = await axios.post(SERVER_URL, readableStream, { + onUploadProgress: ({ progress }) => { + console.log((progress * 100).toFixed(2)); + }, + + headers: { + 'Content-Length': contentLength, + }, + + maxRedirects: 0, // avoid buffering the entire stream +}); +``` + +> Note: +> Capturing FormData upload progress is not currently supported in node.js environments. + +> Warning: +> Set `maxRedirects: 0` when uploading streams in node.js. +> The follow-redirects package buffers the entire stream in RAM and does not follow the "backpressure" algorithm. + +## Rate limiting + +Download and upload rate limits can only be set for the http adapter (node.js): + +```js +const { data } = await axios.post(LOCAL_SERVER_URL, myBuffer, { + onUploadProgress: ({ progress, rate }) => { + console.log(`Upload [${(progress * 100).toFixed(2)}%]: ${(rate / 1024).toFixed(2)}KB/s`); + }, + + maxRate: [100 * 1024], // 100KB/s limit +}); +``` + +## AxiosHeaders + +Axios includes an `AxiosHeaders` class for working with headers through a Map-like API. +HTTP header names are case-insensitive, but Axios keeps the original header case for style and for servers that incorrectly depend on case. +Directly manipulating the headers object still works, but it is deprecated. + +### Working with headers + +An `AxiosHeaders` instance can contain several internal value types that control setting and merging. +Axios gets the final headers object with string values by calling `toJSON`. + +> Note: By JSON here we mean an object consisting only of string values intended to be sent over the network. + +The header value can be one of the following types: + +- `string` - normal string value sent to the server +- `null` - skip header when rendering to JSON +- `false` - skip header when rendering to JSON. Also indicates that the `set` method must be called with `rewrite` set to `true` + to overwrite this value (Axios uses this internally to allow users to opt out of installing certain headers like `User-Agent` or `Content-Type`) +- `undefined` - value is not set + +> Note: The header value is considered set if it is not equal to undefined. + +The headers object is always initialized inside interceptors and transformers: + +```ts +axios.interceptors.request.use((request: InternalAxiosRequestConfig) => { + request.headers.set('My-header', 'value'); + + request.headers.set({ + 'My-set-header1': 'my-set-value1', + 'My-set-header2': 'my-set-value2', + }); + + request.headers.set('User-Agent', false); // prevent Axios from setting this header later + + request.headers.setContentType('text/plain'); + + request.headers['My-set-header2'] = 'newValue'; // direct access is deprecated + + return request; +}); +``` + +You can iterate over an `AxiosHeaders` instance using a `for...of` statement: + +```js +const headers = new AxiosHeaders({ + foo: '1', + bar: '2', + baz: '3', +}); + +for (const [header, value] of headers) { + console.log(header, value); +} + +// foo 1 +// bar 2 +// baz 3 +``` + +### Preserving a specific header case + +Header names are case-insensitive, but `AxiosHeaders` keeps the case of the first matching key it sees. +If you need a specific case for non-standard case-sensitive servers, define a case preset with `undefined` and then set the value later: + +```js +const api = axios.create(); + +api.defaults.headers.common = { + 'content-type': undefined, + accept: undefined, +}; + +await api.put(url, data, { + headers: { + 'Content-Type': 'application/octet-stream', + Accept: 'application/json', + }, +}); +``` + +You can also compose the same behavior with `AxiosHeaders.concat`: + +```js +const headers = axios.AxiosHeaders.concat( + { 'content-type': undefined }, + { 'Content-Type': 'application/octet-stream' } +); + +await axios.put(url, data, { headers }); +``` + +### new AxiosHeaders(headers?) + +Constructs a new `AxiosHeaders` instance. + +``` +constructor(headers?: RawAxiosHeaders | AxiosHeaders | string); +``` + +If the headers object is a string, Axios parses it as raw HTTP headers. + +```js +const headers = new AxiosHeaders(` +Host: www.bing.com +User-Agent: curl/7.54.0 +Accept: */*`); + +console.log(headers); + +// Object [AxiosHeaders] { +// host: 'www.bing.com', +// 'user-agent': 'curl/7.54.0', +// accept: '*/*' +// } +``` + +### AxiosHeaders#set + +```ts +set(headerName, value: Axios, rewrite?: boolean); +set(headerName, value, rewrite?: (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean); +set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean); +``` + +The `rewrite` argument controls the overwriting behavior: + +- `false` - do not overwrite if the header's value is set (is not `undefined`) +- `undefined` (default) - overwrite the header unless its value is set to `false` +- `true` - rewrite anyway + +The option can also accept a user-defined function that determines whether to overwrite the value. + +Empty or whitespace-only header names are ignored. + +Returns `this`. + +### AxiosHeaders#get(header) + +``` + get(headerName: string, matcher?: true | AxiosHeaderMatcher): AxiosHeaderValue; + get(headerName: string, parser: RegExp): RegExpExecArray | null; +``` + +Returns the internal value of the header. It can take an extra argument to parse the header's value with `RegExp.exec`, +matcher function or internal key-value parser. + +```ts +const headers = new AxiosHeaders({ + 'Content-Type': 'multipart/form-data; boundary=Asrf456BGe4h', +}); + +console.log(headers.get('Content-Type')); +// multipart/form-data; boundary=Asrf456BGe4h + +console.log(headers.get('Content-Type', true)); // parse key-value pairs from a string separated with \s,;= delimiters: +// [Object: null prototype] { +// 'multipart/form-data': undefined, +// boundary: 'Asrf456BGe4h' +// } + +console.log( + headers.get('Content-Type', (value, name, headers) => { + return String(value).replace(/a/g, 'ZZZ'); + }) +); +// multipZZZrt/form-dZZZtZZZ; boundZZZry=Asrf456BGe4h + +console.log(headers.get('Content-Type', /boundary=(\w+)/)?.[0]); +// boundary=Asrf456BGe4h +``` + +Returns the value of the header. + +### AxiosHeaders#has(header, matcher?) + +``` +has(header: string, matcher?: AxiosHeaderMatcher): boolean; +``` + +Returns `true` if the header is set (has no `undefined` value). + +### AxiosHeaders#delete(header, matcher?) + +``` +delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean; +``` + +Returns `true` if at least one header has been removed. + +### AxiosHeaders#clear(matcher?) + +``` +clear(matcher?: AxiosHeaderMatcher): boolean; +``` + +Removes all headers. +Unlike the `delete` method matcher, this optional matcher matches the header name rather than the value. + +```ts +const headers = new AxiosHeaders({ + foo: '1', + 'x-foo': '2', + 'x-bar': '3', +}); + +console.log(headers.clear(/^x-/)); // true + +console.log(headers.toJSON()); // [Object: null prototype] { foo: '1' } +``` + +Returns `true` if at least one header has been cleared. + +### AxiosHeaders#normalize(format); + +If the headers object was changed directly, it can have duplicates with the same name but in different cases. +This method normalizes the headers object by combining duplicate keys into one. +Axios uses this method internally after calling each interceptor. +Set `format` to true for converting header names to lowercase and capitalizing the initial letters (`cOntEnt-type` => `Content-Type`) + +```js +const headers = new AxiosHeaders({ + foo: '1', +}); + +headers.Foo = '2'; +headers.FOO = '3'; + +console.log(headers.toJSON()); // [Object: null prototype] { foo: '1', Foo: '2', FOO: '3' } +console.log(headers.normalize().toJSON()); // [Object: null prototype] { foo: '3' } +console.log(headers.normalize(true).toJSON()); // [Object: null prototype] { Foo: '3' } +``` + +Returns `this`. + +### AxiosHeaders#concat(...targets) + +``` +concat(...targets: Array): AxiosHeaders; +``` + +Merges the instance with targets into a new `AxiosHeaders` instance. If the target is a string, Axios parses it as raw HTTP headers. + +Returns a new `AxiosHeaders` instance. + +### AxiosHeaders#toJSON(asStrings?) + +``` +toJSON(asStrings: true): Record; +toJSON(asStrings?: false): Record; +``` + +Resolves all internal header values into a new null prototype object. +Set `asStrings` to true to resolve arrays as a string containing all elements, separated by commas. + +### AxiosHeaders.from(thing?) + +``` +from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders; +``` + +Returns a new `AxiosHeaders` instance created from the raw headers passed in, +or returns the given headers object if it's already an `AxiosHeaders` instance. + +### AxiosHeaders.concat(...targets) + +``` +concat(...targets: Array): AxiosHeaders; +``` + +Returns a new `AxiosHeaders` instance created by merging the target objects. + +### Shortcuts + +The following shortcuts are available: + +- `setContentType`, `getContentType`, `hasContentType` + +- `setContentLength`, `getContentLength`, `hasContentLength` + +- `setAccept`, `getAccept`, `hasAccept` + +- `setUserAgent`, `getUserAgent`, `hasUserAgent` + +- `setContentEncoding`, `getContentEncoding`, `hasContentEncoding` + +## Fetch adapter + +Axios introduced the fetch adapter in `v1.7.0`. By default, Axios uses it when the `xhr` and `http` adapters are not available in the build or not supported by the environment. +To use it by default, select it explicitly: + +```js +const { data } = axios.get(url, { + adapter: 'fetch', // by default ['xhr', 'http', 'fetch'] +}); +``` + +You can create a separate instance for this: + +```js +const fetchAxios = axios.create({ + adapter: 'fetch', +}); + +const { data } = fetchAxios.get(url); +``` + +The adapter supports the same features as the `xhr` adapter, including upload and download progress capturing. +It also supports response types such as `stream` and `formdata` when the environment supports them. + +When `auth` is omitted, the fetch adapter can read HTTP Basic auth credentials from the request URL, for example `https://user:pass@example.com`. Percent-encoded URL credentials are decoded before the `Authorization` header is generated, and `auth` takes precedence over URL-embedded credentials. + +### Custom fetch + +Since `v1.12.0`, you can configure the fetch adapter to use a custom fetch API instead of environment globals. +Pass a custom `fetch` function, `Request`, and `Response` constructors through `env` config. +This helps in custom environments and app frameworks. + +When using a custom fetch, you may also need to set custom `Request` and `Response` constructors. If you do not set them, Axios uses the global objects. +If your custom fetch API does not provide these objects and the globals are incompatible with it, pass `null` to disable them inside the fetch adapter. + +> Note: Setting `Request` and `Response` to `null` prevents the fetch adapter from capturing upload and download progress. + +Basic example: + +```js +import customFetchFunction from 'customFetchModule'; + +const instance = axios.create({ + adapter: 'fetch', + onDownloadProgress(e) { + console.log('downloadProgress', e); + }, + env: { + fetch: customFetchFunction, + Request: null, // undefined -> use the global constructor + Response: null, + }, +}); +``` + +#### Using with Tauri + +A minimal example of setting up Axios for use in a [Tauri](https://tauri.app/plugin/http-client/) app with a platform fetch function that ignores CORS policy for requests. + +```js +import { fetch } from '@tauri-apps/plugin-http'; +import axios from 'axios'; + +const instance = axios.create({ + adapter: 'fetch', + onDownloadProgress(e) { + console.log('downloadProgress', e); + }, + env: { + fetch, + }, +}); + +const { data } = await instance.get('https://google.com'); +``` + +#### Using with SvelteKit + +[SvelteKit](https://svelte.dev/docs/kit/web-standards#Fetch-APIs) uses a custom fetch function for server rendering in `load` functions. It also uses relative paths, which are incompatible with the standard URL API. Configure Axios to use SvelteKit's custom fetch API: + +```js +export async function load({ fetch }) { + const { data: post } = await axios.get('https://jsonplaceholder.typicode.com/posts/1', { + adapter: 'fetch', + env: { + fetch, + Request: null, + Response: null, + }, + }); + + return { post }; +} +``` + +#### HTTP/2 support + +Axios supports HTTP/2 through the Node.js `http` adapter, introduced in v1.13.0. + +Support depends on the runtime environment. Axios relies on Node.js APIs, so HTTP/2 works in supported Node.js versions but may not work in other environments such as Bun or Deno. + +Options like `httpVersion` and `http2Options` are adapter-specific and may not behave the same way in every environment. + +Note: HTTP/2 redirects are currently not supported by the HTTP/2 adapter. + +```js +const form = new FormData(); + +form.append('foo', '123'); + +const { data, headers, status } = await axios.post('https://httpbin.org/post', form, { + onUploadProgress(e) { + console.log('upload progress', e); + }, + onDownloadProgress(e) { + console.log('download progress', e); + }, + responseType: 'arraybuffer', +}); +``` + +## Semver + +Axios follows [semver](https://semver.org/) since `v1.0.0`. + +## Promises + +axios depends on a native ES6 Promise implementation to be [supported](https://caniuse.com/promises). +If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise). + +## TypeScript + +axios includes [TypeScript](https://typescriptlang.org) definitions and a type guard for axios errors. + +```typescript +let user: User = null; +try { + const { data } = await axios.get('/user?ID=12345'); + user = data.userDetails; +} catch (error) { + if (axios.isAxiosError(error)) { + handleAxiosError(error); + } else { + handleUnexpectedError(error); + } +} +``` + +Use `axios.isCancel()` to narrow cancellation errors to `CanceledError`: + +```typescript +const controller = new AbortController(); + +try { + await axios.get('/user?ID=12345', { signal: controller.signal }); +} catch (error) { + if (axios.isCancel(error)) { + handleCancellation(error); + } +} +``` + +Because axios publishes an ESM default export and a CJS `module.exports`, TypeScript has a few caveats. +The recommended setting is `"moduleResolution": "node16"`, which is implied by `"module": "node16"`. This requires TypeScript 4.7 or greater. +If you use ESM, your settings should be fine. +If you compile TypeScript to CJS and can't use `"moduleResolution": "node 16"`, enable `esModuleInterop`. +If you use TypeScript to type check CJS JavaScript code, your only option is to use `"moduleResolution": "node16"`. + +You can also create a custom instance with typed interceptors: + +```typescript +import axios, { AxiosInstance, InternalAxiosRequestConfig } from 'axios'; + +const apiClient: AxiosInstance = axios.create({ + baseURL: 'https://api.example.com', + timeout: 10000, +}); + +apiClient.interceptors.request.use((config: InternalAxiosRequestConfig) => { + // Add auth token + return config; +}); +``` + +## Online one-click setup + +You can use Gitpod, a free online IDE for open source projects, to contribute or run the examples online. + +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/axios/axios/blob/main/examples/server.js) + +## Contributing + +### Local setup + +As a supply-chain hardening measure, this repository ships a project-level `.npmrc` that sets `ignore-scripts=true`. This blocks npm lifecycle scripts (`preinstall`, `install`, `postinstall`, `prepare`) from any direct or transitive dependency when you run `npm install` or `npm ci` inside the repo. See [THREATMODEL.md](./THREATMODEL.md) (threat T-S2) for the rationale. + +One consequence: the repository's own `prepare` hook (which installs Husky's git hooks) will **not** run automatically. After your first install, enable the git hooks manually: + +```bash +npm ci +npm rebuild husky && npx husky +``` + +Run those two commands once per fresh checkout. You do **not** need to re-run them after every subsequent `npm install`. + +Do not remove `ignore-scripts=true` from `.npmrc` to "fix" this. That reopens the lifecycle-script attack surface for every other package in the tree. All CI workflows already invoke npm with `--ignore-scripts`, so local behaviour matches CI. + +## Resources + +- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md) +- [Ecosystem](https://github.com/axios/axios/blob/v1.x/ECOSYSTEM.md) +- [Contributing Guide](https://github.com/axios/axios/blob/v1.x/CONTRIBUTING.md) +- [Code of Conduct](https://github.com/axios/axios/blob/v1.x/CODE_OF_CONDUCT.md) + +## Credits + +axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) in [AngularJS](https://angularjs.org/). It provides a standalone `$http`-like service for use outside AngularJS. + +## License + +[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) diff --git a/node_modules/axios/index.d.cts b/node_modules/axios/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..2996ce14094a6961d7ad1c46288e9a19a6a184d3 --- /dev/null +++ b/node_modules/axios/index.d.cts @@ -0,0 +1,722 @@ +type MethodsHeaders = Partial< + { + [Key in axios.Method as Lowercase]: AxiosHeaders; + } & { common: AxiosHeaders } +>; + +type AxiosHeaderMatcher = + | string + | RegExp + | ((this: AxiosHeaders, value: string, name: string) => boolean); + +type AxiosHeaderParser = (this: AxiosHeaders, value: axios.AxiosHeaderValue, header: string) => any; + +type CommonRequestHeadersList = + | 'Accept' + | 'Content-Length' + | 'User-Agent' + | 'Content-Encoding' + | 'Authorization' + | 'Location'; + +type ContentType = + | axios.AxiosHeaderValue + | 'text/html' + | 'text/plain' + | 'multipart/form-data' + | 'application/json' + | 'application/x-www-form-urlencoded' + | 'application/octet-stream'; + +type CommonResponseHeadersList = + | 'Server' + | 'Content-Type' + | 'Content-Length' + | 'Cache-Control' + | 'Content-Encoding'; + +type CommonResponseHeaderKey = CommonResponseHeadersList | Lowercase; + +type BrowserProgressEvent = any; + +declare class AxiosHeaders { + constructor(headers?: axios.RawAxiosHeaders | AxiosHeaders | string); + + [key: string]: any; + + set( + headerName?: string, + value?: axios.AxiosHeaderValue, + rewrite?: boolean | AxiosHeaderMatcher + ): AxiosHeaders; + set(headers?: axios.RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders; + + get(headerName: string, parser: RegExp): RegExpExecArray | null; + get(headerName: string, matcher?: true | AxiosHeaderParser): axios.AxiosHeaderValue; + + has(header: string, matcher?: AxiosHeaderMatcher): boolean; + + delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean; + + clear(matcher?: AxiosHeaderMatcher): boolean; + + normalize(format: boolean): AxiosHeaders; + + concat( + ...targets: Array + ): AxiosHeaders; + + toJSON(asStrings: true): Record; + toJSON(asStrings?: false): Record; + toJSON(asStrings?: boolean): Record; + + static from(thing?: AxiosHeaders | axios.RawAxiosHeaders | string): AxiosHeaders; + + static accessor(header: string | string[]): AxiosHeaders; + + static concat( + ...targets: Array + ): AxiosHeaders; + + setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getContentType(parser?: RegExp): RegExpExecArray | null; + getContentType(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue; + hasContentType(matcher?: AxiosHeaderMatcher): boolean; + + setContentLength( + value: axios.AxiosHeaderValue, + rewrite?: boolean | AxiosHeaderMatcher + ): AxiosHeaders; + getContentLength(parser?: RegExp): RegExpExecArray | null; + getContentLength(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue; + hasContentLength(matcher?: AxiosHeaderMatcher): boolean; + + setAccept(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getAccept(parser?: RegExp): RegExpExecArray | null; + getAccept(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue; + hasAccept(matcher?: AxiosHeaderMatcher): boolean; + + setUserAgent(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getUserAgent(parser?: RegExp): RegExpExecArray | null; + getUserAgent(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue; + hasUserAgent(matcher?: AxiosHeaderMatcher): boolean; + + setContentEncoding( + value: axios.AxiosHeaderValue, + rewrite?: boolean | AxiosHeaderMatcher + ): AxiosHeaders; + getContentEncoding(parser?: RegExp): RegExpExecArray | null; + getContentEncoding(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue; + hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean; + + setAuthorization( + value: axios.AxiosHeaderValue, + rewrite?: boolean | AxiosHeaderMatcher + ): AxiosHeaders; + getAuthorization(parser?: RegExp): RegExpExecArray | null; + getAuthorization(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue; + hasAuthorization(matcher?: AxiosHeaderMatcher): boolean; + + getSetCookie(): string[]; + + [Symbol.iterator](): IterableIterator<[string, axios.AxiosHeaderValue]>; +} + +declare class AxiosError extends Error { + constructor( + message?: string, + code?: string, + config?: axios.InternalAxiosRequestConfig, + request?: any, + response?: axios.AxiosResponse + ); + + config?: axios.InternalAxiosRequestConfig; + code?: string; + request?: any; + response?: axios.AxiosResponse; + isAxiosError: boolean; + status?: number; + toJSON: () => object; + cause?: Error; + event?: BrowserProgressEvent; + static from( + error: Error | unknown, + code?: string, + config?: axios.InternalAxiosRequestConfig, + request?: any, + response?: axios.AxiosResponse, + customProps?: object + ): AxiosError; + static readonly ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS'; + static readonly ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE'; + static readonly ERR_BAD_OPTION = 'ERR_BAD_OPTION'; + static readonly ERR_NETWORK = 'ERR_NETWORK'; + static readonly ERR_DEPRECATED = 'ERR_DEPRECATED'; + static readonly ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE'; + static readonly ERR_BAD_REQUEST = 'ERR_BAD_REQUEST'; + static readonly ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT'; + static readonly ERR_INVALID_URL = 'ERR_INVALID_URL'; + static readonly ERR_CANCELED = 'ERR_CANCELED'; + static readonly ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED'; + static readonly ECONNABORTED = 'ECONNABORTED'; + static readonly ECONNREFUSED = 'ECONNREFUSED'; + static readonly ETIMEDOUT = 'ETIMEDOUT'; +} + +declare class CanceledError extends AxiosError { + readonly name: 'CanceledError'; +} + +declare class Axios { + constructor(config?: axios.AxiosRequestConfig); + defaults: axios.AxiosDefaults; + interceptors: { + request: axios.AxiosInterceptorManager; + response: axios.AxiosInterceptorManager; + }; + getUri(config?: axios.AxiosRequestConfig): string; + request, D = any>( + config: axios.AxiosRequestConfig + ): Promise; + get, D = any>( + url: string, + config?: axios.AxiosRequestConfig + ): Promise; + delete, D = any>( + url: string, + config?: axios.AxiosRequestConfig + ): Promise; + head, D = any>( + url: string, + config?: axios.AxiosRequestConfig + ): Promise; + options, D = any>( + url: string, + config?: axios.AxiosRequestConfig + ): Promise; + post, D = any>( + url: string, + data?: D, + config?: axios.AxiosRequestConfig + ): Promise; + put, D = any>( + url: string, + data?: D, + config?: axios.AxiosRequestConfig + ): Promise; + patch, D = any>( + url: string, + data?: D, + config?: axios.AxiosRequestConfig + ): Promise; + postForm, D = any>( + url: string, + data?: D, + config?: axios.AxiosRequestConfig + ): Promise; + putForm, D = any>( + url: string, + data?: D, + config?: axios.AxiosRequestConfig + ): Promise; + patchForm, D = any>( + url: string, + data?: D, + config?: axios.AxiosRequestConfig + ): Promise; + query, D = any>( + url: string, + data?: D, + config?: axios.AxiosRequestConfig + ): Promise; +} + +declare enum HttpStatusCode { + Continue = 100, + SwitchingProtocols = 101, + Processing = 102, + EarlyHints = 103, + Ok = 200, + Created = 201, + Accepted = 202, + NonAuthoritativeInformation = 203, + NoContent = 204, + ResetContent = 205, + PartialContent = 206, + MultiStatus = 207, + AlreadyReported = 208, + ImUsed = 226, + MultipleChoices = 300, + MovedPermanently = 301, + Found = 302, + SeeOther = 303, + NotModified = 304, + UseProxy = 305, + Unused = 306, + TemporaryRedirect = 307, + PermanentRedirect = 308, + BadRequest = 400, + Unauthorized = 401, + PaymentRequired = 402, + Forbidden = 403, + NotFound = 404, + MethodNotAllowed = 405, + NotAcceptable = 406, + ProxyAuthenticationRequired = 407, + RequestTimeout = 408, + Conflict = 409, + Gone = 410, + LengthRequired = 411, + PreconditionFailed = 412, + PayloadTooLarge = 413, + UriTooLong = 414, + UnsupportedMediaType = 415, + RangeNotSatisfiable = 416, + ExpectationFailed = 417, + ImATeapot = 418, + MisdirectedRequest = 421, + UnprocessableEntity = 422, + Locked = 423, + FailedDependency = 424, + TooEarly = 425, + UpgradeRequired = 426, + PreconditionRequired = 428, + TooManyRequests = 429, + RequestHeaderFieldsTooLarge = 431, + UnavailableForLegalReasons = 451, + InternalServerError = 500, + NotImplemented = 501, + BadGateway = 502, + ServiceUnavailable = 503, + GatewayTimeout = 504, + HttpVersionNotSupported = 505, + VariantAlsoNegotiates = 506, + InsufficientStorage = 507, + LoopDetected = 508, + NotExtended = 510, + NetworkAuthenticationRequired = 511, +} + +type InternalAxiosError = AxiosError; + +declare namespace axios { + type AxiosError = InternalAxiosError; + + interface RawAxiosHeaders { + [key: string]: AxiosHeaderValue; + } + + type RawAxiosRequestHeaders = Partial< + RawAxiosHeaders & { + [Key in CommonRequestHeadersList]: AxiosHeaderValue; + } & { + 'Content-Type': ContentType; + } + >; + + type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders; + + type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null; + + type RawCommonResponseHeaders = { + [Key in CommonResponseHeaderKey]: AxiosHeaderValue; + } & { + 'set-cookie': string[]; + }; + + type RawAxiosResponseHeaders = Partial; + + type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders; + + interface AxiosRequestTransformer { + (this: InternalAxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any; + } + + interface AxiosResponseTransformer { + ( + this: InternalAxiosRequestConfig, + data: any, + headers: AxiosResponseHeaders, + status?: number + ): any; + } + + interface AxiosAdapter { + (config: InternalAxiosRequestConfig): AxiosPromise; + } + + interface AxiosBasicCredentials { + username: string; + password: string; + } + + interface AxiosProxyConfig { + host: string; + port: number; + auth?: AxiosBasicCredentials; + protocol?: string; + } + + type UppercaseMethod = + | 'GET' + | 'DELETE' + | 'HEAD' + | 'OPTIONS' + | 'POST' + | 'PUT' + | 'PATCH' + | 'PURGE' + | 'LINK' + | 'UNLINK' + | 'QUERY'; + + type Method = (UppercaseMethod | Lowercase) & {}; + + type ResponseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream' | 'formdata'; + + type UppercaseResponseEncoding = + | 'ASCII' + | 'ANSI' + | 'BINARY' + | 'BASE64' + | 'BASE64URL' + | 'HEX' + | 'LATIN1' + | 'UCS-2' + | 'UCS2' + | 'UTF-8' + | 'UTF8' + | 'UTF16LE'; + + type responseEncoding = (UppercaseResponseEncoding | Lowercase) & {}; + + interface TransitionalOptions { + silentJSONParsing?: boolean; + forcedJSONParsing?: boolean; + clarifyTimeoutError?: boolean; + legacyInterceptorReqResOrdering?: boolean; + advertiseZstdAcceptEncoding?: boolean; + validateStatusUndefinedResolves?: boolean; + } + + interface GenericAbortSignal { + readonly aborted: boolean; + onabort?: ((...args: any) => any) | null; + addEventListener?: (...args: any) => any; + removeEventListener?: (...args: any) => any; + } + + interface FormDataVisitorHelpers { + defaultVisitor: SerializerVisitor; + convertValue: (value: any) => any; + isVisitable: (value: any) => boolean; + } + + interface SerializerVisitor { + ( + this: GenericFormData, + value: any, + key: string | number, + path: null | Array, + helpers: FormDataVisitorHelpers + ): boolean; + } + + interface SerializerOptions { + visitor?: SerializerVisitor; + dots?: boolean; + metaTokens?: boolean; + indexes?: boolean | null; + } + + // tslint:disable-next-line + interface FormSerializerOptions extends SerializerOptions {} + + interface ParamEncoder { + (value: any, defaultEncoder: (value: any) => any): any; + } + + interface CustomParamsSerializer { + (params: Record, options?: ParamsSerializerOptions): string; + } + + interface ParamsSerializerOptions extends SerializerOptions { + encode?: ParamEncoder; + serialize?: CustomParamsSerializer; + } + + type MaxUploadRate = number; + + type MaxDownloadRate = number; + + interface AxiosProgressEvent { + loaded: number; + total?: number; + progress?: number; + bytes: number; + rate?: number; + estimated?: number; + upload?: boolean; + download?: boolean; + event?: BrowserProgressEvent; + lengthComputable: boolean; + } + + type Milliseconds = number; + + type AxiosAdapterName = 'fetch' | 'xhr' | 'http' | (string & {}); + + type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName; + + type AddressFamily = 4 | 6 | undefined; + + interface LookupAddressEntry { + address: string; + family?: AddressFamily; + } + + type LookupAddress = string | LookupAddressEntry; + + interface AxiosRequestConfig { + url?: string; + method?: Method | string; + baseURL?: string; + allowAbsoluteUrls?: boolean; + transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[]; + transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[]; + headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders; + params?: any; + paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer; + data?: D; + timeout?: Milliseconds; + timeoutErrorMessage?: string; + withCredentials?: boolean; + adapter?: AxiosAdapterConfig | AxiosAdapterConfig[]; + auth?: AxiosBasicCredentials; + responseType?: ResponseType; + responseEncoding?: responseEncoding | string; + xsrfCookieName?: string; + xsrfHeaderName?: string; + onUploadProgress?: (progressEvent: AxiosProgressEvent) => void; + onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void; + maxContentLength?: number; + validateStatus?: ((status: number) => boolean) | null; + maxBodyLength?: number; + maxRedirects?: number; + maxRate?: number | [MaxUploadRate, MaxDownloadRate]; + beforeRedirect?: ( + options: Record, + responseDetails: { headers: Record; statusCode: HttpStatusCode }, + requestDetails: { headers: Record; url: string; method: string }, + ) => void; + socketPath?: string | null; + allowedSocketPaths?: string | string[] | null; + transport?: any; + httpAgent?: any; + httpsAgent?: any; + proxy?: AxiosProxyConfig | false; + cancelToken?: CancelToken | undefined; + decompress?: boolean; + transitional?: TransitionalOptions; + signal?: GenericAbortSignal; + insecureHTTPParser?: boolean; + env?: { + FormData?: new (...args: any[]) => object; + fetch?: (input: URL | Request | string, init?: RequestInit) => Promise; + Request?: new (input: URL | Request | string, init?: RequestInit) => Request; + Response?: new ( + body?: ArrayBuffer | ArrayBufferView | Blob | FormData | URLSearchParams | string | null, + init?: ResponseInit + ) => Response; + }; + formSerializer?: FormSerializerOptions; + family?: AddressFamily; + lookup?: + | (( + hostname: string, + options: object, + cb: ( + err: Error | null, + address: LookupAddress | LookupAddress[], + family?: AddressFamily + ) => void + ) => void) + | (( + hostname: string, + options: object + ) => Promise< + | [address: LookupAddressEntry | LookupAddressEntry[], family?: AddressFamily] + | LookupAddress + >); + withXSRFToken?: boolean | ((config: InternalAxiosRequestConfig) => boolean | undefined); + parseReviver?: (this: any, key: string, value: any, context?: { source?: string }) => any; + fetchOptions?: + | Omit + | Record; + httpVersion?: 1 | 2; + http2Options?: Record & { + sessionTimeout?: number; + }; + formDataHeaderPolicy?: 'legacy' | 'content-only'; + redact?: string[]; + sensitiveHeaders?: string[]; + } + + // Alias + type RawAxiosRequestConfig = AxiosRequestConfig; + + interface InternalAxiosRequestConfig extends AxiosRequestConfig { + headers: AxiosRequestHeaders; + } + + interface HeadersDefaults { + common: RawAxiosRequestHeaders; + delete: RawAxiosRequestHeaders; + get: RawAxiosRequestHeaders; + head: RawAxiosRequestHeaders; + post: RawAxiosRequestHeaders; + put: RawAxiosRequestHeaders; + patch: RawAxiosRequestHeaders; + options?: RawAxiosRequestHeaders; + purge?: RawAxiosRequestHeaders; + link?: RawAxiosRequestHeaders; + unlink?: RawAxiosRequestHeaders; + query?: RawAxiosRequestHeaders; + } + + interface AxiosDefaults extends Omit, 'headers'> { + headers: HeadersDefaults; + } + + interface CreateAxiosDefaults extends Omit, 'headers'> { + headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial; + } + + interface AxiosResponse { + data: T; + status: number; + statusText: string; + headers: (H & RawAxiosResponseHeaders) | AxiosResponseHeaders; + config: InternalAxiosRequestConfig; + request?: any; + } + + type AxiosPromise = Promise>; + + interface CancelStatic { + new (message?: string): Cancel; + } + + interface Cancel { + message: string | undefined; + } + + interface Canceler { + (message?: string, config?: AxiosRequestConfig, request?: any): void; + } + + interface CancelTokenStatic { + new (executor: (cancel: Canceler) => void): CancelToken; + source(): CancelTokenSource; + } + + interface CancelToken { + promise: Promise; + reason?: Cancel; + throwIfRequested(): void; + } + + interface CancelTokenSource { + token: CancelToken; + cancel: Canceler; + } + + interface AxiosInterceptorOptions { + synchronous?: boolean; + runWhen?: ((config: InternalAxiosRequestConfig) => boolean) | null; + } + + type AxiosInterceptorFulfilled = (value: T) => T | Promise; + type AxiosInterceptorRejected = (error: any) => any; + + type AxiosRequestInterceptorUse = ( + onFulfilled?: AxiosInterceptorFulfilled | null, + onRejected?: AxiosInterceptorRejected | null, + options?: AxiosInterceptorOptions + ) => number; + + type AxiosResponseInterceptorUse = ( + onFulfilled?: AxiosInterceptorFulfilled | null, + onRejected?: AxiosInterceptorRejected | null + ) => number; + + interface AxiosInterceptorHandler { + fulfilled: AxiosInterceptorFulfilled; + rejected?: AxiosInterceptorRejected; + synchronous: boolean; + runWhen?: ((config: InternalAxiosRequestConfig) => boolean) | null; + } + + interface AxiosInterceptorManager { + use: V extends AxiosResponse ? AxiosResponseInterceptorUse : AxiosRequestInterceptorUse; + eject(id: number): void; + clear(): void; + handlers?: Array>; + } + + interface AxiosInstance extends Axios { + , D = any>(config: AxiosRequestConfig): Promise; + , D = any>( + url: string, + config?: AxiosRequestConfig + ): Promise; + + create(config?: CreateAxiosDefaults): AxiosInstance; + defaults: Omit & { + headers: HeadersDefaults & { + [key: string]: AxiosHeaderValue; + }; + }; + } + + interface GenericFormData { + append(name: string, value: any, options?: any): any; + } + + interface GenericHTMLFormElement { + name: string; + method: string; + submit(): void; + } + + interface AxiosStatic extends AxiosInstance { + Cancel: CancelStatic; + CancelToken: CancelTokenStatic; + Axios: typeof Axios; + AxiosError: typeof AxiosError; + CanceledError: typeof CanceledError; + HttpStatusCode: typeof HttpStatusCode; + readonly VERSION: string; + isCancel(value: any): value is CanceledError; + all(values: Array>): Promise; + spread(callback: (...args: T[]) => R): (array: T[]) => R; + isAxiosError(payload: any): payload is AxiosError; + toFormData( + sourceObj: object, + targetFormData?: GenericFormData, + options?: FormSerializerOptions + ): GenericFormData; + formToJSON(form: GenericFormData | GenericHTMLFormElement): object; + getAdapter(adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined): AxiosAdapter; + AxiosHeaders: typeof AxiosHeaders; + mergeConfig( + config1: AxiosRequestConfig, + config2: AxiosRequestConfig + ): AxiosRequestConfig; + } +} + +declare const axios: axios.AxiosStatic; + +export = axios; diff --git a/node_modules/axios/index.d.ts b/node_modules/axios/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9392b41e1b4a4ea0fcbd3aea988feae7408ef85 --- /dev/null +++ b/node_modules/axios/index.d.ts @@ -0,0 +1,739 @@ +// TypeScript Version: 4.7 +type StringLiteralsOrString = Literals | (string & {}); + +export type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null; + +export interface RawAxiosHeaders { + [key: string]: AxiosHeaderValue; +} + +type MethodsHeaders = Partial< + { + [Key in Method as Lowercase]: AxiosHeaders; + } & { common: AxiosHeaders } +>; + +type AxiosHeaderMatcher = + | string + | RegExp + | ((this: AxiosHeaders, value: string, name: string) => boolean); + +type AxiosHeaderParser = (this: AxiosHeaders, value: AxiosHeaderValue, header: string) => any; + +export class AxiosHeaders { + constructor(headers?: RawAxiosHeaders | AxiosHeaders | string); + + [key: string]: any; + + set( + headerName?: string, + value?: AxiosHeaderValue, + rewrite?: boolean | AxiosHeaderMatcher + ): AxiosHeaders; + set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders; + + get(headerName: string, parser: RegExp): RegExpExecArray | null; + get(headerName: string, matcher?: true | AxiosHeaderParser): AxiosHeaderValue; + + has(header: string, matcher?: AxiosHeaderMatcher): boolean; + + delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean; + + clear(matcher?: AxiosHeaderMatcher): boolean; + + normalize(format: boolean): AxiosHeaders; + + concat( + ...targets: Array + ): AxiosHeaders; + + toJSON(asStrings: true): Record; + toJSON(asStrings?: false): Record; + toJSON(asStrings?: boolean): Record; + + static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders; + + static accessor(header: string | string[]): AxiosHeaders; + + static concat( + ...targets: Array + ): AxiosHeaders; + + setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getContentType(parser?: RegExp): RegExpExecArray | null; + getContentType(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasContentType(matcher?: AxiosHeaderMatcher): boolean; + + setContentLength(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getContentLength(parser?: RegExp): RegExpExecArray | null; + getContentLength(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasContentLength(matcher?: AxiosHeaderMatcher): boolean; + + setAccept(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getAccept(parser?: RegExp): RegExpExecArray | null; + getAccept(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasAccept(matcher?: AxiosHeaderMatcher): boolean; + + setUserAgent(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getUserAgent(parser?: RegExp): RegExpExecArray | null; + getUserAgent(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasUserAgent(matcher?: AxiosHeaderMatcher): boolean; + + setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getContentEncoding(parser?: RegExp): RegExpExecArray | null; + getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean; + + setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getAuthorization(parser?: RegExp): RegExpExecArray | null; + getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasAuthorization(matcher?: AxiosHeaderMatcher): boolean; + + getSetCookie(): string[]; + + [Symbol.iterator](): IterableIterator<[string, AxiosHeaderValue]>; +} + +type CommonRequestHeadersList = + | 'Accept' + | 'Content-Length' + | 'User-Agent' + | 'Content-Encoding' + | 'Authorization' + | 'Location'; + +type ContentType = + | AxiosHeaderValue + | 'text/html' + | 'text/plain' + | 'multipart/form-data' + | 'application/json' + | 'application/x-www-form-urlencoded' + | 'application/octet-stream'; + +export type RawAxiosRequestHeaders = Partial< + RawAxiosHeaders & { + [Key in CommonRequestHeadersList]: AxiosHeaderValue; + } & { + 'Content-Type': ContentType; + } +>; + +export type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders; + +type CommonResponseHeadersList = + | 'Server' + | 'Content-Type' + | 'Content-Length' + | 'Cache-Control' + | 'Content-Encoding'; + +type CommonResponseHeaderKey = CommonResponseHeadersList | Lowercase; + +type RawCommonResponseHeaders = { + [Key in CommonResponseHeaderKey]: AxiosHeaderValue; +} & { + 'set-cookie': string[]; +}; + +export type RawAxiosResponseHeaders = Partial; + +export type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders; + +export interface AxiosRequestTransformer { + (this: InternalAxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any; +} + +export interface AxiosResponseTransformer { + ( + this: InternalAxiosRequestConfig, + data: any, + headers: AxiosResponseHeaders, + status?: number + ): any; +} + +export interface AxiosAdapter { + (config: InternalAxiosRequestConfig): AxiosPromise; +} + +export interface AxiosBasicCredentials { + username: string; + password: string; +} + +export interface AxiosProxyConfig { + host: string; + port: number; + auth?: AxiosBasicCredentials; + protocol?: string; +} + +export enum HttpStatusCode { + Continue = 100, + SwitchingProtocols = 101, + Processing = 102, + EarlyHints = 103, + Ok = 200, + Created = 201, + Accepted = 202, + NonAuthoritativeInformation = 203, + NoContent = 204, + ResetContent = 205, + PartialContent = 206, + MultiStatus = 207, + AlreadyReported = 208, + ImUsed = 226, + MultipleChoices = 300, + MovedPermanently = 301, + Found = 302, + SeeOther = 303, + NotModified = 304, + UseProxy = 305, + Unused = 306, + TemporaryRedirect = 307, + PermanentRedirect = 308, + BadRequest = 400, + Unauthorized = 401, + PaymentRequired = 402, + Forbidden = 403, + NotFound = 404, + MethodNotAllowed = 405, + NotAcceptable = 406, + ProxyAuthenticationRequired = 407, + RequestTimeout = 408, + Conflict = 409, + Gone = 410, + LengthRequired = 411, + PreconditionFailed = 412, + PayloadTooLarge = 413, + UriTooLong = 414, + UnsupportedMediaType = 415, + RangeNotSatisfiable = 416, + ExpectationFailed = 417, + ImATeapot = 418, + MisdirectedRequest = 421, + UnprocessableEntity = 422, + Locked = 423, + FailedDependency = 424, + TooEarly = 425, + UpgradeRequired = 426, + PreconditionRequired = 428, + TooManyRequests = 429, + RequestHeaderFieldsTooLarge = 431, + UnavailableForLegalReasons = 451, + InternalServerError = 500, + NotImplemented = 501, + BadGateway = 502, + ServiceUnavailable = 503, + GatewayTimeout = 504, + HttpVersionNotSupported = 505, + VariantAlsoNegotiates = 506, + InsufficientStorage = 507, + LoopDetected = 508, + NotExtended = 510, + NetworkAuthenticationRequired = 511, +} + +type UppercaseMethod = + | 'GET' + | 'DELETE' + | 'HEAD' + | 'OPTIONS' + | 'POST' + | 'PUT' + | 'PATCH' + | 'PURGE' + | 'LINK' + | 'UNLINK' + | 'QUERY'; + +export type Method = (UppercaseMethod | Lowercase) & {}; + +export type ResponseType = + | 'arraybuffer' + | 'blob' + | 'document' + | 'json' + | 'text' + | 'stream' + | 'formdata'; + +type UppercaseResponseEncoding = + | 'ASCII' + | 'ANSI' + | 'BINARY' + | 'BASE64' + | 'BASE64URL' + | 'HEX' + | 'LATIN1' + | 'UCS-2' + | 'UCS2' + | 'UTF-8' + | 'UTF8' + | 'UTF16LE'; + +export type responseEncoding = ( + | UppercaseResponseEncoding + | Lowercase +) & {}; + +export interface TransitionalOptions { + silentJSONParsing?: boolean; + forcedJSONParsing?: boolean; + clarifyTimeoutError?: boolean; + legacyInterceptorReqResOrdering?: boolean; + advertiseZstdAcceptEncoding?: boolean; + validateStatusUndefinedResolves?: boolean; +} + +export interface GenericAbortSignal { + readonly aborted: boolean; + onabort?: ((...args: any) => any) | null; + addEventListener?: (...args: any) => any; + removeEventListener?: (...args: any) => any; +} + +export interface FormDataVisitorHelpers { + defaultVisitor: SerializerVisitor; + convertValue: (value: any) => any; + isVisitable: (value: any) => boolean; +} + +export interface SerializerVisitor { + ( + this: GenericFormData, + value: any, + key: string | number, + path: null | Array, + helpers: FormDataVisitorHelpers + ): boolean; +} + +export interface SerializerOptions { + visitor?: SerializerVisitor; + dots?: boolean; + metaTokens?: boolean; + indexes?: boolean | null; +} + +// tslint:disable-next-line +export interface FormSerializerOptions extends SerializerOptions {} + +export interface ParamEncoder { + (value: any, defaultEncoder: (value: any) => any): any; +} + +export interface CustomParamsSerializer { + (params: Record, options?: ParamsSerializerOptions): string; +} + +export interface ParamsSerializerOptions extends SerializerOptions { + encode?: ParamEncoder; + serialize?: CustomParamsSerializer; +} + +type MaxUploadRate = number; + +type MaxDownloadRate = number; + +type BrowserProgressEvent = any; + +export interface AxiosProgressEvent { + loaded: number; + total?: number; + progress?: number; + bytes: number; + rate?: number; + estimated?: number; + upload?: boolean; + download?: boolean; + event?: BrowserProgressEvent; + lengthComputable: boolean; +} + +type Milliseconds = number; + +type AxiosAdapterName = StringLiteralsOrString<'xhr' | 'http' | 'fetch'>; + +type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName; + +export type AddressFamily = 4 | 6 | undefined; + +export interface LookupAddressEntry { + address: string; + family?: AddressFamily; +} + +export type LookupAddress = string | LookupAddressEntry; + +export interface AxiosRequestConfig { + url?: string; + method?: StringLiteralsOrString; + baseURL?: string; + allowAbsoluteUrls?: boolean; + transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[]; + transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[]; + headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders; + params?: any; + paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer; + data?: D; + timeout?: Milliseconds; + timeoutErrorMessage?: string; + withCredentials?: boolean; + adapter?: AxiosAdapterConfig | AxiosAdapterConfig[]; + auth?: AxiosBasicCredentials; + responseType?: ResponseType; + responseEncoding?: StringLiteralsOrString; + xsrfCookieName?: string; + xsrfHeaderName?: string; + onUploadProgress?: (progressEvent: AxiosProgressEvent) => void; + onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void; + maxContentLength?: number; + validateStatus?: ((status: number) => boolean) | null; + maxBodyLength?: number; + maxRedirects?: number; + maxRate?: number | [MaxUploadRate, MaxDownloadRate]; + beforeRedirect?: ( + options: Record, + responseDetails: { + headers: Record; + statusCode: HttpStatusCode; + }, + requestDetails: { + headers: Record; + url: string; + method: string; + }, + ) => void; + socketPath?: string | null; + allowedSocketPaths?: string | string[] | null; + transport?: any; + httpAgent?: any; + httpsAgent?: any; + proxy?: AxiosProxyConfig | false; + cancelToken?: CancelToken | undefined; + decompress?: boolean; + transitional?: TransitionalOptions; + signal?: GenericAbortSignal; + insecureHTTPParser?: boolean; + env?: { + FormData?: new (...args: any[]) => object; + fetch?: (input: URL | Request | string, init?: RequestInit) => Promise; + Request?: new (input: URL | Request | string, init?: RequestInit) => Request; + Response?: new ( + body?: ArrayBuffer | ArrayBufferView | Blob | FormData | URLSearchParams | string | null, + init?: ResponseInit + ) => Response; + }; + formSerializer?: FormSerializerOptions; + family?: AddressFamily; + lookup?: + | (( + hostname: string, + options: object, + cb: ( + err: Error | null, + address: LookupAddress | LookupAddress[], + family?: AddressFamily + ) => void + ) => void) + | (( + hostname: string, + options: object + ) => Promise< + [address: LookupAddressEntry | LookupAddressEntry[], family?: AddressFamily] | LookupAddress + >); + withXSRFToken?: boolean | ((config: InternalAxiosRequestConfig) => boolean | undefined); + parseReviver?: (this: any, key: string, value: any, context?: { source?: string }) => any; + fetchOptions?: Omit | Record; + httpVersion?: 1 | 2; + http2Options?: Record & { + sessionTimeout?: number; + }; + formDataHeaderPolicy?: 'legacy' | 'content-only'; + redact?: string[]; + sensitiveHeaders?: string[]; +} + +// Alias +export type RawAxiosRequestConfig = AxiosRequestConfig; + +export interface InternalAxiosRequestConfig extends AxiosRequestConfig { + headers: AxiosRequestHeaders; +} + +export interface HeadersDefaults { + common: RawAxiosRequestHeaders; + delete: RawAxiosRequestHeaders; + get: RawAxiosRequestHeaders; + head: RawAxiosRequestHeaders; + post: RawAxiosRequestHeaders; + put: RawAxiosRequestHeaders; + patch: RawAxiosRequestHeaders; + options?: RawAxiosRequestHeaders; + purge?: RawAxiosRequestHeaders; + link?: RawAxiosRequestHeaders; + unlink?: RawAxiosRequestHeaders; + query?: RawAxiosRequestHeaders; +} + +export interface AxiosDefaults extends Omit, 'headers'> { + headers: HeadersDefaults; +} + +export interface CreateAxiosDefaults extends Omit, 'headers'> { + headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial; +} + +export interface AxiosResponse { + data: T; + status: number; + statusText: string; + headers: (H & RawAxiosResponseHeaders) | AxiosResponseHeaders; + config: InternalAxiosRequestConfig; + request?: any; +} + +export class AxiosError extends Error { + constructor( + message?: string, + code?: string, + config?: InternalAxiosRequestConfig, + request?: any, + response?: AxiosResponse + ); + + config?: InternalAxiosRequestConfig; + code?: string; + request?: any; + response?: AxiosResponse; + isAxiosError: boolean; + status?: number; + toJSON: () => object; + cause?: Error; + event?: BrowserProgressEvent; + static from( + error: Error | unknown, + code?: string, + config?: InternalAxiosRequestConfig, + request?: any, + response?: AxiosResponse, + customProps?: object + ): AxiosError; + static readonly ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS'; + static readonly ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE'; + static readonly ERR_BAD_OPTION = 'ERR_BAD_OPTION'; + static readonly ERR_NETWORK = 'ERR_NETWORK'; + static readonly ERR_DEPRECATED = 'ERR_DEPRECATED'; + static readonly ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE'; + static readonly ERR_BAD_REQUEST = 'ERR_BAD_REQUEST'; + static readonly ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT'; + static readonly ERR_INVALID_URL = 'ERR_INVALID_URL'; + static readonly ERR_CANCELED = 'ERR_CANCELED'; + static readonly ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED'; + static readonly ECONNABORTED = 'ECONNABORTED'; + static readonly ECONNREFUSED = 'ECONNREFUSED'; + static readonly ETIMEDOUT = 'ETIMEDOUT'; +} + +export class CanceledError extends AxiosError { + readonly name: 'CanceledError'; +} + +export type AxiosPromise = Promise>; + +export interface CancelStatic { + new (message?: string): Cancel; +} + +export interface Cancel { + message: string | undefined; +} + +export interface Canceler { + (message?: string, config?: AxiosRequestConfig, request?: any): void; +} + +export interface CancelTokenStatic { + new (executor: (cancel: Canceler) => void): CancelToken; + source(): CancelTokenSource; +} + +export interface CancelToken { + promise: Promise; + reason?: Cancel; + throwIfRequested(): void; +} + +export interface CancelTokenSource { + token: CancelToken; + cancel: Canceler; +} + +export interface AxiosInterceptorOptions { + synchronous?: boolean; + runWhen?: ((config: InternalAxiosRequestConfig) => boolean) | null; +} + +type AxiosInterceptorFulfilled = (value: T) => T | Promise; +type AxiosInterceptorRejected = (error: any) => any; + +type AxiosRequestInterceptorUse = ( + onFulfilled?: AxiosInterceptorFulfilled | null, + onRejected?: AxiosInterceptorRejected | null, + options?: AxiosInterceptorOptions +) => number; + +type AxiosResponseInterceptorUse = ( + onFulfilled?: AxiosInterceptorFulfilled | null, + onRejected?: AxiosInterceptorRejected | null +) => number; + +interface AxiosInterceptorHandler { + fulfilled: AxiosInterceptorFulfilled; + rejected?: AxiosInterceptorRejected; + synchronous: boolean; + runWhen?: ((config: InternalAxiosRequestConfig) => boolean) | null; +} + +export interface AxiosInterceptorManager { + use: V extends AxiosResponse ? AxiosResponseInterceptorUse : AxiosRequestInterceptorUse; + eject(id: number): void; + clear(): void; + handlers?: Array>; +} + +export class Axios { + constructor(config?: AxiosRequestConfig); + defaults: AxiosDefaults; + interceptors: { + request: AxiosInterceptorManager; + response: AxiosInterceptorManager; + }; + getUri(config?: AxiosRequestConfig): string; + request, D = any>(config: AxiosRequestConfig): Promise; + get, D = any>( + url: string, + config?: AxiosRequestConfig + ): Promise; + delete, D = any>( + url: string, + config?: AxiosRequestConfig + ): Promise; + head, D = any>( + url: string, + config?: AxiosRequestConfig + ): Promise; + options, D = any>( + url: string, + config?: AxiosRequestConfig + ): Promise; + post, D = any>( + url: string, + data?: D, + config?: AxiosRequestConfig + ): Promise; + put, D = any>( + url: string, + data?: D, + config?: AxiosRequestConfig + ): Promise; + patch, D = any>( + url: string, + data?: D, + config?: AxiosRequestConfig + ): Promise; + postForm, D = any>( + url: string, + data?: D, + config?: AxiosRequestConfig + ): Promise; + putForm, D = any>( + url: string, + data?: D, + config?: AxiosRequestConfig + ): Promise; + patchForm, D = any>( + url: string, + data?: D, + config?: AxiosRequestConfig + ): Promise; + query, D = any>( + url: string, + data?: D, + config?: AxiosRequestConfig + ): Promise; +} + +export interface AxiosInstance extends Axios { + , D = any>(config: AxiosRequestConfig): Promise; + , D = any>(url: string, config?: AxiosRequestConfig): Promise; + + create(config?: CreateAxiosDefaults): AxiosInstance; + defaults: Omit & { + headers: HeadersDefaults & { + [key: string]: AxiosHeaderValue; + }; + }; +} + +export interface GenericFormData { + append(name: string, value: any, options?: any): any; +} + +export interface GenericHTMLFormElement { + name: string; + method: string; + submit(): void; +} + +export function getAdapter( + adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined +): AxiosAdapter; + +export function toFormData( + sourceObj: object, + targetFormData?: GenericFormData, + options?: FormSerializerOptions +): GenericFormData; + +export function formToJSON(form: GenericFormData | GenericHTMLFormElement): object; + +export function isAxiosError(payload: any): payload is AxiosError; + +export function spread(callback: (...args: T[]) => R): (array: T[]) => R; + +export function isCancel(value: any): value is CanceledError; + +export function all(values: Array>): Promise; + +export function mergeConfig( + config1: AxiosRequestConfig, + config2: AxiosRequestConfig +): AxiosRequestConfig; + +export function create(config?: CreateAxiosDefaults): AxiosInstance; + +export interface AxiosStatic extends AxiosInstance { + Cancel: CancelStatic; + CancelToken: CancelTokenStatic; + Axios: typeof Axios; + AxiosError: typeof AxiosError; + HttpStatusCode: typeof HttpStatusCode; + readonly VERSION: string; + isCancel: typeof isCancel; + all: typeof all; + spread: typeof spread; + isAxiosError: typeof isAxiosError; + toFormData: typeof toFormData; + formToJSON: typeof formToJSON; + getAdapter: typeof getAdapter; + CanceledError: typeof CanceledError; + AxiosHeaders: typeof AxiosHeaders; + mergeConfig: typeof mergeConfig; +} + +declare const axios: AxiosStatic; + +export default axios; diff --git a/node_modules/axios/index.js b/node_modules/axios/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5bc03654d62e0d3d41078b7bbe7497b32470d8ac --- /dev/null +++ b/node_modules/axios/index.js @@ -0,0 +1,45 @@ +import axios from './lib/axios.js'; + +// This module is intended to unwrap Axios default export as named. +// Keep top-level export same with static properties +// so that it can keep same with es module or cjs +const { + Axios, + AxiosError, + CanceledError, + isCancel, + CancelToken, + VERSION, + all, + Cancel, + isAxiosError, + spread, + toFormData, + AxiosHeaders, + HttpStatusCode, + formToJSON, + getAdapter, + mergeConfig, + create, +} = axios; + +export { + axios as default, + create, + Axios, + AxiosError, + CanceledError, + isCancel, + CancelToken, + VERSION, + all, + Cancel, + isAxiosError, + spread, + toFormData, + AxiosHeaders, + HttpStatusCode, + formToJSON, + getAdapter, + mergeConfig, +}; diff --git a/node_modules/axios/lib/adapters/README.md b/node_modules/axios/lib/adapters/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8d9dd97db5b076c89249a52d2f38d5c7826ef565 --- /dev/null +++ b/node_modules/axios/lib/adapters/README.md @@ -0,0 +1,36 @@ +# axios // adapters + +The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received. + +## Example + +```js +var settle = require('../core/settle'); + +module.exports = function myAdapter(config) { + // At this point: + // - config has been merged with defaults + // - request transformers have already run + // - request interceptors have already run + + // Make the request using config provided + // Upon response settle the Promise + + return new Promise(function (resolve, reject) { + var response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config, + request: request, + }; + + settle(resolve, reject, response); + + // From here: + // - response transformers will run + // - response interceptors will run + }); +}; +``` diff --git a/node_modules/axios/lib/adapters/adapters.js b/node_modules/axios/lib/adapters/adapters.js new file mode 100644 index 0000000000000000000000000000000000000000..68f675f3560de1058d5b219906b1eba7aa13c091 --- /dev/null +++ b/node_modules/axios/lib/adapters/adapters.js @@ -0,0 +1,132 @@ +import utils from '../utils.js'; +import httpAdapter from './http.js'; +import xhrAdapter from './xhr.js'; +import * as fetchAdapter from './fetch.js'; +import AxiosError from '../core/AxiosError.js'; + +/** + * Known adapters mapping. + * Provides environment-specific adapters for Axios: + * - `http` for Node.js + * - `xhr` for browsers + * - `fetch` for fetch API-based requests + * + * @type {Object} + */ +const knownAdapters = { + http: httpAdapter, + xhr: xhrAdapter, + fetch: { + get: fetchAdapter.getFetch, + }, +}; + +// Assign adapter names for easier debugging and identification +utils.forEach(knownAdapters, (fn, value) => { + if (fn) { + try { + // Null-proto descriptors so a polluted Object.prototype.get cannot turn + // these data descriptors into accessor descriptors on the way in. + Object.defineProperty(fn, 'name', { __proto__: null, value }); + } catch (e) { + // eslint-disable-next-line no-empty + } + Object.defineProperty(fn, 'adapterName', { __proto__: null, value }); + } +}); + +/** + * Render a rejection reason string for unknown or unsupported adapters + * + * @param {string} reason + * @returns {string} + */ +const renderReason = (reason) => `- ${reason}`; + +/** + * Check if the adapter is resolved (function, null, or false) + * + * @param {Function|null|false} adapter + * @returns {boolean} + */ +const isResolvedHandle = (adapter) => + utils.isFunction(adapter) || adapter === null || adapter === false; + +/** + * Get the first suitable adapter from the provided list. + * Tries each adapter in order until a supported one is found. + * Throws an AxiosError if no adapter is suitable. + * + * @param {Array|string|Function} adapters - Adapter(s) by name or function. + * @param {Object} config - Axios request configuration + * @throws {AxiosError} If no suitable adapter is available + * @returns {Function} The resolved adapter function + */ +function getAdapter(adapters, config) { + adapters = utils.isArray(adapters) ? adapters : [adapters]; + + const { length } = adapters; + let nameOrAdapter; + let adapter; + + const rejectedReasons = {}; + + for (let i = 0; i < length; i++) { + nameOrAdapter = adapters[i]; + let id; + + adapter = nameOrAdapter; + + if (!isResolvedHandle(nameOrAdapter)) { + adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; + + if (adapter === undefined) { + throw new AxiosError(`Unknown adapter '${id}'`); + } + } + + if (adapter && (utils.isFunction(adapter) || (adapter = adapter.get(config)))) { + break; + } + + rejectedReasons[id || '#' + i] = adapter; + } + + if (!adapter) { + const reasons = Object.entries(rejectedReasons).map( + ([id, state]) => + `adapter ${id} ` + + (state === false ? 'is not supported by the environment' : 'is not available in the build') + ); + + let s = length + ? reasons.length > 1 + ? 'since :\n' + reasons.map(renderReason).join('\n') + : ' ' + renderReason(reasons[0]) + : 'as no adapter specified'; + + throw new AxiosError( + `There is no suitable adapter to dispatch the request ` + s, + 'ERR_NOT_SUPPORT' + ); + } + + return adapter; +} + +/** + * Exports Axios adapters and utility to resolve an adapter + */ +export default { + /** + * Resolve an adapter from a list of adapter names or functions. + * @type {Function} + */ + getAdapter, + + /** + * Exposes all known adapters + * @type {Object} + */ + adapters: knownAdapters, +}; diff --git a/node_modules/axios/lib/adapters/fetch.js b/node_modules/axios/lib/adapters/fetch.js new file mode 100644 index 0000000000000000000000000000000000000000..9b031015ac1716c4362f8016b81e26e2a60a723e --- /dev/null +++ b/node_modules/axios/lib/adapters/fetch.js @@ -0,0 +1,628 @@ +import platform from '../platform/index.js'; +import utils from '../utils.js'; +import AxiosError from '../core/AxiosError.js'; +import composeSignals from '../helpers/composeSignals.js'; +import { trackStream } from '../helpers/trackStream.js'; +import AxiosHeaders from '../core/AxiosHeaders.js'; +import { + progressEventReducer, + progressEventDecorator, + asyncDecorator, +} from '../helpers/progressEventReducer.js'; +import resolveConfig from '../helpers/resolveConfig.js'; +import settle from '../core/settle.js'; +import estimateDataURLDecodedBytes from '../helpers/estimateDataURLDecodedBytes.js'; +import { VERSION } from '../env/data.js'; +import { toByteStringHeaderObject } from '../helpers/sanitizeHeaderValue.js'; + +const DEFAULT_CHUNK_SIZE = 64 * 1024; + +const { isFunction } = utils; + +/** + * Encode a UTF-8 string to a Latin-1 byte string for use with btoa(). + * This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern. + * + * @param {string} str The string to encode + * + * @returns {string} UTF-8 bytes as a Latin-1 string + */ +const encodeUTF8 = (str) => + encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) => + String.fromCharCode(parseInt(hex, 16)) + ); + +// Node's WHATWG URL parser returns `username` and `password` percent-encoded. +// Decode before composing the `auth` option so credentials such as +// `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the +// original value for malformed input so a bad encoding never throws. +const decodeURIComponentSafe = (value) => { + if (!utils.isString(value)) { + return value; + } + + try { + return decodeURIComponent(value); + } catch (error) { + return value; + } +}; + +const test = (fn, ...args) => { + try { + return !!fn(...args); + } catch (e) { + return false; + } +}; + +const maybeWithAuthCredentials = (url) => { + const protocolIndex = url.indexOf('://'); + let urlToCheck = url; + if (protocolIndex !== -1) { + urlToCheck = urlToCheck.slice(protocolIndex + 3); + } + return urlToCheck.includes('@') || urlToCheck.includes(':'); +}; + +const factory = (env) => { + const globalObject = + utils.global !== undefined && utils.global !== null + ? utils.global + : globalThis; + const { ReadableStream, TextEncoder } = globalObject; + + env = utils.merge.call( + { + skipUndefined: true, + }, + { + Request: globalObject.Request, + Response: globalObject.Response, + }, + env + ); + + const { fetch: envFetch, Request, Response } = env; + const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function'; + const isRequestSupported = isFunction(Request); + const isResponseSupported = isFunction(Response); + + if (!isFetchSupported) { + return false; + } + + const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream); + + const encodeText = + isFetchSupported && + (typeof TextEncoder === 'function' + ? ( + (encoder) => (str) => + encoder.encode(str) + )(new TextEncoder()) + : async (str) => new Uint8Array(await new Request(str).arrayBuffer())); + + const supportsRequestStream = + isRequestSupported && + isReadableStreamSupported && + test(() => { + let duplexAccessed = false; + + const request = new Request(platform.origin, { + body: new ReadableStream(), + method: 'POST', + get duplex() { + duplexAccessed = true; + return 'half'; + }, + }); + + const hasContentType = request.headers.has('Content-Type'); + + if (request.body != null) { + request.body.cancel(); + } + + return duplexAccessed && !hasContentType; + }); + + const supportsResponseStream = + isResponseSupported && + isReadableStreamSupported && + test(() => utils.isReadableStream(new Response('').body)); + + const resolvers = { + stream: supportsResponseStream && ((res) => res.body), + }; + + isFetchSupported && + (() => { + ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach((type) => { + !resolvers[type] && + (resolvers[type] = (res, config) => { + let method = res && res[type]; + + if (method) { + return method.call(res); + } + + throw new AxiosError( + `Response type '${type}' is not supported`, + AxiosError.ERR_NOT_SUPPORT, + config + ); + }); + }); + })(); + + const getBodyLength = async (body) => { + if (body == null) { + return 0; + } + + if (utils.isBlob(body)) { + return body.size; + } + + if (utils.isSpecCompliantForm(body)) { + const _request = new Request(platform.origin, { + method: 'POST', + body, + }); + return (await _request.arrayBuffer()).byteLength; + } + + if (utils.isArrayBufferView(body) || utils.isArrayBuffer(body)) { + return body.byteLength; + } + + if (utils.isURLSearchParams(body)) { + body = body + ''; + } + + if (utils.isString(body)) { + return (await encodeText(body)).byteLength; + } + }; + + const resolveBodyLength = async (headers, body) => { + const length = utils.toFiniteNumber(headers.getContentLength()); + + return length == null ? getBodyLength(body) : length; + }; + + return async (config) => { + let { + url, + method, + data, + signal, + cancelToken, + timeout, + onDownloadProgress, + onUploadProgress, + responseType, + headers, + withCredentials = 'same-origin', + fetchOptions, + maxContentLength, + maxBodyLength, + } = resolveConfig(config); + + const hasMaxContentLength = utils.isNumber(maxContentLength) && maxContentLength > -1; + const hasMaxBodyLength = utils.isNumber(maxBodyLength) && maxBodyLength > -1; + const own = (key) => (utils.hasOwnProp(config, key) ? config[key] : undefined); + + let _fetch = envFetch || fetch; + + responseType = responseType ? (responseType + '').toLowerCase() : 'text'; + + let composedSignal = composeSignals( + [signal, cancelToken && cancelToken.toAbortSignal()], + timeout + ); + + let request = null; + + const unsubscribe = + composedSignal && + composedSignal.unsubscribe && + (() => { + composedSignal.unsubscribe(); + }); + + let requestContentLength; + + // AxiosError we raise while the request body is being streamed. Captured + // by identity so the catch block can surface it directly, regardless of + // how the runtime wraps the resulting fetch rejection (undici exposes it + // as `err.cause`; some browsers drop the original error entirely). + let pendingBodyError = null; + + const maxBodyLengthError = () => + new AxiosError( + 'Request body larger than maxBodyLength limit', + AxiosError.ERR_BAD_REQUEST, + config, + request + ); + + try { + // HTTP basic authentication + let auth = undefined; + const configAuth = own('auth'); + + if (configAuth) { + const username = utils.getSafeProp(configAuth, 'username') || ''; + const password = utils.getSafeProp(configAuth, 'password') || ''; + auth = { + username, + password + }; + } + + if (maybeWithAuthCredentials(url)) { + const parsedURL = new URL(url, platform.origin); + + if (!auth && (parsedURL.username || parsedURL.password)) { + const urlUsername = decodeURIComponentSafe(parsedURL.username); + const urlPassword = decodeURIComponentSafe(parsedURL.password); + auth = { + username: urlUsername, + password: urlPassword + }; + } + + if (parsedURL.username || parsedURL.password) { + parsedURL.username = ''; + parsedURL.password = ''; + url = parsedURL.href; + } + } + + if (auth) { + headers.delete('authorization'); + headers.set( + 'Authorization', + 'Basic ' + btoa(encodeUTF8((auth.username || '') + ':' + (auth.password || ''))) + ); + } + + // Enforce maxContentLength for data: URLs up-front so we never materialize + // an oversized payload. The HTTP adapter applies the same check (see http.js + // "if (protocol === 'data:')" branch). + if (hasMaxContentLength && typeof url === 'string' && url.startsWith('data:')) { + const estimated = estimateDataURLDecodedBytes(url); + if (estimated > maxContentLength) { + throw new AxiosError( + 'maxContentLength size of ' + maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, + config, + request + ); + } + } + + // Enforce maxBodyLength against known-size bodies before dispatch using + // the body's *actual* size — never a caller-declared Content-Length, + // which could under-report to slip an oversized body past the check. + // Unknown-size streams return undefined here and are counted per-chunk + // below as fetch consumes them. + if (hasMaxBodyLength && method !== 'get' && method !== 'head') { + const outboundLength = await getBodyLength(data); + if (typeof outboundLength === 'number' && isFinite(outboundLength)) { + requestContentLength = outboundLength; + if (outboundLength > maxBodyLength) { + throw maxBodyLengthError(); + } + } + } + + // A streamed body under maxBodyLength must be counted as fetch consumes + // it; its size is never trusted from a caller-declared Content-Length. + const mustEnforceStreamBody = + hasMaxBodyLength && (utils.isReadableStream(data) || utils.isStream(data)); + + const trackRequestStream = (stream, onProgress, flush) => + trackStream( + stream, + DEFAULT_CHUNK_SIZE, + (loadedBytes) => { + if (hasMaxBodyLength && loadedBytes > maxBodyLength) { + throw (pendingBodyError = maxBodyLengthError()); + } + onProgress && onProgress(loadedBytes); + }, + flush + ); + + if ( + supportsRequestStream && + method !== 'get' && + method !== 'head' && + (onUploadProgress || mustEnforceStreamBody) + ) { + requestContentLength = + requestContentLength == null ? await resolveBodyLength(headers, data) : requestContentLength; + + // A declared length of 0 is only trusted to skip the wrap when we are + // not enforcing a stream limit (which must not rely on that header). + if (requestContentLength !== 0 || mustEnforceStreamBody) { + let _request = new Request(url, { + method: 'POST', + body: data, + duplex: 'half', + }); + + let contentTypeHeader; + + if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) { + headers.setContentType(contentTypeHeader); + } + + if (_request.body) { + const [onProgress, flush] = + (onUploadProgress && + progressEventDecorator( + requestContentLength, + progressEventReducer(asyncDecorator(onUploadProgress)) + )) || + []; + + data = trackRequestStream(_request.body, onProgress, flush); + } + } + } else if ( + mustEnforceStreamBody && + !isRequestSupported && + isReadableStreamSupported && + method !== 'get' && + method !== 'head' + ) { + data = trackRequestStream(data); + } else if ( + mustEnforceStreamBody && + isRequestSupported && + !supportsRequestStream && + method !== 'get' && + method !== 'head' + ) { + throw new AxiosError( + 'Stream request bodies are not supported by the current fetch implementation', + AxiosError.ERR_NOT_SUPPORT, + config, + request + ); + } + + if (!utils.isString(withCredentials)) { + withCredentials = withCredentials ? 'include' : 'omit'; + } + + // Cloudflare Workers throws when credentials are defined + // see https://github.com/cloudflare/workerd/issues/902 + const isCredentialsSupported = isRequestSupported && 'credentials' in Request.prototype; + + // If data is FormData and Content-Type is multipart/form-data without boundary, + // delete it so fetch can set it correctly with the boundary + if (utils.isFormData(data)) { + const contentType = headers.getContentType(); + if ( + contentType && + /^multipart\/form-data/i.test(contentType) && + !/boundary=/i.test(contentType) + ) { + headers.delete('content-type'); + } + } + + // Set User-Agent header if not already set (fetch defaults to 'node' in Node.js) + headers.set('User-Agent', 'axios/' + VERSION, false); + + const resolvedOptions = { + ...fetchOptions, + signal: composedSignal, + method: method.toUpperCase(), + headers: toByteStringHeaderObject(headers.normalize()), + body: data, + duplex: 'half', + credentials: isCredentialsSupported ? withCredentials : undefined, + }; + + request = isRequestSupported && new Request(url, resolvedOptions); + + let response = await (isRequestSupported + ? _fetch(request, fetchOptions) + : _fetch(url, resolvedOptions)); + + const responseHeaders = AxiosHeaders.from(response.headers); + + // Cheap pre-check: if the server honestly declares a content-length that + // already exceeds the cap, reject before we start streaming. + if (hasMaxContentLength) { + const declaredLength = utils.toFiniteNumber(responseHeaders.getContentLength()); + if (declaredLength != null && declaredLength > maxContentLength) { + throw new AxiosError( + 'maxContentLength size of ' + maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, + config, + request + ); + } + } + + const isStreamResponse = + supportsResponseStream && (responseType === 'stream' || responseType === 'response'); + + if ( + supportsResponseStream && + response.body && + (onDownloadProgress || hasMaxContentLength || (isStreamResponse && unsubscribe)) + ) { + const options = {}; + + ['status', 'statusText', 'headers'].forEach((prop) => { + options[prop] = response[prop]; + }); + + const responseContentLength = utils.toFiniteNumber(responseHeaders.getContentLength()); + + const [onProgress, flush] = + (onDownloadProgress && + progressEventDecorator( + responseContentLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true) + )) || + []; + + let bytesRead = 0; + const onChunkProgress = (loadedBytes) => { + if (hasMaxContentLength) { + bytesRead = loadedBytes; + if (bytesRead > maxContentLength) { + throw new AxiosError( + 'maxContentLength size of ' + maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, + config, + request + ); + } + } + onProgress && onProgress(loadedBytes); + }; + + response = new Response( + trackStream(response.body, DEFAULT_CHUNK_SIZE, onChunkProgress, () => { + flush && flush(); + unsubscribe && unsubscribe(); + }), + options + ); + } + + responseType = responseType || 'text'; + + let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text']( + response, + config + ); + + // Fallback enforcement for environments without ReadableStream support + // (legacy runtimes). Detect materialized size from typed output; skip + // streams/Response passthrough since the user will read those themselves. + if (hasMaxContentLength && !supportsResponseStream && !isStreamResponse) { + let materializedSize; + if (responseData != null) { + if (typeof responseData.byteLength === 'number') { + materializedSize = responseData.byteLength; + } else if (typeof responseData.size === 'number') { + materializedSize = responseData.size; + } else if (typeof responseData === 'string') { + materializedSize = + typeof TextEncoder === 'function' + ? new TextEncoder().encode(responseData).byteLength + : responseData.length; + } + } + if (typeof materializedSize === 'number' && materializedSize > maxContentLength) { + throw new AxiosError( + 'maxContentLength size of ' + maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, + config, + request + ); + } + } + + !isStreamResponse && unsubscribe && unsubscribe(); + + return await new Promise((resolve, reject) => { + settle(resolve, reject, { + data: responseData, + headers: AxiosHeaders.from(response.headers), + status: response.status, + statusText: response.statusText, + config, + request, + }); + }); + } catch (err) { + unsubscribe && unsubscribe(); + + // Safari can surface fetch aborts as a DOMException-like object whose + // branded getters throw. Prefer our composed signal reason before reading + // the caught error, preserving timeout vs cancellation semantics. + if (composedSignal && composedSignal.aborted && composedSignal.reason instanceof AxiosError) { + const canceledError = composedSignal.reason; + canceledError.config = config; + request && (canceledError.request = request); + err !== canceledError && (canceledError.cause = err); + throw canceledError; + } + + // Surface a maxBodyLength violation we raised while the request body was + // being streamed. Matching by identity (rather than reading + // `err.cause.isAxiosError`) keeps the error deterministic across runtimes + // and avoids both prototype-pollution reads and mis-attributing a foreign + // AxiosError that merely happened to land in `err.cause`. + if (pendingBodyError) { + request && !pendingBodyError.request && (pendingBodyError.request = request); + throw pendingBodyError; + } + + // Re-throw AxiosErrors we raised synchronously (data: URL / content-length + // pre-checks, response size enforcement) without re-wrapping them. + if (err instanceof AxiosError) { + request && !err.request && (err.request = request); + throw err; + } + + if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) { + throw Object.assign( + new AxiosError( + 'Network Error', + AxiosError.ERR_NETWORK, + config, + request, + err && err.response + ), + { + cause: err.cause || err, + } + ); + } + + throw AxiosError.from(err, err && err.code, config, request, err && err.response); + } + }; +}; + +const seedCache = new Map(); + +export const getFetch = (config) => { + let env = (config && config.env) || {}; + const { fetch, Request, Response } = env; + const seeds = [Request, Response, fetch]; + + let len = seeds.length, + i = len, + seed, + target, + map = seedCache; + + while (i--) { + seed = seeds[i]; + target = map.get(seed); + + target === undefined && map.set(seed, (target = i ? new Map() : factory(env))); + + map = target; + } + + return target; +}; + +const adapter = getFetch(); + +export default adapter; diff --git a/node_modules/axios/lib/adapters/http.js b/node_modules/axios/lib/adapters/http.js new file mode 100644 index 0000000000000000000000000000000000000000..b95795b3b92d3664ab8f6e7a3b427ba78e5518aa --- /dev/null +++ b/node_modules/axios/lib/adapters/http.js @@ -0,0 +1,1345 @@ +import utils from '../utils.js'; +import settle from '../core/settle.js'; +import buildFullPath from '../core/buildFullPath.js'; +import buildURL from '../helpers/buildURL.js'; +import { getProxyForUrl } from 'proxy-from-env'; +import HttpsProxyAgent from 'https-proxy-agent'; +import http from 'http'; +import https from 'https'; +import http2 from 'http2'; +import util from 'util'; +import { resolve as resolvePath } from 'path'; +import followRedirects from 'follow-redirects'; +import zlib from 'zlib'; +import { VERSION } from '../env/data.js'; +import transitionalDefaults from '../defaults/transitional.js'; +import AxiosError from '../core/AxiosError.js'; +import CanceledError from '../cancel/CanceledError.js'; +import platform from '../platform/index.js'; +import fromDataURI from '../helpers/fromDataURI.js'; +import stream from 'stream'; +import AxiosHeaders from '../core/AxiosHeaders.js'; +import AxiosTransformStream from '../helpers/AxiosTransformStream.js'; +import { EventEmitter } from 'events'; +import formDataToStream from '../helpers/formDataToStream.js'; +import readBlob from '../helpers/readBlob.js'; +import ZlibHeaderTransformStream from '../helpers/ZlibHeaderTransformStream.js'; +import Http2Sessions from '../helpers/Http2Sessions.js'; +import callbackify from '../helpers/callbackify.js'; +import shouldBypassProxy from '../helpers/shouldBypassProxy.js'; +import { toByteStringHeaderObject } from '../helpers/sanitizeHeaderValue.js'; +import { + progressEventReducer, + progressEventDecorator, + asyncDecorator, +} from '../helpers/progressEventReducer.js'; +import estimateDataURLDecodedBytes from '../helpers/estimateDataURLDecodedBytes.js'; + +const zlibOptions = { + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH, +}; + +const brotliOptions = { + flush: zlib.constants.BROTLI_OPERATION_FLUSH, + finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH, +}; + +const zstdOptions = { + flush: zlib.constants.ZSTD_e_flush, + finishFlush: zlib.constants.ZSTD_e_flush, +}; + +const isBrotliSupported = utils.isFunction(zlib.createBrotliDecompress); +const isZstdSupported = utils.isFunction(zlib.createZstdDecompress); +const ACCEPT_ENCODING = 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''); +const ACCEPT_ENCODING_WITH_ZSTD = ACCEPT_ENCODING + (isZstdSupported ? ', zstd' : ''); + +const { http: httpFollow, https: httpsFollow } = followRedirects; + +const isHttps = /https:?/; +const FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length']; + +function setFormDataHeaders(headers, formHeaders, policy) { + if (policy !== 'content-only') { + headers.set(formHeaders); + return; + } + + Object.entries(formHeaders).forEach(([key, val]) => { + if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) { + headers.set(key, val); + } + }); +} + +// Symbols used to bind a single 'error' listener to a pooled socket and track +// the request currently owning that socket across keep-alive reuse (issue #10780). +const kAxiosSocketListener = Symbol('axios.http.socketListener'); +const kAxiosCurrentReq = Symbol('axios.http.currentReq'); + +// Tags HttpsProxyAgent instances installed by setProxy() so the redirect path +// can strip them without clobbering a user-supplied agent that happens to be +// an HttpsProxyAgent. +const kAxiosInstalledTunnel = Symbol('axios.http.installedTunnel'); + +// Cache of CONNECT-tunneling agents keyed by proxy config so repeat requests +// through the same proxy reuse a single agent (and its socket pool). The +// keyspace is bounded by the set of distinct proxy configs the process uses, +// so unbounded growth is not a concern in practice. +const tunnelingAgentCache = new Map(); +const tunnelingAgentCacheUser = new WeakMap(); + +function getTunnelingAgent(agentOptions, userHttpsAgent) { + const key = + agentOptions.protocol + + '//' + + agentOptions.hostname + + ':' + + (agentOptions.port || '') + + '#' + + (agentOptions.auth || ''); + const cache = userHttpsAgent + ? (tunnelingAgentCacheUser.get(userHttpsAgent) || + tunnelingAgentCacheUser.set(userHttpsAgent, new Map()).get(userHttpsAgent)) + : tunnelingAgentCache; + let agent = cache.get(key); + if (agent) return agent; + // Forward the user's TLS options (custom CA, rejectUnauthorized, client cert, + // etc.) into the tunneling agent so they apply to the origin TLS upgrade + // performed after CONNECT. Our proxy fields take precedence on conflict. + const merged = userHttpsAgent && userHttpsAgent.options + ? { ...userHttpsAgent.options, ...agentOptions } + : agentOptions; + agent = new HttpsProxyAgent(merged); + if (userHttpsAgent && userHttpsAgent.options) { + const originTLSOptions = { ...userHttpsAgent.options }; + const callback = agent.callback; + agent.callback = function axiosTunnelingAgentCallback(req, opts) { + // HttpsProxyAgent v5 reads callback opts for the post-CONNECT origin TLS upgrade. + return callback.call(this, req, { ...originTLSOptions, ...opts }); + }; + } + agent[kAxiosInstalledTunnel] = true; + cache.set(key, agent); + return agent; +} + +const supportedProtocols = platform.protocols.map((protocol) => { + return protocol + ':'; +}); + +// Node's WHATWG URL parser returns `username` and `password` percent-encoded. +// Decode before composing the `auth` option so credentials such as +// `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the +// original value for malformed input so a bad encoding never throws. +const decodeURIComponentSafe = (value) => { + if (!utils.isString(value)) { + return value; + } + + try { + return decodeURIComponent(value); + } catch (error) { + return value; + } +}; + +const flushOnFinish = (stream, [throttled, flush]) => { + stream.on('end', flush).on('error', flush); + + return throttled; +}; + +const http2Sessions = new Http2Sessions(); + +/** + * If the proxy, auth, sensitive header, or config beforeRedirects functions are defined, + * call them with the options object. + * + * @param {Object} options - The options object that was passed to the request. + * + * @returns {Object} + */ +function dispatchBeforeRedirect(options, responseDetails, requestDetails) { + if (options.beforeRedirects.proxy) { + options.beforeRedirects.proxy(options); + } + if (options.beforeRedirects.auth) { + options.beforeRedirects.auth(options); + } + if (options.beforeRedirects.sensitiveHeaders) { + options.beforeRedirects.sensitiveHeaders(options, requestDetails); + } + if (options.beforeRedirects.config) { + options.beforeRedirects.config(options, responseDetails, requestDetails); + } +} + +function stripMatchingHeaders(headers, sensitiveSet) { + if (!headers) { + return; + } + + Object.keys(headers).forEach((header) => { + if (sensitiveSet.has(header.toLowerCase())) { + delete headers[header]; + } + }); +} + +function isSameOriginRedirect(redirectOptions, requestDetails) { + if (!requestDetails) { + return false; + } + + try { + return new URL(requestDetails.url).origin === new URL(redirectOptions.href).origin; + } catch (e) { + // If origin comparison fails, treat the redirect as unsafe. + return false; + } +} + +/** + * If the proxy or config afterRedirects functions are defined, call them with the options + * + * @param {http.ClientRequestArgs} options + * @param {AxiosProxyConfig} configProxy configuration from Axios options object + * @param {string} location + * + * @returns {http.ClientRequestArgs} + */ +function setProxy(options, configProxy, location, isRedirect, configHttpsAgent) { + let proxy = configProxy; + if (!proxy && proxy !== false) { + const proxyUrl = getProxyForUrl(location); + if (proxyUrl) { + if (!shouldBypassProxy(location)) { + proxy = new URL(proxyUrl); + } + } + } + // On redirect re-invocation, strip any stale Proxy-Authorization header carried + // over from the prior request (e.g. new target no longer uses a proxy, or uses + // a different proxy). Skip on the initial request so user-supplied headers are + // preserved. Header names are case-insensitive, so remove every case variant. + if (isRedirect && options.headers) { + for (const name of Object.keys(options.headers)) { + if (name.toLowerCase() === 'proxy-authorization') { + delete options.headers[name]; + } + } + } + // Strip any tunneling agent we installed for the previous hop so a redirect + // that drops the proxy or crosses an HTTPS↔HTTP boundary doesn't reuse a + // stale one. Match on our Symbol marker so a user-supplied HttpsProxyAgent + // (which won't carry the marker) is left alone. + if (isRedirect && options.agent && options.agent[kAxiosInstalledTunnel]) { + options.agent = undefined; + } + if (proxy) { + // Read proxy fields without traversing the prototype chain. URL instances expose + // username/password/hostname/host/port/protocol via getters on URL.prototype (so + // direct reads are shielded), but plain object proxies — and the `auth` field + // (which URL does not expose) — must be guarded so a polluted Object.prototype + // (e.g. Object.prototype.auth = { username, password }) cannot inject + // attacker-controlled credentials into the Proxy-Authorization header or + // redirect proxying to an attacker-controlled host. + const isProxyURL = proxy instanceof URL; + const readProxyField = (key) => + isProxyURL || utils.hasOwnProp(proxy, key) ? proxy[key] : undefined; + + const proxyUsername = readProxyField('username'); + const proxyPassword = readProxyField('password'); + let proxyAuth = utils.hasOwnProp(proxy, 'auth') ? proxy.auth : undefined; + + // Basic proxy authorization + if (proxyUsername) { + proxyAuth = (proxyUsername || '') + ':' + (proxyPassword || ''); + } + + if (proxyAuth) { + // Support proxy auth object form. Read sub-fields via own-prop checks so a + // plain object inheriting from polluted Object.prototype cannot leak creds. + const authIsObject = typeof proxyAuth === 'object'; + const authUsername = + authIsObject && utils.hasOwnProp(proxyAuth, 'username') ? proxyAuth.username : undefined; + const authPassword = + authIsObject && utils.hasOwnProp(proxyAuth, 'password') ? proxyAuth.password : undefined; + const validProxyAuth = Boolean(authUsername || authPassword); + + if (validProxyAuth) { + proxyAuth = (authUsername || '') + ':' + (authPassword || ''); + } else if (authIsObject) { + throw new AxiosError('Invalid proxy authorization', AxiosError.ERR_BAD_OPTION, { proxy }); + } + } + + const targetIsHttps = isHttps.test(options.protocol); + + if (targetIsHttps) { + // CONNECT-tunneling path for HTTPS targets. Preserves end-to-end TLS to + // the origin so the proxy cannot inspect the URL, headers, or body — the + // behavior already promised by THREATMODEL.md (T-R9). HttpsProxyAgent + // sends Proxy-Authorization on the CONNECT request only, never on the + // wrapped TLS request, which is why we don't stamp it onto + // options.headers here. If the user already supplied an HttpsProxyAgent, + // they own tunneling end-to-end and we leave them alone; otherwise we + // install our own tunneling agent and forward their TLS options (if any) + // so a custom httpsAgent for cert pinning / rejectUnauthorized still + // applies to the origin TLS upgrade. + if (!(configHttpsAgent instanceof HttpsProxyAgent)) { + const proxyHost = readProxyField('hostname') || readProxyField('host'); + const proxyPort = readProxyField('port'); + const rawProxyProtocol = readProxyField('protocol'); + const normalizedProtocol = rawProxyProtocol + ? rawProxyProtocol.includes(':') + ? rawProxyProtocol + : `${rawProxyProtocol}:` + : 'http:'; + // Bracket IPv6 literals for URL parsing; URL.hostname strips the + // brackets again on read so the agent receives the raw form. + const proxyHostForURL = + proxyHost && proxyHost.includes(':') && !proxyHost.startsWith('[') + ? `[${proxyHost}]` + : proxyHost; + const proxyURL = new URL( + `${normalizedProtocol}//${proxyHostForURL}${proxyPort ? ':' + proxyPort : ''}` + ); + const agentOptions = { + protocol: proxyURL.protocol, + hostname: proxyURL.hostname.replace(/^\[|\]$/g, ''), + port: proxyURL.port, + auth: proxyAuth && typeof proxyAuth === 'string' ? proxyAuth : undefined, + }; + if (proxyURL.protocol === 'https:') { + agentOptions.ALPNProtocols = ['http/1.1']; + } + const tunnelingAgent = getTunnelingAgent(agentOptions, configHttpsAgent); + // Set both: `options.agent` is consumed by the native https.request path + // (maxRedirects === 0); `options.agents.https` is consumed by + // follow-redirects, which ignores `options.agent` when `options.agents` + // is present. + options.agent = tunnelingAgent; + if (options.agents) { + options.agents.https = tunnelingAgent; + } + } + } else { + // Forward-proxy mode for plaintext HTTP targets. The request line carries + // the absolute URL and the proxy sees everything — acceptable for plain + // HTTP since the wire was already plaintext. + if (proxyAuth) { + const base64 = Buffer.from(proxyAuth, 'utf8').toString('base64'); + options.headers['Proxy-Authorization'] = 'Basic ' + base64; + } + + // Preserve a user-supplied Host header (case-insensitive) so callers can override + // the value forwarded to the proxy; otherwise default to the request URL's host. + let hasUserHostHeader = false; + for (const name of Object.keys(options.headers)) { + if (name.toLowerCase() === 'host') { + hasUserHostHeader = true; + break; + } + } + if (!hasUserHostHeader) { + options.headers.host = options.hostname + (options.port ? ':' + options.port : ''); + } + const proxyHost = readProxyField('hostname') || readProxyField('host'); + options.hostname = proxyHost; + // Replace 'host' since options is not a URL object + options.host = proxyHost; + options.port = readProxyField('port'); + options.path = location; + const proxyProtocol = readProxyField('protocol'); + if (proxyProtocol) { + options.protocol = proxyProtocol.includes(':') ? proxyProtocol : `${proxyProtocol}:`; + } + } + } + + options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) { + // Configure proxy for redirected request, passing the original config proxy to apply + // the exact same logic as if the redirected request was performed by axios directly. + setProxy(redirectOptions, configProxy, redirectOptions.href, true, configHttpsAgent); + }; +} + +const isHttpAdapterSupported = + typeof process !== 'undefined' && utils.kindOf(process) === 'process'; + +// temporary hotfix + +const wrapAsync = (asyncExecutor) => { + return new Promise((resolve, reject) => { + let onDone; + let isDone; + + const done = (value, isRejected) => { + if (isDone) return; + isDone = true; + onDone && onDone(value, isRejected); + }; + + const _resolve = (value) => { + done(value); + resolve(value); + }; + + const _reject = (reason) => { + done(reason, true); + reject(reason); + }; + + asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject); + }); +}; + +const resolveFamily = ({ address, family }) => { + if (!utils.isString(address)) { + throw TypeError('address must be a string'); + } + return { + address, + family: family || (address.indexOf('.') < 0 ? 6 : 4), + }; +}; + +const buildAddressEntry = (address, family) => + resolveFamily(utils.isObject(address) ? address : { address, family }); + +const http2Transport = { + request(options, cb) { + const authority = + options.protocol + + '//' + + options.hostname + + ':' + + (options.port || (options.protocol === 'https:' ? 443 : 80)); + + const { http2Options, headers } = options; + + const session = http2Sessions.getSession(authority, http2Options); + + const { HTTP2_HEADER_SCHEME, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS } = + http2.constants; + + const http2Headers = { + [HTTP2_HEADER_SCHEME]: options.protocol.replace(':', ''), + [HTTP2_HEADER_METHOD]: options.method, + [HTTP2_HEADER_PATH]: options.path, + }; + + utils.forEach(headers, (header, name) => { + name.charAt(0) !== ':' && (http2Headers[name] = header); + }); + + const req = session.request(http2Headers); + + req.once('response', (responseHeaders) => { + const response = req; //duplex + + responseHeaders = Object.assign({}, responseHeaders); + + const status = responseHeaders[HTTP2_HEADER_STATUS]; + + delete responseHeaders[HTTP2_HEADER_STATUS]; + + response.headers = responseHeaders; + + response.statusCode = +status; + + cb(response); + }); + + return req; + }, +}; + +/*eslint consistent-return:0*/ +export default isHttpAdapterSupported && + function httpAdapter(config) { + return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) { + // Read config pollution-safely: own properties and members inherited from + // a non-Object.prototype source (e.g. an Object.create(defaults) template) + // are honored, but values injected onto a polluted Object.prototype are + // ignored. All behavior-affecting reads in this adapter go through own() + // so the protection boundary stays consistent. + const own = (key) => utils.getSafeProp(config, key); + const transitional = own('transitional') || transitionalDefaults; + let data = own('data'); + let lookup = own('lookup'); + let family = own('family'); + let httpVersion = own('httpVersion'); + if (httpVersion === undefined) httpVersion = 1; + let http2Options = own('http2Options'); + const responseType = own('responseType'); + const responseEncoding = own('responseEncoding'); + const httpAgent = own('httpAgent'); + const httpsAgent = own('httpsAgent'); + const method = own('method').toUpperCase(); + const maxRedirects = own('maxRedirects'); + const maxBodyLength = own('maxBodyLength'); + const maxContentLength = own('maxContentLength'); + const decompress = own('decompress'); + let isDone; + let rejected = false; + let req; + let connectPhaseTimer; + + httpVersion = +httpVersion; + + if (Number.isNaN(httpVersion)) { + throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`); + } + + if (httpVersion !== 1 && httpVersion !== 2) { + throw TypeError(`Unsupported protocol version '${httpVersion}'`); + } + + const isHttp2 = httpVersion === 2; + + if (lookup) { + const _lookup = callbackify(lookup, (value) => (utils.isArray(value) ? value : [value])); + // hotfix to support opt.all option which is required for node 20.x + lookup = (hostname, opt, cb) => { + _lookup(hostname, opt, (err, arg0, arg1) => { + if (err) { + return cb(err); + } + + const addresses = utils.isArray(arg0) + ? arg0.map((addr) => buildAddressEntry(addr)) + : [buildAddressEntry(arg0, arg1)]; + + opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); + }); + }; + } + + const abortEmitter = new EventEmitter(); + + function abort(reason) { + try { + abortEmitter.emit( + 'abort', + !reason || reason.type ? new CanceledError(null, config, req) : reason + ); + } catch (err) { + // ignore emit errors + } + } + + function clearConnectPhaseTimer() { + if (connectPhaseTimer) { + clearTimeout(connectPhaseTimer); + connectPhaseTimer = null; + } + } + + function createTimeoutError() { + const configTimeout = own('timeout'); + let timeoutErrorMessage = configTimeout + ? 'timeout of ' + configTimeout + 'ms exceeded' + : 'timeout exceeded'; + const configTimeoutErrorMessage = own('timeoutErrorMessage'); + if (configTimeoutErrorMessage) { + timeoutErrorMessage = configTimeoutErrorMessage; + } + return new AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + req + ); + } + + abortEmitter.once('abort', reject); + + const onFinished = () => { + clearConnectPhaseTimer(); + + if (config.cancelToken) { + config.cancelToken.unsubscribe(abort); + } + + if (config.signal) { + config.signal.removeEventListener('abort', abort); + } + + abortEmitter.removeAllListeners(); + }; + + if (config.cancelToken || config.signal) { + config.cancelToken && config.cancelToken.subscribe(abort); + if (config.signal) { + config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort); + } + } + + onDone((response, isRejected) => { + isDone = true; + clearConnectPhaseTimer(); + + if (isRejected) { + rejected = true; + onFinished(); + return; + } + + const { data } = response; + + if (data instanceof stream.Readable || data instanceof stream.Duplex) { + const offListeners = stream.finished(data, () => { + offListeners(); + onFinished(); + }); + } else { + onFinished(); + } + }); + + // Parse url + const fullPath = buildFullPath(own('baseURL'), own('url'), own('allowAbsoluteUrls'), config); + const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : undefined); + const protocol = parsed.protocol || supportedProtocols[0]; + + if (protocol === 'data:') { + // Apply the same semantics as HTTP: only enforce if a finite, non-negative cap is set. + if (maxContentLength > -1) { + // Use the exact string passed to fromDataURI (the configured url); fall back to fullPath if needed. + const dataUrl = String(own('url') || fullPath || ''); + const estimated = estimateDataURLDecodedBytes(dataUrl); + + if (estimated > maxContentLength) { + return reject( + new AxiosError( + 'maxContentLength size of ' + maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, + config + ) + ); + } + } + + let convertedData; + + if (method !== 'GET') { + return settle(resolve, reject, { + status: 405, + statusText: 'method not allowed', + headers: {}, + config, + }); + } + + try { + convertedData = fromDataURI(own('url'), responseType === 'blob', { + Blob: config.env && config.env.Blob, + }); + } catch (err) { + throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config); + } + + if (responseType === 'text') { + convertedData = convertedData.toString(responseEncoding); + + if (!responseEncoding || responseEncoding === 'utf8') { + convertedData = utils.stripBOM(convertedData); + } + } else if (responseType === 'stream') { + convertedData = stream.Readable.from(convertedData); + } + + return settle(resolve, reject, { + data: convertedData, + status: 200, + statusText: 'OK', + headers: new AxiosHeaders(), + config, + }); + } + + if (supportedProtocols.indexOf(protocol) === -1) { + return reject( + new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_BAD_REQUEST, config) + ); + } + + const headers = AxiosHeaders.from(config.headers).normalize(); + + // Set User-Agent (required by some servers) + // See https://github.com/axios/axios/issues/69 + // User-Agent is specified; handle case where no UA header is desired + // Only set header if it hasn't been set in config + headers.set('User-Agent', 'axios/' + VERSION, false); + + const { onUploadProgress, onDownloadProgress } = config; + const maxRate = config.maxRate; + let maxUploadRate = undefined; + let maxDownloadRate = undefined; + + // support for spec compliant FormData objects + if (utils.isSpecCompliantForm(data)) { + const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i); + + data = formDataToStream( + data, + (formHeaders) => { + headers.set(formHeaders); + }, + { + tag: `axios-${VERSION}-boundary`, + boundary: (userBoundary && userBoundary[1]) || undefined, + } + ); + // support for https://www.npmjs.com/package/form-data api + } else if ( + utils.isFormData(data) && + utils.isFunction(data.getHeaders) && + data.getHeaders !== Object.prototype.getHeaders + ) { + setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy')); + + if (!headers.hasContentLength()) { + try { + const knownLength = await util.promisify(data.getLength).call(data); + Number.isFinite(knownLength) && + knownLength >= 0 && + headers.setContentLength(knownLength); + /*eslint no-empty:0*/ + } catch (e) {} + } + } else if (utils.isBlob(data) || utils.isFile(data)) { + data.size && headers.setContentType(data.type || 'application/octet-stream'); + headers.setContentLength(data.size || 0); + data = stream.Readable.from(readBlob(data)); + } else if (data && !utils.isStream(data)) { + if (Buffer.isBuffer(data)) { + // Nothing to do... + } else if (utils.isArrayBuffer(data)) { + data = Buffer.from(new Uint8Array(data)); + } else if (utils.isString(data)) { + data = Buffer.from(data, 'utf-8'); + } else { + return reject( + new AxiosError( + 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', + AxiosError.ERR_BAD_REQUEST, + config + ) + ); + } + + // Add Content-Length header if data exists + headers.setContentLength(data.length, false); + + if (maxBodyLength > -1 && data.length > maxBodyLength) { + return reject( + new AxiosError( + 'Request body larger than maxBodyLength limit', + AxiosError.ERR_BAD_REQUEST, + config + ) + ); + } + } + + const contentLength = utils.toFiniteNumber(headers.getContentLength()); + + if (utils.isArray(maxRate)) { + maxUploadRate = maxRate[0]; + maxDownloadRate = maxRate[1]; + } else { + maxUploadRate = maxDownloadRate = maxRate; + } + + if (data && (onUploadProgress || maxUploadRate)) { + if (!utils.isStream(data)) { + data = stream.Readable.from(data, { objectMode: false }); + } + + data = stream.pipeline( + [ + data, + new AxiosTransformStream({ + maxRate: utils.toFiniteNumber(maxUploadRate), + }), + ], + utils.noop + ); + + onUploadProgress && + data.on( + 'progress', + flushOnFinish( + data, + progressEventDecorator( + contentLength, + progressEventReducer(asyncDecorator(onUploadProgress), false, 3) + ) + ) + ); + } + + // HTTP basic authentication + let auth = undefined; + const configAuth = own('auth'); + if (configAuth) { + const username = utils.getSafeProp(configAuth, 'username') || ''; + const password = utils.getSafeProp(configAuth, 'password') || ''; + auth = username + ':' + password; + } + + if (!auth && (parsed.username || parsed.password)) { + const urlUsername = decodeURIComponentSafe(parsed.username); + const urlPassword = decodeURIComponentSafe(parsed.password); + auth = urlUsername + ':' + urlPassword; + } + + auth && headers.delete('authorization'); + + let path; + + try { + path = buildURL( + parsed.pathname + parsed.search, + own('params'), + own('paramsSerializer') + ).replace(/^\?/, ''); + } catch (err) { + const customErr = new Error(err.message); + customErr.config = config; + customErr.url = own('url'); + customErr.exists = true; + return reject(customErr); + } + + headers.set( + 'Accept-Encoding', + utils.hasOwnProp(transitional, 'advertiseZstdAcceptEncoding') && + transitional.advertiseZstdAcceptEncoding === true ? ACCEPT_ENCODING_WITH_ZSTD : ACCEPT_ENCODING, + false + ); + + // Null-prototype to block prototype pollution gadgets on properties read + // directly by Node's http.request (e.g. insecureHTTPParser, lookup). + const options = Object.assign(Object.create(null), { + path, + method: method, + headers: toByteStringHeaderObject(headers), + agents: { http: httpAgent, https: httpsAgent }, + auth, + protocol, + family, + beforeRedirect: dispatchBeforeRedirect, + beforeRedirects: Object.create(null), + http2Options, + }); + + // cacheable-lookup integration hotfix + !utils.isUndefined(lookup) && (options.lookup = lookup); + + const socketPath = own('socketPath'); + if (socketPath) { + if (typeof socketPath !== 'string') { + return reject( + new AxiosError('socketPath must be a string', AxiosError.ERR_BAD_OPTION_VALUE, config) + ); + } + + const allowedSocketPaths = own('allowedSocketPaths'); + if (allowedSocketPaths != null) { + const allowed = Array.isArray(allowedSocketPaths) + ? allowedSocketPaths + : [allowedSocketPaths]; + + const resolvedSocket = resolvePath(socketPath); + const isAllowed = allowed.some( + (entry) => typeof entry === 'string' && resolvePath(entry) === resolvedSocket + ); + + if (!isAllowed) { + return reject( + new AxiosError( + `socketPath "${socketPath}" is not permitted by allowedSocketPaths`, + AxiosError.ERR_BAD_OPTION_VALUE, + config + ) + ); + } + } + + options.socketPath = socketPath; + } else { + options.hostname = parsed.hostname.startsWith('[') + ? parsed.hostname.slice(1, -1) + : parsed.hostname; + options.port = parsed.port; + setProxy( + options, + own('proxy'), + protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path, + false, + httpsAgent + ); + } + let transport; + let isNativeTransport = false; + // True only for the follow-redirects transport, which applies + // options.maxBodyLength itself. Every other transport (http2, native + // http/https, a user-supplied custom transport) needs the explicit + // byte-counting pipeline below to enforce maxBodyLength on streamed uploads. + let transportEnforcesMaxBodyLength = false; + const isHttpsRequest = isHttps.test(options.protocol); + // Don't clobber a CONNECT-tunneling agent installed by setProxy() for an + // HTTPS target. + if (options.agent == null) { + options.agent = isHttpsRequest ? httpsAgent : httpAgent; + } + + if (isHttp2) { + transport = http2Transport; + } else { + const configTransport = own('transport'); + if (configTransport) { + transport = configTransport; + } else if (maxRedirects === 0) { + transport = isHttpsRequest ? https : http; + isNativeTransport = true; + } else { + transportEnforcesMaxBodyLength = true; + options.sensitiveHeaders = []; + if (maxRedirects) { + options.maxRedirects = maxRedirects; + } + const configBeforeRedirect = own('beforeRedirect'); + if (configBeforeRedirect) { + options.beforeRedirects.config = configBeforeRedirect; + } + if (auth) { + // Restore HTTP Basic credentials on same-origin redirects only. + // follow-redirects >= 1.15.8 strips Authorization on every redirect (see #6929); + // cross-origin stripping is the documented mitigation for T-R2 in THREATMODEL.md + // and is preserved by deliberately not restoring on origin change. + const requestOrigin = parsed.origin; + const authToRestore = auth; + options.beforeRedirects.auth = function beforeRedirectAuth(redirectOptions) { + try { + if (new URL(redirectOptions.href).origin === requestOrigin) { + redirectOptions.auth = authToRestore; + } + } catch (e) { + // ignore malformed URL: leaving auth stripped is fail-safe + } + }; + } + const sensitiveHeaders = own('sensitiveHeaders'); + if (sensitiveHeaders != null) { + if (!utils.isArray(sensitiveHeaders)) { + return reject( + new AxiosError( + 'sensitiveHeaders must be an array of strings', + AxiosError.ERR_BAD_OPTION_VALUE, + config + ) + ); + } + + const sensitiveSet = new Set(); + for (const header of sensitiveHeaders) { + if (!utils.isString(header)) { + return reject( + new AxiosError( + 'sensitiveHeaders must be an array of strings', + AxiosError.ERR_BAD_OPTION_VALUE, + config + ) + ); + } + + sensitiveSet.add(header.toLowerCase()); + } + + if (sensitiveSet.size) { + options.sensitiveHeaders = Array.from(sensitiveSet); + options.beforeRedirects.sensitiveHeaders = function beforeRedirectSensitiveHeaders( + redirectOptions, + requestDetails + ) { + if (!isSameOriginRedirect(redirectOptions, requestDetails)) { + stripMatchingHeaders(redirectOptions.headers, sensitiveSet); + } + }; + } + } + transport = isHttpsRequest ? httpsFollow : httpFollow; + } + } + + if (maxBodyLength > -1) { + options.maxBodyLength = maxBodyLength; + } else { + // follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited + options.maxBodyLength = Infinity; + } + + // Always set an explicit own value so a polluted + // Object.prototype.insecureHTTPParser cannot enable the lenient parser + // through Node's internal options copy + options.insecureHTTPParser = Boolean(own('insecureHTTPParser')); + + // Create the request + req = transport.request(options, function handleResponse(res) { + clearConnectPhaseTimer(); + + if (req.destroyed) return; + + const streams = [res]; + + const responseLength = utils.toFiniteNumber(res.headers['content-length']); + + if (onDownloadProgress || maxDownloadRate) { + const transformStream = new AxiosTransformStream({ + maxRate: utils.toFiniteNumber(maxDownloadRate), + }); + + onDownloadProgress && + transformStream.on( + 'progress', + flushOnFinish( + transformStream, + progressEventDecorator( + responseLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true, 3) + ) + ) + ); + + streams.push(transformStream); + } + + // decompress the response body transparently if required + let responseStream = res; + + // return the last request in case of redirects + const lastRequest = res.req || req; + + // if decompress disabled we should not decompress + if (decompress !== false && res.headers['content-encoding']) { + // if no content, but headers still say that it is encoded, + // remove the header not confuse downstream operations + if (method === 'HEAD' || res.statusCode === 204) { + delete res.headers['content-encoding']; + } + + switch ((res.headers['content-encoding'] || '').toLowerCase()) { + /*eslint default-case:0*/ + case 'gzip': + case 'x-gzip': + case 'compress': + case 'x-compress': + // add the unzipper to the body stream processing pipeline + streams.push(zlib.createUnzip(zlibOptions)); + + // remove the content-encoding in order to not confuse downstream operations + delete res.headers['content-encoding']; + break; + case 'deflate': + streams.push(new ZlibHeaderTransformStream()); + + // add the unzipper to the body stream processing pipeline + streams.push(zlib.createUnzip(zlibOptions)); + + // remove the content-encoding in order to not confuse downstream operations + delete res.headers['content-encoding']; + break; + case 'br': + if (isBrotliSupported) { + streams.push(zlib.createBrotliDecompress(brotliOptions)); + delete res.headers['content-encoding']; + } + break; + case 'zstd': + if (isZstdSupported) { + streams.push(zlib.createZstdDecompress(zstdOptions)); + delete res.headers['content-encoding']; + } + break; + } + } + + responseStream = streams.length > 1 ? stream.pipeline(streams, utils.noop) : streams[0]; + + const response = { + status: res.statusCode, + statusText: res.statusMessage, + headers: new AxiosHeaders(res.headers), + config, + request: lastRequest, + }; + + if (responseType === 'stream') { + // Enforce maxContentLength on streamed responses; previously this + // was applied only to buffered responses. + if (maxContentLength > -1) { + const limit = maxContentLength; + const source = responseStream; + async function* enforceMaxContentLength() { + let totalResponseBytes = 0; + for await (const chunk of source) { + totalResponseBytes += chunk.length; + if (totalResponseBytes > limit) { + throw new AxiosError( + 'maxContentLength size of ' + limit + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, + config, + lastRequest + ); + } + yield chunk; + } + } + responseStream = stream.Readable.from(enforceMaxContentLength(), { + objectMode: false, + }); + } + response.data = responseStream; + settle(resolve, reject, response); + } else { + const responseBuffer = []; + let totalResponseBytes = 0; + + responseStream.on('data', function handleStreamData(chunk) { + responseBuffer.push(chunk); + totalResponseBytes += chunk.length; + + // make sure the content length is not over the maxContentLength if specified + if (maxContentLength > -1 && totalResponseBytes > maxContentLength) { + // stream.destroy() emit aborted event before calling reject() on Node.js v16 + rejected = true; + responseStream.destroy(); + abort( + new AxiosError( + 'maxContentLength size of ' + maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, + config, + lastRequest + ) + ); + } + }); + + responseStream.on('aborted', function handlerStreamAborted() { + if (rejected) { + return; + } + + const err = new AxiosError( + 'stream has been aborted', + AxiosError.ERR_BAD_RESPONSE, + config, + lastRequest, + response + ); + responseStream.destroy(err); + reject(err); + }); + + responseStream.on('error', function handleStreamError(err) { + if (rejected) return; + reject(AxiosError.from(err, null, config, lastRequest, response)); + }); + + responseStream.on('end', function handleStreamEnd() { + try { + let responseData = + responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); + if (responseType !== 'arraybuffer') { + responseData = responseData.toString(responseEncoding); + if (!responseEncoding || responseEncoding === 'utf8') { + responseData = utils.stripBOM(responseData); + } + } + response.data = responseData; + } catch (err) { + return reject(AxiosError.from(err, null, config, response.request, response)); + } + settle(resolve, reject, response); + }); + } + + abortEmitter.once('abort', (err) => { + if (!responseStream.destroyed) { + responseStream.emit('error', err); + responseStream.destroy(); + } + }); + }); + + abortEmitter.once('abort', (err) => { + if (req.close) { + req.close(); + } else { + req.destroy(err); + } + }); + + // Handle errors + req.on('error', function handleRequestError(err) { + reject(AxiosError.from(err, null, config, req)); + }); + + // set tcp keep alive to prevent drop connection by peer + // Track every socket bound to this outer RedirectableRequest so a single + // 'close' listener can release ownership on all of them. follow-redirects + // re-emits the 'socket' event for each hop's native request onto the same + // outer request, so attaching per-request listeners inside this handler + // would accumulate across hops and trigger MaxListenersExceededWarning at + // >= 11 redirects. Clearing only the last-bound socket would leave stale + // kAxiosCurrentReq refs on earlier hop sockets returned to the keep-alive + // pool, causing an idle-pool 'error' to be attributed to a closed req. + const boundSockets = new Set(); + + req.on('socket', function handleRequestSocket(socket) { + // default interval of sending ack packet is 1 minute + socket.setKeepAlive(true, 1000 * 60); + + // Install a single 'error' listener per socket (not per request) to avoid + // accumulating listeners on pooled keep-alive sockets that get reassigned + // to new requests before the previous request's 'close' fires (issue #10780). + // The listener is bound to the socket's currently-active request via a + // symbol, which is swapped as the socket is reassigned. + if (!socket[kAxiosSocketListener]) { + socket.on('error', function handleSocketError(err) { + const current = socket[kAxiosCurrentReq]; + if (current && !current.destroyed) { + current.destroy(err); + } + }); + socket[kAxiosSocketListener] = true; + } + + socket[kAxiosCurrentReq] = req; + boundSockets.add(socket); + }); + + req.once('close', function clearCurrentReq() { + clearConnectPhaseTimer(); + + for (const socket of boundSockets) { + if (socket[kAxiosCurrentReq] === req) { + socket[kAxiosCurrentReq] = null; + } + } + boundSockets.clear(); + }); + + // Handle request timeout + if (own('timeout')) { + // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types. + const timeout = parseInt(own('timeout'), 10); + + if (Number.isNaN(timeout)) { + abort( + new AxiosError( + 'error trying to parse `config.timeout` to int', + AxiosError.ERR_BAD_OPTION_VALUE, + config, + req + ) + ); + + return; + } + + const handleTimeout = function handleTimeout() { + if (isDone) return; + abort(createTimeoutError()); + }; + + if (isNativeTransport && timeout > 0) { + // Native ClientRequest#setTimeout starts from the socket lifecycle and + // may not fire while TCP connect is still pending. Mirror the + // follow-redirects wall-clock timer for the maxRedirects === 0 path. + connectPhaseTimer = setTimeout(handleTimeout, timeout); + } + + // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. + // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. + // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. + // And then these socket which be hang up will devouring CPU little by little. + // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. + req.setTimeout(timeout, handleTimeout); + } else { + // explicitly reset the socket timeout value for a possible `keep-alive` request + req.setTimeout(0); + } + + // Send the request + if (utils.isStream(data)) { + let ended = false; + let errored = false; + + data.on('end', () => { + ended = true; + }); + + data.once('error', (err) => { + errored = true; + req.destroy(err); + }); + + data.on('close', () => { + if (!ended && !errored) { + abort(new CanceledError('Request stream has been aborted', config, req)); + } + }); + + // Enforce maxBodyLength for streamed uploads on every transport that + // does not apply options.maxBodyLength itself (native http/https, http2, + // and user-supplied custom transports). The follow-redirects transport + // enforces it on the redirected HTTP/1 path. + let uploadStream = data; + if (maxBodyLength > -1 && !transportEnforcesMaxBodyLength) { + const limit = maxBodyLength; + let bytesSent = 0; + uploadStream = stream.pipeline( + [ + data, + new stream.Transform({ + transform(chunk, _enc, cb) { + bytesSent += chunk.length; + if (bytesSent > limit) { + return cb( + new AxiosError( + 'Request body larger than maxBodyLength limit', + AxiosError.ERR_BAD_REQUEST, + config, + req + ) + ); + } + cb(null, chunk); + }, + }), + ], + utils.noop + ); + uploadStream.on('error', (err) => { + if (!req.destroyed) req.destroy(err); + }); + } + + uploadStream.pipe(req); + } else { + data && req.write(data); + req.end(); + } + }); + }; + +export const __setProxy = setProxy; +export const __isSameOriginRedirect = isSameOriginRedirect; diff --git a/node_modules/axios/lib/adapters/xhr.js b/node_modules/axios/lib/adapters/xhr.js new file mode 100644 index 0000000000000000000000000000000000000000..256367764f804b88c696a534ff9f71b0ac755b08 --- /dev/null +++ b/node_modules/axios/lib/adapters/xhr.js @@ -0,0 +1,227 @@ +import utils from '../utils.js'; +import settle from '../core/settle.js'; +import transitionalDefaults from '../defaults/transitional.js'; +import AxiosError from '../core/AxiosError.js'; +import CanceledError from '../cancel/CanceledError.js'; +import parseProtocol from '../helpers/parseProtocol.js'; +import platform from '../platform/index.js'; +import AxiosHeaders from '../core/AxiosHeaders.js'; +import { progressEventReducer } from '../helpers/progressEventReducer.js'; +import resolveConfig from '../helpers/resolveConfig.js'; +import { toByteStringHeaderObject } from '../helpers/sanitizeHeaderValue.js'; + +const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; + +export default isXHRAdapterSupported && + function (config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + const _config = resolveConfig(config); + let requestData = _config.data; + const requestHeaders = AxiosHeaders.from(_config.headers).normalize(); + let { responseType, onUploadProgress, onDownloadProgress } = _config; + let onCanceled; + let uploadThrottled, downloadThrottled; + let flushUpload, flushDownload; + + function done() { + flushUpload && flushUpload(); // flush events + flushDownload && flushDownload(); // flush events + + _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + + _config.signal && _config.signal.removeEventListener('abort', onCanceled); + } + + let request = new XMLHttpRequest(); + + request.open(_config.method.toUpperCase(), _config.url, true); + + // Set the request timeout in MS + request.timeout = _config.timeout; + + function onloadend() { + if (!request) { + return; + } + // Prepare the response + const responseHeaders = AxiosHeaders.from( + 'getAllResponseHeaders' in request && request.getAllResponseHeaders() + ); + const responseData = + !responseType || responseType === 'text' || responseType === 'json' + ? request.responseText + : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config, + request, + }; + + settle( + function _resolve(value) { + resolve(value); + done(); + }, + function _reject(err) { + reject(err); + done(); + }, + response + ); + + // Clean up request + request = null; + } + + if ('onloadend' in request) { + // Use onloadend if available + request.onloadend = onloadend; + } else { + // Listen for ready state to emulate onloadend + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if ( + request.status === 0 && + !(request.responseURL && request.responseURL.startsWith('file:')) + ) { + return; + } + // readystate handler is calling before onerror or ontimeout handlers, + // so we should call onloadend on the next 'tick' + setTimeout(onloadend); + }; + } + + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } + + reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); + done(); + + // Clean up request + request = null; + }; + + // Handle low level network errors + request.onerror = function handleError(event) { + // Browsers deliver a ProgressEvent in XHR onerror + // (message may be empty; when present, surface it) + // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event + const msg = event && event.message ? event.message : 'Network Error'; + const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request); + // attach the underlying event for consumers who want details + err.event = event || null; + reject(err); + done(); + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + let timeoutErrorMessage = _config.timeout + ? 'timeout of ' + _config.timeout + 'ms exceeded' + : 'timeout exceeded'; + const transitional = _config.transitional || transitionalDefaults; + if (_config.timeoutErrorMessage) { + timeoutErrorMessage = _config.timeoutErrorMessage; + } + reject( + new AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + request + ) + ); + done(); + + // Clean up request + request = null; + }; + + // Remove Content-Type if data is undefined + requestData === undefined && requestHeaders.setContentType(null); + + // Add headers to the request + if ('setRequestHeader' in request) { + utils.forEach(toByteStringHeaderObject(requestHeaders), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); + }); + } + + // Add withCredentials to request if needed + if (!utils.isUndefined(_config.withCredentials)) { + request.withCredentials = !!_config.withCredentials; + } + + // Add responseType to request if needed + if (responseType && responseType !== 'json') { + request.responseType = _config.responseType; + } + + // Handle progress if needed + if (onDownloadProgress) { + [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true); + request.addEventListener('progress', downloadThrottled); + } + + // Not all browsers support upload events + if (onUploadProgress && request.upload) { + [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress); + + request.upload.addEventListener('progress', uploadThrottled); + + request.upload.addEventListener('loadend', flushUpload); + } + + if (_config.cancelToken || _config.signal) { + // Handle cancellation + // eslint-disable-next-line func-names + onCanceled = (cancel) => { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); + request.abort(); + done(); + request = null; + }; + + _config.cancelToken && _config.cancelToken.subscribe(onCanceled); + if (_config.signal) { + _config.signal.aborted + ? onCanceled() + : _config.signal.addEventListener('abort', onCanceled); + } + } + + const protocol = parseProtocol(_config.url); + + if (protocol && !platform.protocols.includes(protocol)) { + reject( + new AxiosError( + 'Unsupported protocol ' + protocol + ':', + AxiosError.ERR_BAD_REQUEST, + config + ) + ); + return; + } + + // Send the request + request.send(requestData || null); + }); + }; diff --git a/node_modules/axios/lib/axios.js b/node_modules/axios/lib/axios.js new file mode 100644 index 0000000000000000000000000000000000000000..5a3a876c8e00aa563e84306fc89ae8e19b35bba2 --- /dev/null +++ b/node_modules/axios/lib/axios.js @@ -0,0 +1,89 @@ +'use strict'; + +import utils from './utils.js'; +import bind from './helpers/bind.js'; +import Axios from './core/Axios.js'; +import mergeConfig from './core/mergeConfig.js'; +import defaults from './defaults/index.js'; +import formDataToJSON from './helpers/formDataToJSON.js'; +import CanceledError from './cancel/CanceledError.js'; +import CancelToken from './cancel/CancelToken.js'; +import isCancel from './cancel/isCancel.js'; +import { VERSION } from './env/data.js'; +import toFormData from './helpers/toFormData.js'; +import AxiosError from './core/AxiosError.js'; +import spread from './helpers/spread.js'; +import isAxiosError from './helpers/isAxiosError.js'; +import AxiosHeaders from './core/AxiosHeaders.js'; +import adapters from './adapters/adapters.js'; +import HttpStatusCode from './helpers/HttpStatusCode.js'; + +/** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * + * @returns {Axios} A new instance of Axios + */ +function createInstance(defaultConfig) { + const context = new Axios(defaultConfig); + const instance = bind(Axios.prototype.request, context); + + // Copy axios.prototype to instance + utils.extend(instance, Axios.prototype, context, { allOwnKeys: true }); + + // Copy context to instance + utils.extend(instance, context, null, { allOwnKeys: true }); + + // Factory for creating new instances + instance.create = function create(instanceConfig) { + return createInstance(mergeConfig(defaultConfig, instanceConfig)); + }; + + return instance; +} + +// Create the default instance to be exported +const axios = createInstance(defaults); + +// Expose Axios class to allow class inheritance +axios.Axios = Axios; + +// Expose Cancel & CancelToken +axios.CanceledError = CanceledError; +axios.CancelToken = CancelToken; +axios.isCancel = isCancel; +axios.VERSION = VERSION; +axios.toFormData = toFormData; + +// Expose AxiosError class +axios.AxiosError = AxiosError; + +// alias for CanceledError for backward compatibility +axios.Cancel = axios.CanceledError; + +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; + +axios.spread = spread; + +// Expose isAxiosError +axios.isAxiosError = isAxiosError; + +// Expose mergeConfig +axios.mergeConfig = mergeConfig; + +axios.AxiosHeaders = AxiosHeaders; + +axios.formToJSON = (thing) => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing); + +axios.getAdapter = adapters.getAdapter; + +axios.HttpStatusCode = HttpStatusCode; + +axios.default = axios; + +// this module should only have a default export +export default axios; diff --git a/node_modules/axios/lib/cancel/CancelToken.js b/node_modules/axios/lib/cancel/CancelToken.js new file mode 100644 index 0000000000000000000000000000000000000000..357381ede41d736daa56556b004b7a4e1b15c2bb --- /dev/null +++ b/node_modules/axios/lib/cancel/CancelToken.js @@ -0,0 +1,135 @@ +'use strict'; + +import CanceledError from './CanceledError.js'; + +/** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @param {Function} executor The executor function. + * + * @returns {CancelToken} + */ +class CancelToken { + constructor(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + let resolvePromise; + + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + const token = this; + + // eslint-disable-next-line func-names + this.promise.then((cancel) => { + if (!token._listeners) return; + + let i = token._listeners.length; + + while (i-- > 0) { + token._listeners[i](cancel); + } + token._listeners = null; + }); + + // eslint-disable-next-line func-names + this.promise.then = (onfulfilled) => { + let _resolve; + // eslint-disable-next-line func-names + const promise = new Promise((resolve) => { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + + return promise; + }; + + executor(function cancel(message, config, request) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new CanceledError(message, config, request); + resolvePromise(token.reason); + }); + } + + /** + * Throws a `CanceledError` if cancellation has been requested. + */ + throwIfRequested() { + if (this.reason) { + throw this.reason; + } + } + + /** + * Subscribe to the cancel signal + */ + + subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } + } + + /** + * Unsubscribe from the cancel signal + */ + + unsubscribe(listener) { + if (!this._listeners) { + return; + } + const index = this._listeners.indexOf(listener); + if (index !== -1) { + this._listeners.splice(index, 1); + } + } + + toAbortSignal() { + const controller = new AbortController(); + + const abort = (err) => { + controller.abort(err); + }; + + this.subscribe(abort); + + controller.signal.unsubscribe = () => this.unsubscribe(abort); + + return controller.signal; + } + + /** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ + static source() { + let cancel; + const token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token, + cancel, + }; + } +} + +export default CancelToken; diff --git a/node_modules/axios/lib/cancel/CanceledError.js b/node_modules/axios/lib/cancel/CanceledError.js new file mode 100644 index 0000000000000000000000000000000000000000..e769b89a4e138e8612e230225812d13979af38b1 --- /dev/null +++ b/node_modules/axios/lib/cancel/CanceledError.js @@ -0,0 +1,22 @@ +'use strict'; + +import AxiosError from '../core/AxiosError.js'; + +class CanceledError extends AxiosError { + /** + * A `CanceledError` is an object that is thrown when an operation is canceled. + * + * @param {string=} message The message. + * @param {Object=} config The config. + * @param {Object=} request The request. + * + * @returns {CanceledError} The created error. + */ + constructor(message, config, request) { + super(message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request); + this.name = 'CanceledError'; + this.__CANCEL__ = true; + } +} + +export default CanceledError; diff --git a/node_modules/axios/lib/cancel/isCancel.js b/node_modules/axios/lib/cancel/isCancel.js new file mode 100644 index 0000000000000000000000000000000000000000..a444a129dec9c8dc9e0ed3f6914e8613f01df37c --- /dev/null +++ b/node_modules/axios/lib/cancel/isCancel.js @@ -0,0 +1,5 @@ +'use strict'; + +export default function isCancel(value) { + return !!(value && value.__CANCEL__); +} diff --git a/node_modules/axios/lib/core/Axios.js b/node_modules/axios/lib/core/Axios.js new file mode 100644 index 0000000000000000000000000000000000000000..7fc529e83d09c9ce62381e9487e6540eddf160fd --- /dev/null +++ b/node_modules/axios/lib/core/Axios.js @@ -0,0 +1,283 @@ +'use strict'; + +import utils from '../utils.js'; +import buildURL from '../helpers/buildURL.js'; +import InterceptorManager from './InterceptorManager.js'; +import dispatchRequest from './dispatchRequest.js'; +import mergeConfig from './mergeConfig.js'; +import buildFullPath from './buildFullPath.js'; +import validator from '../helpers/validator.js'; +import AxiosHeaders from './AxiosHeaders.js'; +import transitionalDefaults from '../defaults/transitional.js'; + +const validators = validator.validators; + +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + * + * @return {Axios} A new instance of Axios + */ +class Axios { + constructor(instanceConfig) { + this.defaults = instanceConfig || {}; + this.interceptors = { + request: new InterceptorManager(), + response: new InterceptorManager(), + }; + } + + /** + * Dispatch a request + * + * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) + * @param {?Object} config + * + * @returns {Promise} The Promise to be fulfilled + */ + async request(configOrUrl, config) { + try { + return await this._request(configOrUrl, config); + } catch (err) { + if (err instanceof Error) { + let dummy = {}; + + Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error()); + + // slice off the Error: ... line + const stack = (() => { + if (!dummy.stack) { + return ''; + } + + const firstNewlineIndex = dummy.stack.indexOf('\n'); + + return firstNewlineIndex === -1 ? '' : dummy.stack.slice(firstNewlineIndex + 1); + })(); + try { + if (!err.stack) { + err.stack = stack; + // match without the 2 top stack lines + } else if (stack) { + const firstNewlineIndex = stack.indexOf('\n'); + const secondNewlineIndex = + firstNewlineIndex === -1 ? -1 : stack.indexOf('\n', firstNewlineIndex + 1); + const stackWithoutTwoTopLines = + secondNewlineIndex === -1 ? '' : stack.slice(secondNewlineIndex + 1); + + if (!String(err.stack).endsWith(stackWithoutTwoTopLines)) { + err.stack += '\n' + stack; + } + } + } catch (e) { + // ignore the case where "stack" is an un-writable property + } + } + + throw err; + } + } + + _request(configOrUrl, config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof configOrUrl === 'string') { + config = config || {}; + config.url = configOrUrl; + } else { + config = configOrUrl || {}; + } + + config = mergeConfig(this.defaults, config); + + const { transitional, paramsSerializer, headers } = config; + + if (transitional !== undefined) { + validator.assertOptions( + transitional, + { + silentJSONParsing: validators.transitional(validators.boolean), + forcedJSONParsing: validators.transitional(validators.boolean), + clarifyTimeoutError: validators.transitional(validators.boolean), + legacyInterceptorReqResOrdering: validators.transitional(validators.boolean), + advertiseZstdAcceptEncoding: validators.transitional(validators.boolean), + validateStatusUndefinedResolves: validators.transitional(validators.boolean), + }, + false + ); + } + + if (paramsSerializer != null) { + if (utils.isFunction(paramsSerializer)) { + config.paramsSerializer = { + serialize: paramsSerializer, + }; + } else { + validator.assertOptions( + paramsSerializer, + { + encode: validators.function, + serialize: validators.function, + }, + true + ); + } + } + + // Set config.allowAbsoluteUrls + if (config.allowAbsoluteUrls !== undefined) { + // do nothing + } else if (this.defaults.allowAbsoluteUrls !== undefined) { + config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls; + } else { + config.allowAbsoluteUrls = true; + } + + validator.assertOptions( + config, + { + baseUrl: validators.spelling('baseURL'), + withXsrfToken: validators.spelling('withXSRFToken'), + }, + true + ); + + // Set config.method + config.method = (config.method || this.defaults.method || 'get').toLowerCase(); + + // Flatten headers + let contextHeaders = headers && utils.merge(headers.common, headers[config.method]); + + headers && + utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query', 'common'], (method) => { + delete headers[method]; + }); + + config.headers = AxiosHeaders.concat(contextHeaders, headers); + + // filter out skipped interceptors + const requestInterceptorChain = []; + let synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { + return; + } + + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + + const transitional = config.transitional || transitionalDefaults; + const legacyInterceptorReqResOrdering = + transitional && transitional.legacyInterceptorReqResOrdering; + + if (legacyInterceptorReqResOrdering) { + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + } else { + requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + } + }); + + const responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + + let promise; + let i = 0; + let len; + + if (!synchronousRequestInterceptors) { + const chain = [dispatchRequest.bind(this), undefined]; + chain.unshift(...requestInterceptorChain); + chain.push(...responseInterceptorChain); + len = chain.length; + + promise = Promise.resolve(config); + + while (i < len) { + promise = promise.then(chain[i++], chain[i++]); + } + + return promise; + } + + len = requestInterceptorChain.length; + + let newConfig = config; + + while (i < len) { + const onFulfilled = requestInterceptorChain[i++]; + const onRejected = requestInterceptorChain[i++]; + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; + } + } + + try { + promise = dispatchRequest.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + + i = 0; + len = responseInterceptorChain.length; + + while (i < len) { + promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + } + + return promise; + } + + getUri(config) { + config = mergeConfig(this.defaults, config); + const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls, config); + return buildURL(fullPath, config.params, config.paramsSerializer); + } +} + +// Provide aliases for supported request methods +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function (url, config) { + return this.request( + mergeConfig(config || {}, { + method, + url, + data: config && utils.hasOwnProp(config, 'data') ? config.data : undefined, + }) + ); + }; +}); + +utils.forEach(['post', 'put', 'patch', 'query'], function forEachMethodWithData(method) { + function generateHTTPMethod(isForm) { + return function httpMethod(url, data, config) { + return this.request( + mergeConfig(config || {}, { + method, + headers: isForm + ? { + 'Content-Type': 'multipart/form-data', + } + : {}, + url, + data, + }) + ); + }; + } + + Axios.prototype[method] = generateHTTPMethod(); + + // QUERY is a safe/idempotent read method; multipart form bodies don't fit + // its semantics, so no queryForm shorthand is generated. + if (method !== 'query') { + Axios.prototype[method + 'Form'] = generateHTTPMethod(true); + } +}); + +export default Axios; diff --git a/node_modules/axios/lib/core/AxiosError.js b/node_modules/axios/lib/core/AxiosError.js new file mode 100644 index 0000000000000000000000000000000000000000..d492485488b9d8dd70d0c99f2b350b0040746419 --- /dev/null +++ b/node_modules/axios/lib/core/AxiosError.js @@ -0,0 +1,176 @@ +'use strict'; + +import utils from '../utils.js'; +import AxiosHeaders from './AxiosHeaders.js'; + +const REDACTED = '[REDACTED ****]'; + +function hasOwnOrPrototypeToJSON(source) { + if (utils.hasOwnProp(source, 'toJSON')) { + return true; + } + + let prototype = Object.getPrototypeOf(source); + + while (prototype && prototype !== Object.prototype) { + if (utils.hasOwnProp(prototype, 'toJSON')) { + return true; + } + + prototype = Object.getPrototypeOf(prototype); + } + + return false; +} + +// Build a plain-object snapshot of `config` and replace the value of any key +// (case-insensitive) listed in `redactKeys` with REDACTED. Walks through arrays +// and AxiosHeaders, and short-circuits on circular references. +function redactConfig(config, redactKeys) { + const lowerKeys = new Set(redactKeys.map((k) => String(k).toLowerCase())); + const seen = []; + + const visit = (source) => { + if (source === null || typeof source !== 'object') return source; + if (utils.isBuffer(source)) return source; + if (seen.indexOf(source) !== -1) return undefined; + + if (source instanceof AxiosHeaders) { + source = source.toJSON(); + } + + seen.push(source); + + let result; + if (utils.isArray(source)) { + result = []; + source.forEach((v, i) => { + const reducedValue = visit(v); + if (!utils.isUndefined(reducedValue)) { + result[i] = reducedValue; + } + }); + } else { + if (!utils.isPlainObject(source) && hasOwnOrPrototypeToJSON(source)) { + seen.pop(); + return source; + } + + result = Object.create(null); + for (const [key, value] of Object.entries(source)) { + const reducedValue = lowerKeys.has(key.toLowerCase()) ? REDACTED : visit(value); + if (!utils.isUndefined(reducedValue)) { + result[key] = reducedValue; + } + } + } + + seen.pop(); + return result; + }; + + return visit(config); +} + +class AxiosError extends Error { + static from(error, code, config, request, response, customProps) { + const axiosError = new AxiosError(error.message, code || error.code, config, request, response); + axiosError.cause = error; + axiosError.name = error.name; + + // Preserve status from the original error if not already set from response + if (error.status != null && axiosError.status == null) { + axiosError.status = error.status; + } + + customProps && Object.assign(axiosError, customProps); + return axiosError; + } + + /** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [config] The config. + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * + * @returns {Error} The created error. + */ + constructor(message, code, config, request, response) { + super(message); + + // Make message enumerable to maintain backward compatibility + // The native Error constructor sets message as non-enumerable, + // but axios < v1.13.3 had it as enumerable + Object.defineProperty(this, 'message', { + // Null-proto descriptor so a polluted Object.prototype.get cannot turn + // this data descriptor into an accessor descriptor on the way in. + __proto__: null, + value: message, + enumerable: true, + writable: true, + configurable: true, + }); + + this.name = 'AxiosError'; + this.isAxiosError = true; + code && (this.code = code); + config && (this.config = config); + request && (this.request = request); + if (response) { + this.response = response; + this.status = response.status; + } + } + + toJSON() { + // Opt-in redaction: when the request config carries a `redact` array, the + // value of any matching key (case-insensitive, at any depth) is replaced + // with REDACTED in the serialized snapshot. Undefined or empty leaves the + // existing serialization behavior unchanged. + const config = this.config; + const redactKeys = config && utils.hasOwnProp(config, 'redact') ? config.redact : undefined; + const serializedConfig = + utils.isArray(redactKeys) && redactKeys.length > 0 + ? redactConfig(config, redactKeys) + : utils.toJSONObject(config); + + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: serializedConfig, + code: this.code, + status: this.status, + }; + } +} + +// This can be changed to static properties as soon as the parser options in .eslint.cjs are updated. +AxiosError.ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE'; +AxiosError.ERR_BAD_OPTION = 'ERR_BAD_OPTION'; +AxiosError.ECONNABORTED = 'ECONNABORTED'; +AxiosError.ETIMEDOUT = 'ETIMEDOUT'; +AxiosError.ECONNREFUSED = 'ECONNREFUSED'; +AxiosError.ERR_NETWORK = 'ERR_NETWORK'; +AxiosError.ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS'; +AxiosError.ERR_DEPRECATED = 'ERR_DEPRECATED'; +AxiosError.ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE'; +AxiosError.ERR_BAD_REQUEST = 'ERR_BAD_REQUEST'; +AxiosError.ERR_CANCELED = 'ERR_CANCELED'; +AxiosError.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT'; +AxiosError.ERR_INVALID_URL = 'ERR_INVALID_URL'; +AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED'; + +export default AxiosError; diff --git a/node_modules/axios/lib/core/AxiosHeaders.js b/node_modules/axios/lib/core/AxiosHeaders.js new file mode 100644 index 0000000000000000000000000000000000000000..376f87a943dd4de16b0e9653becaf0d14f901987 --- /dev/null +++ b/node_modules/axios/lib/core/AxiosHeaders.js @@ -0,0 +1,351 @@ +'use strict'; + +import utils from '../utils.js'; +import parseHeaders from '../helpers/parseHeaders.js'; +import { sanitizeHeaderValue } from '../helpers/sanitizeHeaderValue.js'; + +const $internals = Symbol('internals'); + +function normalizeHeader(header) { + return header && String(header).trim().toLowerCase(); +} + +function normalizeValue(value) { + if (value === false || value == null) { + return value; + } + + return utils.isArray(value) ? value.map(normalizeValue) : sanitizeHeaderValue(String(value)); +} + +function parseTokens(str) { + const tokens = Object.create(null); + const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + let match; + + while ((match = tokensRE.exec(str))) { + tokens[match[1]] = match[2]; + } + + return tokens; +} + +const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); + +function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { + if (utils.isFunction(filter)) { + return filter.call(this, value, header); + } + + if (isHeaderNameFilter) { + value = header; + } + + if (!utils.isString(value)) return; + + if (utils.isString(filter)) { + return value.indexOf(filter) !== -1; + } + + if (utils.isRegExp(filter)) { + return filter.test(value); + } +} + +function formatHeader(header) { + return header + .trim() + .toLowerCase() + .replace(/([a-z\d])(\w*)/g, (w, char, str) => { + return char.toUpperCase() + str; + }); +} + +function buildAccessors(obj, header) { + const accessorName = utils.toCamelCase(' ' + header); + + ['get', 'set', 'has'].forEach((methodName) => { + Object.defineProperty(obj, methodName + accessorName, { + // Null-proto descriptor so a polluted Object.prototype.get cannot turn + // this data descriptor into an accessor descriptor on the way in. + __proto__: null, + value: function (arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); + }, + configurable: true, + }); + }); +} + +class AxiosHeaders { + constructor(headers) { + headers && this.set(headers); + } + + set(header, valueOrRewrite, rewrite) { + const self = this; + + function setHeader(_value, _header, _rewrite) { + const lHeader = normalizeHeader(_header); + + if (!lHeader) { + return; + } + + const key = utils.findKey(self, lHeader); + + if ( + !key || + self[key] === undefined || + _rewrite === true || + (_rewrite === undefined && self[key] !== false) + ) { + self[key || _header] = normalizeValue(_value); + } + } + + const setHeaders = (headers, _rewrite) => + utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + + if (utils.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite); + } else if (utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + setHeaders(parseHeaders(header), valueOrRewrite); + } else if (utils.isObject(header) && utils.isSafeIterable(header)) { + let obj = Object.create(null), + dest, + key; + for (const entry of header) { + if (!utils.isArray(entry)) { + throw new TypeError('Object iterator must return a key-value pair'); + } + + key = entry[0]; + + if (utils.hasOwnProp(obj, key)) { + dest = obj[key]; + obj[key] = utils.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]]; + } else { + obj[key] = entry[1]; + } + } + + setHeaders(obj, valueOrRewrite); + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); + } + + return this; + } + + get(header, parser) { + header = normalizeHeader(header); + + if (header) { + const key = utils.findKey(this, header); + + if (key) { + const value = this[key]; + + if (!parser) { + return value; + } + + if (parser === true) { + return parseTokens(value); + } + + if (utils.isFunction(parser)) { + return parser.call(this, value, key); + } + + if (utils.isRegExp(parser)) { + return parser.exec(value); + } + + throw new TypeError('parser must be boolean|regexp|function'); + } + } + } + + has(header, matcher) { + header = normalizeHeader(header); + + if (header) { + const key = utils.findKey(this, header); + + return !!( + key && + this[key] !== undefined && + (!matcher || matchHeaderValue(this, this[key], key, matcher)) + ); + } + + return false; + } + + delete(header, matcher) { + const self = this; + let deleted = false; + + function deleteHeader(_header) { + _header = normalizeHeader(_header); + + if (_header) { + const key = utils.findKey(self, _header); + + if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { + delete self[key]; + + deleted = true; + } + } + } + + if (utils.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); + } + + return deleted; + } + + clear(matcher) { + const keys = Object.keys(this); + let i = keys.length; + let deleted = false; + + while (i--) { + const key = keys[i]; + if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } + } + + return deleted; + } + + normalize(format) { + const self = this; + const headers = {}; + + utils.forEach(this, (value, header) => { + const key = utils.findKey(headers, header); + + if (key) { + self[key] = normalizeValue(value); + delete self[header]; + return; + } + + const normalized = format ? formatHeader(header) : String(header).trim(); + + if (normalized !== header) { + delete self[header]; + } + + self[normalized] = normalizeValue(value); + + headers[normalized] = true; + }); + + return this; + } + + concat(...targets) { + return this.constructor.concat(this, ...targets); + } + + toJSON(asStrings) { + const obj = Object.create(null); + + utils.forEach(this, (value, header) => { + value != null && + value !== false && + (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value); + }); + + return obj; + } + + [Symbol.iterator]() { + return Object.entries(this.toJSON())[Symbol.iterator](); + } + + toString() { + return Object.entries(this.toJSON()) + .map(([header, value]) => header + ': ' + value) + .join('\n'); + } + + getSetCookie() { + return this.get('set-cookie') || []; + } + + get [Symbol.toStringTag]() { + return 'AxiosHeaders'; + } + + static from(thing) { + return thing instanceof this ? thing : new this(thing); + } + + static concat(first, ...targets) { + const computed = new this(first); + + targets.forEach((target) => computed.set(target)); + + return computed; + } + + static accessor(header) { + const internals = + (this[$internals] = + this[$internals] = + { + accessors: {}, + }); + + const accessors = internals.accessors; + const prototype = this.prototype; + + function defineAccessor(_header) { + const lHeader = normalizeHeader(_header); + + if (!accessors[lHeader]) { + buildAccessors(prototype, _header); + accessors[lHeader] = true; + } + } + + utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + + return this; + } +} + +AxiosHeaders.accessor([ + 'Content-Type', + 'Content-Length', + 'Accept', + 'Accept-Encoding', + 'User-Agent', + 'Authorization', +]); + +// reserved names hotfix +utils.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => { + let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` + return { + get: () => value, + set(headerValue) { + this[mapped] = headerValue; + }, + }; +}); + +utils.freezeMethods(AxiosHeaders); + +export default AxiosHeaders; diff --git a/node_modules/axios/lib/core/InterceptorManager.js b/node_modules/axios/lib/core/InterceptorManager.js new file mode 100644 index 0000000000000000000000000000000000000000..fe10f3d795b47a2751f2f6a447961138ad0f5b3c --- /dev/null +++ b/node_modules/axios/lib/core/InterceptorManager.js @@ -0,0 +1,72 @@ +'use strict'; + +import utils from '../utils.js'; + +class InterceptorManager { + constructor() { + this.handlers = []; + } + + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * @param {Object} options The options for the interceptor, synchronous and runWhen + * + * @return {Number} An ID used to remove interceptor later + */ + use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled, + rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null, + }); + return this.handlers.length - 1; + } + + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + * + * @returns {void} + */ + eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + + /** + * Clear all interceptors from the stack + * + * @returns {void} + */ + clear() { + if (this.handlers) { + this.handlers = []; + } + } + + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + * + * @returns {void} + */ + forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); + } +} + +export default InterceptorManager; diff --git a/node_modules/axios/lib/core/README.md b/node_modules/axios/lib/core/README.md new file mode 100644 index 0000000000000000000000000000000000000000..84559ce7c8039363a0c08afc72590af0aa288979 --- /dev/null +++ b/node_modules/axios/lib/core/README.md @@ -0,0 +1,8 @@ +# axios // core + +The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are: + +- Dispatching requests + - Requests sent via `adapters/` (see lib/adapters/README.md) +- Managing interceptors +- Handling config diff --git a/node_modules/axios/lib/core/buildFullPath.js b/node_modules/axios/lib/core/buildFullPath.js new file mode 100644 index 0000000000000000000000000000000000000000..e88cd6a04fe81ad782644bf1f2773480e88ef9cb --- /dev/null +++ b/node_modules/axios/lib/core/buildFullPath.js @@ -0,0 +1,50 @@ +'use strict'; + +import AxiosError from './AxiosError.js'; +import isAbsoluteURL from '../helpers/isAbsoluteURL.js'; +import combineURLs from '../helpers/combineURLs.js'; + +const malformedHttpProtocol = /^https?:(?!\/\/)/i; +const httpProtocolControlCharacters = /[\t\n\r]/g; + +function stripLeadingC0ControlOrSpace(url) { + let i = 0; + while (i < url.length && url.charCodeAt(i) <= 0x20) { + i++; + } + return url.slice(i); +} + +function normalizeURLForProtocolCheck(url) { + return stripLeadingC0ControlOrSpace(url).replace(httpProtocolControlCharacters, ''); +} + +function assertValidHttpProtocolURL(url, config) { + if (typeof url === 'string' && malformedHttpProtocol.test(normalizeURLForProtocolCheck(url))) { + throw new AxiosError( + 'Invalid URL: missing "//" after protocol', + AxiosError.ERR_INVALID_URL, + config + ); + } +} + +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * + * @returns {string} The combined full path + */ +export default function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls, config) { + assertValidHttpProtocolURL(requestedURL, config); + let isRelativeUrl = !isAbsoluteURL(requestedURL); + if (baseURL && (isRelativeUrl || allowAbsoluteUrls === false)) { + assertValidHttpProtocolURL(baseURL, config); + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +} diff --git a/node_modules/axios/lib/core/dispatchRequest.js b/node_modules/axios/lib/core/dispatchRequest.js new file mode 100644 index 0000000000000000000000000000000000000000..59662d4640e95298a2c9808ca77131a38d586c2e --- /dev/null +++ b/node_modules/axios/lib/core/dispatchRequest.js @@ -0,0 +1,89 @@ +'use strict'; + +import transformData from './transformData.js'; +import isCancel from '../cancel/isCancel.js'; +import defaults from '../defaults/index.js'; +import CanceledError from '../cancel/CanceledError.js'; +import AxiosHeaders from '../core/AxiosHeaders.js'; +import adapters from '../adapters/adapters.js'; + +/** + * Throws a `CanceledError` if cancellation has been requested. + * + * @param {Object} config The config that is to be used for the request + * + * @returns {void} + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } + + if (config.signal && config.signal.aborted) { + throw new CanceledError(null, config); + } +} + +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * + * @returns {Promise} The Promise to be fulfilled + */ +export default function dispatchRequest(config) { + throwIfCancellationRequested(config); + + config.headers = AxiosHeaders.from(config.headers); + + // Transform request data + config.data = transformData.call(config, config.transformRequest); + + if (['post', 'put', 'patch'].indexOf(config.method) !== -1) { + config.headers.setContentType('application/x-www-form-urlencoded', false); + } + + const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config); + + return adapter(config).then( + function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Expose the current response on config so that transformResponse can + // attach it to any AxiosError it throws (e.g. on JSON parse failure). + // We clean it up afterwards to avoid polluting the config object. + config.response = response; + try { + response.data = transformData.call(config, config.transformResponse, response); + } finally { + delete config.response; + } + + response.headers = AxiosHeaders.from(response.headers); + + return response; + }, + function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + config.response = reason.response; + try { + reason.response.data = transformData.call( + config, + config.transformResponse, + reason.response + ); + } finally { + delete config.response; + } + reason.response.headers = AxiosHeaders.from(reason.response.headers); + } + } + + return Promise.reject(reason); + } + ); +} diff --git a/node_modules/axios/lib/core/mergeConfig.js b/node_modules/axios/lib/core/mergeConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..a31a9f16fb19895ea9a71210eee1f8adabdace6c --- /dev/null +++ b/node_modules/axios/lib/core/mergeConfig.js @@ -0,0 +1,158 @@ +'use strict'; + +import utils from '../utils.js'; +import AxiosHeaders from './AxiosHeaders.js'; + +const headersToObject = (thing) => (thing instanceof AxiosHeaders ? { ...thing } : thing); + +/** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * + * @returns {Object} New object resulting from merging config2 to config1 + */ +export default function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + + // Use a null-prototype object so that downstream reads such as `config.auth` + // or `config.baseURL` cannot inherit polluted values from Object.prototype. + // `hasOwnProperty` is restored as a non-enumerable own slot to preserve + // ergonomics for user code that relies on it. + const config = Object.create(null); + Object.defineProperty(config, 'hasOwnProperty', { + // Null-proto descriptor so a polluted Object.prototype.get cannot turn + // this data descriptor into an accessor descriptor on the way in. + __proto__: null, + value: Object.prototype.hasOwnProperty, + enumerable: false, + writable: true, + configurable: true, + }); + + function getMergedValue(target, source, prop, caseless) { + if (utils.isPlainObject(target) && utils.isPlainObject(source)) { + return utils.merge.call({ caseless }, target, source); + } else if (utils.isPlainObject(source)) { + return utils.merge({}, source); + } else if (utils.isArray(source)) { + return source.slice(); + } + return source; + } + + function mergeDeepProperties(a, b, prop, caseless) { + if (!utils.isUndefined(b)) { + return getMergedValue(a, b, prop, caseless); + } else if (!utils.isUndefined(a)) { + return getMergedValue(undefined, a, prop, caseless); + } + } + + // eslint-disable-next-line consistent-return + function valueFromConfig2(a, b) { + if (!utils.isUndefined(b)) { + return getMergedValue(undefined, b); + } + } + + // eslint-disable-next-line consistent-return + function defaultToConfig2(a, b) { + if (!utils.isUndefined(b)) { + return getMergedValue(undefined, b); + } else if (!utils.isUndefined(a)) { + return getMergedValue(undefined, a); + } + } + + function getMergedTransitionalOption(prop) { + const transitional2 = utils.hasOwnProp(config2, 'transitional') ? config2.transitional : undefined; + + if (!utils.isUndefined(transitional2)) { + if (utils.isPlainObject(transitional2)) { + if (utils.hasOwnProp(transitional2, prop)) { + return transitional2[prop]; + } + } else { + return undefined; + } + } + + const transitional1 = utils.hasOwnProp(config1, 'transitional') ? config1.transitional : undefined; + + if (utils.isPlainObject(transitional1) && utils.hasOwnProp(transitional1, prop)) { + return transitional1[prop]; + } + + return undefined; + } + + // eslint-disable-next-line consistent-return + function mergeDirectKeys(a, b, prop) { + if (utils.hasOwnProp(config2, prop)) { + return getMergedValue(a, b); + } else if (utils.hasOwnProp(config1, prop)) { + return getMergedValue(undefined, a); + } + } + + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + allowedSocketPaths: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a, b, prop) => + mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true), + }; + + utils.forEach(Object.keys({ ...config1, ...config2 }), function computeConfigValue(prop) { + if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') return; + const merge = utils.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties; + const a = utils.hasOwnProp(config1, prop) ? config1[prop] : undefined; + const b = utils.hasOwnProp(config2, prop) ? config2[prop] : undefined; + const configValue = merge(a, b, prop); + (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); + }); + + if ( + utils.hasOwnProp(config2, 'validateStatus') && + utils.isUndefined(config2.validateStatus) && + getMergedTransitionalOption('validateStatusUndefinedResolves') === false + ) { + if (utils.hasOwnProp(config1, 'validateStatus')) { + config.validateStatus = getMergedValue(undefined, config1.validateStatus); + } else { + delete config.validateStatus; + } + } + + return config; +} diff --git a/node_modules/axios/lib/core/settle.js b/node_modules/axios/lib/core/settle.js new file mode 100644 index 0000000000000000000000000000000000000000..782f571233db30f348cb932f3f4d9beec50da946 --- /dev/null +++ b/node_modules/axios/lib/core/settle.js @@ -0,0 +1,27 @@ +'use strict'; + +import AxiosError from './AxiosError.js'; + +/** + * Resolve or reject a Promise based on response status. + * + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. + * + * @returns {object} The response. + */ +export default function settle(resolve, reject, response) { + const validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(new AxiosError( + 'Request failed with status code ' + response.status, + response.status >= 400 && response.status < 500 ? AxiosError.ERR_BAD_REQUEST : AxiosError.ERR_BAD_RESPONSE, + response.config, + response.request, + response + )); + } +} diff --git a/node_modules/axios/lib/core/transformData.js b/node_modules/axios/lib/core/transformData.js new file mode 100644 index 0000000000000000000000000000000000000000..f22c474356d07a7fb7b0595640ab139e9472e2cc --- /dev/null +++ b/node_modules/axios/lib/core/transformData.js @@ -0,0 +1,28 @@ +'use strict'; + +import utils from '../utils.js'; +import defaults from '../defaults/index.js'; +import AxiosHeaders from '../core/AxiosHeaders.js'; + +/** + * Transform the data for a request or a response + * + * @param {Array|Function} fns A single function or Array of functions + * @param {?Object} response The response object + * + * @returns {*} The resulting transformed data + */ +export default function transformData(fns, response) { + const config = this || defaults; + const context = response || config; + const headers = AxiosHeaders.from(context.headers); + let data = context.data; + + utils.forEach(fns, function transform(fn) { + data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); + }); + + headers.normalize(); + + return data; +} diff --git a/node_modules/axios/lib/defaults/index.js b/node_modules/axios/lib/defaults/index.js new file mode 100644 index 0000000000000000000000000000000000000000..642a0895af845d254b059dd114fe46c6be06d6c8 --- /dev/null +++ b/node_modules/axios/lib/defaults/index.js @@ -0,0 +1,177 @@ +'use strict'; + +import utils from '../utils.js'; +import AxiosError from '../core/AxiosError.js'; +import transitionalDefaults from './transitional.js'; +import toFormData from '../helpers/toFormData.js'; +import toURLEncodedForm from '../helpers/toURLEncodedForm.js'; +import platform from '../platform/index.js'; +import formDataToJSON from '../helpers/formDataToJSON.js'; + +const own = (obj, key) => (obj != null && utils.hasOwnProp(obj, key) ? obj[key] : undefined); + +/** + * It takes a string, tries to parse it, and if it fails, it returns the stringified version + * of the input + * + * @param {any} rawValue - The value to be stringified. + * @param {Function} parser - A function that parses a string into a JavaScript object. + * @param {Function} encoder - A function that takes a value and returns a string. + * + * @returns {string} A stringified version of the rawValue. + */ +function stringifySafely(rawValue, parser, encoder) { + if (utils.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils.trim(rawValue); + } catch (e) { + if (e.name !== 'SyntaxError') { + throw e; + } + } + } + + return (encoder || JSON.stringify)(rawValue); +} + +const defaults = { + transitional: transitionalDefaults, + + adapter: ['xhr', 'http', 'fetch'], + + transformRequest: [ + function transformRequest(data, headers) { + const contentType = headers.getContentType() || ''; + const hasJSONContentType = contentType.indexOf('application/json') > -1; + const isObjectPayload = utils.isObject(data); + + if (isObjectPayload && utils.isHTMLForm(data)) { + data = new FormData(data); + } + + const isFormData = utils.isFormData(data); + + if (isFormData) { + return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; + } + + if ( + utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) || + utils.isReadableStream(data) + ) { + return data; + } + if (utils.isArrayBufferView(data)) { + return data.buffer; + } + if (utils.isURLSearchParams(data)) { + headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); + return data.toString(); + } + + let isFileList; + + if (isObjectPayload) { + const formSerializer = own(this, 'formSerializer'); + if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { + return toURLEncodedForm(data, formSerializer).toString(); + } + + if ( + (isFileList = utils.isFileList(data)) || + contentType.indexOf('multipart/form-data') > -1 + ) { + const env = own(this, 'env'); + const _FormData = env && env.FormData; + + return toFormData( + isFileList ? { 'files[]': data } : data, + _FormData && new _FormData(), + formSerializer + ); + } + } + + if (isObjectPayload || hasJSONContentType) { + headers.setContentType('application/json', false); + return stringifySafely(data); + } + + return data; + }, + ], + + transformResponse: [ + function transformResponse(data) { + const transitional = own(this, 'transitional') || defaults.transitional; + const forcedJSONParsing = transitional && transitional.forcedJSONParsing; + const responseType = own(this, 'responseType'); + const JSONRequested = responseType === 'json'; + + if (utils.isResponse(data) || utils.isReadableStream(data)) { + return data; + } + + if ( + data && + utils.isString(data) && + ((forcedJSONParsing && !responseType) || JSONRequested) + ) { + const silentJSONParsing = transitional && transitional.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + + try { + return JSON.parse(data, own(this, 'parseReviver')); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, own(this, 'response')); + } + throw e; + } + } + } + + return data; + }, + ], + + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + maxBodyLength: -1, + + env: { + FormData: platform.classes.FormData, + Blob: platform.classes.Blob, + }, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, + + headers: { + common: { + Accept: 'application/json, text/plain, */*', + 'Content-Type': undefined, + }, + }, +}; + +utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query'], (method) => { + defaults.headers[method] = {}; +}); + +export default defaults; diff --git a/node_modules/axios/lib/defaults/transitional.js b/node_modules/axios/lib/defaults/transitional.js new file mode 100644 index 0000000000000000000000000000000000000000..e64a6a994eb74822751865a8a76bd242825277f5 --- /dev/null +++ b/node_modules/axios/lib/defaults/transitional.js @@ -0,0 +1,10 @@ +'use strict'; + +export default { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false, + legacyInterceptorReqResOrdering: true, + advertiseZstdAcceptEncoding: false, + validateStatusUndefinedResolves: true, +}; diff --git a/node_modules/axios/lib/env/README.md b/node_modules/axios/lib/env/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b41baff3c9960a110087369cea8dbc86d6a75f0b --- /dev/null +++ b/node_modules/axios/lib/env/README.md @@ -0,0 +1,3 @@ +# axios // env + +The `data.js` file is updated automatically when the package version is upgrading. Please do not edit it manually. diff --git a/node_modules/axios/lib/env/classes/FormData.js b/node_modules/axios/lib/env/classes/FormData.js new file mode 100644 index 0000000000000000000000000000000000000000..862adb93c3df8de3c178325d090b7a5b1503274a --- /dev/null +++ b/node_modules/axios/lib/env/classes/FormData.js @@ -0,0 +1,2 @@ +import _FormData from 'form-data'; +export default typeof FormData !== 'undefined' ? FormData : _FormData; diff --git a/node_modules/axios/lib/env/data.js b/node_modules/axios/lib/env/data.js new file mode 100644 index 0000000000000000000000000000000000000000..6b5a6ceb55995bccf9a5693fff5b88e3610f10fe --- /dev/null +++ b/node_modules/axios/lib/env/data.js @@ -0,0 +1 @@ +export const VERSION = "1.18.0"; \ No newline at end of file diff --git a/node_modules/axios/lib/helpers/AxiosTransformStream.js b/node_modules/axios/lib/helpers/AxiosTransformStream.js new file mode 100644 index 0000000000000000000000000000000000000000..96e8acb0268374a2fc5ce623742ada3276015df1 --- /dev/null +++ b/node_modules/axios/lib/helpers/AxiosTransformStream.js @@ -0,0 +1,156 @@ +'use strict'; + +import stream from 'stream'; +import utils from '../utils.js'; + +const kInternals = Symbol('internals'); + +class AxiosTransformStream extends stream.Transform { + constructor(options) { + options = utils.toFlatObject( + options, + { + maxRate: 0, + chunkSize: 64 * 1024, + minChunkSize: 100, + timeWindow: 500, + ticksRate: 2, + samplesCount: 15, + }, + null, + (prop, source) => { + return !utils.isUndefined(source[prop]); + } + ); + + super({ + readableHighWaterMark: options.chunkSize, + }); + + const internals = (this[kInternals] = { + timeWindow: options.timeWindow, + chunkSize: options.chunkSize, + maxRate: options.maxRate, + minChunkSize: options.minChunkSize, + bytesSeen: 0, + isCaptured: false, + notifiedBytesLoaded: 0, + ts: Date.now(), + bytes: 0, + onReadCallback: null, + }); + + this.on('newListener', (event) => { + if (event === 'progress') { + if (!internals.isCaptured) { + internals.isCaptured = true; + } + } + }); + } + + _read(size) { + const internals = this[kInternals]; + + if (internals.onReadCallback) { + internals.onReadCallback(); + } + + return super._read(size); + } + + _transform(chunk, encoding, callback) { + const internals = this[kInternals]; + const maxRate = internals.maxRate; + + const readableHighWaterMark = this.readableHighWaterMark; + + const timeWindow = internals.timeWindow; + + const divider = 1000 / timeWindow; + const bytesThreshold = maxRate / divider; + const minChunkSize = + internals.minChunkSize !== false + ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) + : 0; + + const pushChunk = (_chunk, _callback) => { + const bytes = Buffer.byteLength(_chunk); + internals.bytesSeen += bytes; + internals.bytes += bytes; + + internals.isCaptured && this.emit('progress', internals.bytesSeen); + + if (this.push(_chunk)) { + process.nextTick(_callback); + } else { + internals.onReadCallback = () => { + internals.onReadCallback = null; + process.nextTick(_callback); + }; + } + }; + + const transformChunk = (_chunk, _callback) => { + const chunkSize = Buffer.byteLength(_chunk); + let chunkRemainder = null; + let maxChunkSize = readableHighWaterMark; + let bytesLeft; + let passed = 0; + + if (maxRate) { + const now = Date.now(); + + if (!internals.ts || (passed = now - internals.ts) >= timeWindow) { + internals.ts = now; + bytesLeft = bytesThreshold - internals.bytes; + internals.bytes = bytesLeft < 0 ? -bytesLeft : 0; + passed = 0; + } + + bytesLeft = bytesThreshold - internals.bytes; + } + + if (maxRate) { + if (bytesLeft <= 0) { + // next time window + return setTimeout(() => { + _callback(null, _chunk); + }, timeWindow - passed); + } + + if (bytesLeft < maxChunkSize) { + maxChunkSize = bytesLeft; + } + } + + if (maxChunkSize && chunkSize > maxChunkSize && chunkSize - maxChunkSize > minChunkSize) { + chunkRemainder = _chunk.subarray(maxChunkSize); + _chunk = _chunk.subarray(0, maxChunkSize); + } + + pushChunk( + _chunk, + chunkRemainder + ? () => { + process.nextTick(_callback, null, chunkRemainder); + } + : _callback + ); + }; + + transformChunk(chunk, function transformNextChunk(err, _chunk) { + if (err) { + return callback(err); + } + + if (_chunk) { + transformChunk(_chunk, transformNextChunk); + } else { + callback(null); + } + }); + } +} + +export default AxiosTransformStream; diff --git a/node_modules/axios/lib/helpers/AxiosURLSearchParams.js b/node_modules/axios/lib/helpers/AxiosURLSearchParams.js new file mode 100644 index 0000000000000000000000000000000000000000..57cf16d114aa417faac47c2a7f22ac62f0933bd4 --- /dev/null +++ b/node_modules/axios/lib/helpers/AxiosURLSearchParams.js @@ -0,0 +1,61 @@ +'use strict'; + +import toFormData from './toFormData.js'; + +/** + * It encodes a string by replacing all characters that are not in the unreserved set with + * their percent-encoded equivalents + * + * @param {string} str - The string to encode. + * + * @returns {string} The encoded string. + */ +function encode(str) { + const charMap = { + '!': '%21', + "'": '%27', + '(': '%28', + ')': '%29', + '~': '%7E', + '%20': '+', + }; + return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match) { + return charMap[match]; + }); +} + +/** + * It takes a params object and converts it to a FormData object + * + * @param {Object} params - The parameters to be converted to a FormData object. + * @param {Object} options - The options object passed to the Axios constructor. + * + * @returns {void} + */ +function AxiosURLSearchParams(params, options) { + this._pairs = []; + + params && toFormData(params, this, options); +} + +const prototype = AxiosURLSearchParams.prototype; + +prototype.append = function append(name, value) { + this._pairs.push([name, value]); +}; + +prototype.toString = function toString(encoder) { + const _encode = encoder + ? function (value) { + return encoder.call(this, value, encode); + } + : encode; + + return this._pairs + .map(function each(pair) { + return _encode(pair[0]) + '=' + _encode(pair[1]); + }, '') + .join('&'); +}; + +export default AxiosURLSearchParams; diff --git a/node_modules/axios/lib/helpers/Http2Sessions.js b/node_modules/axios/lib/helpers/Http2Sessions.js new file mode 100644 index 0000000000000000000000000000000000000000..b3cf924b49cf0ce2d9d661eac606da53cd79299f --- /dev/null +++ b/node_modules/axios/lib/helpers/Http2Sessions.js @@ -0,0 +1,119 @@ +'use strict'; + +// Node-only: relies on the built-in `http2` module. Browser/react-native +// builds replace `lib/adapters/http.js` (the sole importer) with `lib/helpers/null.js` +// via the `browser` package.json field, so this module is never reached in +// those environments. Do not import it from any browser-reachable code path. + +import http2 from 'http2'; +import util from 'util'; + +class Http2Sessions { + constructor() { + this.sessions = Object.create(null); + } + + getSession(authority, options) { + options = Object.assign( + { + sessionTimeout: 1000, + }, + options + ); + + let authoritySessions = this.sessions[authority]; + + if (authoritySessions) { + let len = authoritySessions.length; + + for (let i = 0; i < len; i++) { + const [sessionHandle, sessionOptions] = authoritySessions[i]; + if ( + !sessionHandle.destroyed && + !sessionHandle.closed && + util.isDeepStrictEqual(sessionOptions, options) + ) { + return sessionHandle; + } + } + } + + const session = http2.connect(authority, options); + + let removed; + let timer; + + const removeSession = () => { + if (removed) { + return; + } + + removed = true; + + if (timer) { + clearTimeout(timer); + timer = null; + } + + let entries = authoritySessions, + len = entries.length, + i = len; + + while (i--) { + if (entries[i][0] === session) { + if (len === 1) { + delete this.sessions[authority]; + } else { + entries.splice(i, 1); + } + if (!session.closed) { + session.close(); + } + return; + } + } + }; + + const originalRequestFn = session.request; + + const { sessionTimeout } = options; + + if (sessionTimeout != null) { + let streamsCount = 0; + + session.request = function () { + const stream = originalRequestFn.apply(this, arguments); + + streamsCount++; + + if (timer) { + clearTimeout(timer); + timer = null; + } + + stream.once('close', () => { + if (!--streamsCount) { + timer = setTimeout(() => { + timer = null; + removeSession(); + }, sessionTimeout); + } + }); + + return stream; + }; + } + + session.once('close', removeSession); + + let entry = [session, options]; + + authoritySessions + ? authoritySessions.push(entry) + : (authoritySessions = this.sessions[authority] = [entry]); + + return session; + } +} + +export default Http2Sessions; diff --git a/node_modules/axios/lib/helpers/HttpStatusCode.js b/node_modules/axios/lib/helpers/HttpStatusCode.js new file mode 100644 index 0000000000000000000000000000000000000000..b68d08e1bbea3f9eda0c49adf778a8e81da16cbb --- /dev/null +++ b/node_modules/axios/lib/helpers/HttpStatusCode.js @@ -0,0 +1,77 @@ +const HttpStatusCode = { + Continue: 100, + SwitchingProtocols: 101, + Processing: 102, + EarlyHints: 103, + Ok: 200, + Created: 201, + Accepted: 202, + NonAuthoritativeInformation: 203, + NoContent: 204, + ResetContent: 205, + PartialContent: 206, + MultiStatus: 207, + AlreadyReported: 208, + ImUsed: 226, + MultipleChoices: 300, + MovedPermanently: 301, + Found: 302, + SeeOther: 303, + NotModified: 304, + UseProxy: 305, + Unused: 306, + TemporaryRedirect: 307, + PermanentRedirect: 308, + BadRequest: 400, + Unauthorized: 401, + PaymentRequired: 402, + Forbidden: 403, + NotFound: 404, + MethodNotAllowed: 405, + NotAcceptable: 406, + ProxyAuthenticationRequired: 407, + RequestTimeout: 408, + Conflict: 409, + Gone: 410, + LengthRequired: 411, + PreconditionFailed: 412, + PayloadTooLarge: 413, + UriTooLong: 414, + UnsupportedMediaType: 415, + RangeNotSatisfiable: 416, + ExpectationFailed: 417, + ImATeapot: 418, + MisdirectedRequest: 421, + UnprocessableEntity: 422, + Locked: 423, + FailedDependency: 424, + TooEarly: 425, + UpgradeRequired: 426, + PreconditionRequired: 428, + TooManyRequests: 429, + RequestHeaderFieldsTooLarge: 431, + UnavailableForLegalReasons: 451, + InternalServerError: 500, + NotImplemented: 501, + BadGateway: 502, + ServiceUnavailable: 503, + GatewayTimeout: 504, + HttpVersionNotSupported: 505, + VariantAlsoNegotiates: 506, + InsufficientStorage: 507, + LoopDetected: 508, + NotExtended: 510, + NetworkAuthenticationRequired: 511, + WebServerIsDown: 521, + ConnectionTimedOut: 522, + OriginIsUnreachable: 523, + TimeoutOccurred: 524, + SslHandshakeFailed: 525, + InvalidSslCertificate: 526, +}; + +Object.entries(HttpStatusCode).forEach(([key, value]) => { + HttpStatusCode[value] = key; +}); + +export default HttpStatusCode; diff --git a/node_modules/axios/lib/helpers/README.md b/node_modules/axios/lib/helpers/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4ae34193a1edf855caaf3fc3a3700230934379af --- /dev/null +++ b/node_modules/axios/lib/helpers/README.md @@ -0,0 +1,7 @@ +# axios // helpers + +The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like: + +- Browser polyfills +- Managing cookies +- Parsing HTTP headers diff --git a/node_modules/axios/lib/helpers/ZlibHeaderTransformStream.js b/node_modules/axios/lib/helpers/ZlibHeaderTransformStream.js new file mode 100644 index 0000000000000000000000000000000000000000..c588dede07da0a6c5aa0c4c64fe9df04a256b40f --- /dev/null +++ b/node_modules/axios/lib/helpers/ZlibHeaderTransformStream.js @@ -0,0 +1,29 @@ +'use strict'; + +import stream from 'stream'; + +class ZlibHeaderTransformStream extends stream.Transform { + __transform(chunk, encoding, callback) { + this.push(chunk); + callback(); + } + + _transform(chunk, encoding, callback) { + if (chunk.length !== 0) { + this._transform = this.__transform; + + // Add Default Compression headers if no zlib headers are present + if (chunk[0] !== 120) { + // Hex: 78 + const header = Buffer.alloc(2); + header[0] = 120; // Hex: 78 + header[1] = 156; // Hex: 9C + this.push(header, encoding); + } + } + + this.__transform(chunk, encoding, callback); + } +} + +export default ZlibHeaderTransformStream; diff --git a/node_modules/axios/lib/helpers/bind.js b/node_modules/axios/lib/helpers/bind.js new file mode 100644 index 0000000000000000000000000000000000000000..938da5c1640963c3727aaf7a85b9d148648eaedd --- /dev/null +++ b/node_modules/axios/lib/helpers/bind.js @@ -0,0 +1,14 @@ +'use strict'; + +/** + * Create a bound version of a function with a specified `this` context + * + * @param {Function} fn - The function to bind + * @param {*} thisArg - The value to be passed as the `this` parameter + * @returns {Function} A new function that will call the original function with the specified `this` context + */ +export default function bind(fn, thisArg) { + return function wrap() { + return fn.apply(thisArg, arguments); + }; +} diff --git a/node_modules/axios/lib/helpers/buildURL.js b/node_modules/axios/lib/helpers/buildURL.js new file mode 100644 index 0000000000000000000000000000000000000000..c3606f68fcb370c851b34e4ffc39b9ffda3d2abc --- /dev/null +++ b/node_modules/axios/lib/helpers/buildURL.js @@ -0,0 +1,68 @@ +'use strict'; + +import utils from '../utils.js'; +import AxiosURLSearchParams from './AxiosURLSearchParams.js'; + +/** + * It replaces URL-encoded forms of `:`, `$`, `,`, and spaces with + * their plain counterparts (`:`, `$`, `,`, `+`). + * + * @param {string} val The value to be encoded. + * + * @returns {string} The encoded value. + */ +export function encode(val) { + return encodeURIComponent(val) + .replace(/%3A/gi, ':') + .replace(/%24/g, '$') + .replace(/%2C/gi, ',') + .replace(/%20/g, '+'); +} + +/** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @param {?(object|Function)} options + * + * @returns {string} The formatted url + */ +export default function buildURL(url, params, options) { + if (!params) { + return url; + } + + const _options = utils.isFunction(options) + ? { + serialize: options, + } + : options; + + // Read serializer options pollution-safely: own properties and methods on a + // class/template prototype are honored, but values injected onto a polluted + // Object.prototype are ignored. + const _encode = utils.getSafeProp(_options, 'encode') || encode; + const serializeFn = utils.getSafeProp(_options, 'serialize'); + + let serializedParams; + + if (serializeFn) { + serializedParams = serializeFn(params, _options); + } else { + serializedParams = utils.isURLSearchParams(params) + ? params.toString() + : new AxiosURLSearchParams(params, _options).toString(_encode); + } + + if (serializedParams) { + const hashmarkIndex = url.indexOf('#'); + + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } + + return url; +} diff --git a/node_modules/axios/lib/helpers/callbackify.js b/node_modules/axios/lib/helpers/callbackify.js new file mode 100644 index 0000000000000000000000000000000000000000..e8cea68734dfb16ac11232f841dc9367e63bffe8 --- /dev/null +++ b/node_modules/axios/lib/helpers/callbackify.js @@ -0,0 +1,18 @@ +import utils from '../utils.js'; + +const callbackify = (fn, reducer) => { + return utils.isAsyncFn(fn) + ? function (...args) { + const cb = args.pop(); + fn.apply(this, args).then((value) => { + try { + reducer ? cb(null, ...reducer(value)) : cb(null, value); + } catch (err) { + cb(err); + } + }, cb); + } + : fn; +}; + +export default callbackify; diff --git a/node_modules/axios/lib/helpers/combineURLs.js b/node_modules/axios/lib/helpers/combineURLs.js new file mode 100644 index 0000000000000000000000000000000000000000..9f04f02020a629275d6e90cb8d7cf5c5d13c8f7d --- /dev/null +++ b/node_modules/axios/lib/helpers/combineURLs.js @@ -0,0 +1,15 @@ +'use strict'; + +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * + * @returns {string} The combined URL + */ +export default function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +} diff --git a/node_modules/axios/lib/helpers/composeSignals.js b/node_modules/axios/lib/helpers/composeSignals.js new file mode 100644 index 0000000000000000000000000000000000000000..74e99ed42f78470545ae6cd9b635278a50b23e3c --- /dev/null +++ b/node_modules/axios/lib/helpers/composeSignals.js @@ -0,0 +1,57 @@ +import CanceledError from '../cancel/CanceledError.js'; +import AxiosError from '../core/AxiosError.js'; +import utils from '../utils.js'; + +const composeSignals = (signals, timeout) => { + signals = signals ? signals.filter(Boolean) : []; + + if (!timeout && !signals.length) { + return; + } + + const controller = new AbortController(); + + let aborted = false; + + const onabort = function (reason) { + if (!aborted) { + aborted = true; + unsubscribe(); + const err = reason instanceof Error ? reason : this.reason; + controller.abort( + err instanceof AxiosError + ? err + : new CanceledError(err instanceof Error ? err.message : err) + ); + } + }; + + let timer = + timeout && + setTimeout(() => { + timer = null; + onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT)); + }, timeout); + + const unsubscribe = () => { + if (!signals) { return; } + timer && clearTimeout(timer); + timer = null; + signals.forEach((signal) => { + signal.unsubscribe + ? signal.unsubscribe(onabort) + : signal.removeEventListener('abort', onabort); + }); + signals = null; + }; + + signals.forEach((signal) => signal.addEventListener('abort', onabort)); + + const { signal } = controller; + + signal.unsubscribe = () => utils.asap(unsubscribe); + + return signal; +}; + +export default composeSignals; diff --git a/node_modules/axios/lib/helpers/cookies.js b/node_modules/axios/lib/helpers/cookies.js new file mode 100644 index 0000000000000000000000000000000000000000..3f0baf242117d5c996d368b965acd43d7d89cea0 --- /dev/null +++ b/node_modules/axios/lib/helpers/cookies.js @@ -0,0 +1,60 @@ +import utils from '../utils.js'; +import platform from '../platform/index.js'; + +export default platform.hasStandardBrowserEnv + ? // Standard browser envs support document.cookie + { + write(name, value, expires, path, domain, secure, sameSite) { + if (typeof document === 'undefined') return; + + const cookie = [`${name}=${encodeURIComponent(value)}`]; + + if (utils.isNumber(expires)) { + cookie.push(`expires=${new Date(expires).toUTCString()}`); + } + if (utils.isString(path)) { + cookie.push(`path=${path}`); + } + if (utils.isString(domain)) { + cookie.push(`domain=${domain}`); + } + if (secure === true) { + cookie.push('secure'); + } + if (utils.isString(sameSite)) { + cookie.push(`SameSite=${sameSite}`); + } + + document.cookie = cookie.join('; '); + }, + + read(name) { + if (typeof document === 'undefined') return null; + // Match name=value by splitting on the semicolon separator instead of building a + // RegExp from `name` — interpolating an unescaped string into a RegExp would let + // metacharacters (e.g. `.+?` in an attacker-influenced cookie name) cause ReDoS or + // match the wrong cookie. Browsers may serialize cookie pairs as either ";" or + // "; ", so ignore optional whitespace before each cookie name. + const cookies = document.cookie.split(';'); + for (let i = 0; i < cookies.length; i++) { + const cookie = cookies[i].replace(/^\s+/, ''); + const eq = cookie.indexOf('='); + if (eq !== -1 && cookie.slice(0, eq) === name) { + return decodeURIComponent(cookie.slice(eq + 1)); + } + } + return null; + }, + + remove(name) { + this.write(name, '', Date.now() - 86400000, '/'); + }, + } + : // Non-standard browser env (web workers, react-native) lack needed support. + { + write() {}, + read() { + return null; + }, + remove() {}, + }; diff --git a/node_modules/axios/lib/helpers/deprecatedMethod.js b/node_modules/axios/lib/helpers/deprecatedMethod.js new file mode 100644 index 0000000000000000000000000000000000000000..ec112de211e9995e635180f45273dd6b36340076 --- /dev/null +++ b/node_modules/axios/lib/helpers/deprecatedMethod.js @@ -0,0 +1,31 @@ +'use strict'; + +/*eslint no-console:0*/ + +/** + * Supply a warning to the developer that a method they are using + * has been deprecated. + * + * @param {string} method The name of the deprecated method + * @param {string} [instead] The alternate method to use if applicable + * @param {string} [docs] The documentation URL to get further details + * + * @returns {void} + */ +export default function deprecatedMethod(method, instead, docs) { + try { + console.warn( + 'DEPRECATED method `' + + method + + '`.' + + (instead ? ' Use `' + instead + '` instead.' : '') + + ' This method will be removed in a future release.' + ); + + if (docs) { + console.warn('For more information about usage see ' + docs); + } + } catch (e) { + /* Ignore */ + } +} diff --git a/node_modules/axios/lib/helpers/estimateDataURLDecodedBytes.js b/node_modules/axios/lib/helpers/estimateDataURLDecodedBytes.js new file mode 100644 index 0000000000000000000000000000000000000000..927b755bcae594ae5dfdde95a0af49dbffbb1bbe --- /dev/null +++ b/node_modules/axios/lib/helpers/estimateDataURLDecodedBytes.js @@ -0,0 +1,105 @@ +/** + * Estimate decoded byte length of a data:// URL *without* allocating large buffers. + * - For base64: compute exact decoded size using length and padding; + * handle %XX at the character-count level (no string allocation). + * - For non-base64: compute the exact percent-decoded UTF-8 byte length. + * + * @param {string} url + * @returns {number} + */ +const isHexDigit = (charCode) => + (charCode >= 48 && charCode <= 57) || + (charCode >= 65 && charCode <= 70) || + (charCode >= 97 && charCode <= 102); + +const isPercentEncodedByte = (str, i, len) => + i + 2 < len && isHexDigit(str.charCodeAt(i + 1)) && isHexDigit(str.charCodeAt(i + 2)); + +export default function estimateDataURLDecodedBytes(url) { + if (!url || typeof url !== 'string') return 0; + if (!url.startsWith('data:')) return 0; + + const comma = url.indexOf(','); + if (comma < 0) return 0; + + const meta = url.slice(5, comma); + const body = url.slice(comma + 1); + const isBase64 = /;base64/i.test(meta); + + if (isBase64) { + let effectiveLen = body.length; + const len = body.length; // cache length + + for (let i = 0; i < len; i++) { + if (body.charCodeAt(i) === 37 /* '%' */ && i + 2 < len) { + const a = body.charCodeAt(i + 1); + const b = body.charCodeAt(i + 2); + const isHex = isHexDigit(a) && isHexDigit(b); + + if (isHex) { + effectiveLen -= 2; + i += 2; + } + } + } + + let pad = 0; + let idx = len - 1; + + const tailIsPct3D = (j) => + j >= 2 && + body.charCodeAt(j - 2) === 37 && // '%' + body.charCodeAt(j - 1) === 51 && // '3' + (body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100); // 'D' or 'd' + + if (idx >= 0) { + if (body.charCodeAt(idx) === 61 /* '=' */) { + pad++; + idx--; + } else if (tailIsPct3D(idx)) { + pad++; + idx -= 3; + } + } + + if (pad === 1 && idx >= 0) { + if (body.charCodeAt(idx) === 61 /* '=' */) { + pad++; + } else if (tailIsPct3D(idx)) { + pad++; + } + } + + const groups = Math.floor(effectiveLen / 4); + const bytes = groups * 3 - (pad || 0); + return bytes > 0 ? bytes : 0; + } + + // Compute UTF-8 byte length directly from UTF-16 code units without allocating + // a byte buffer (TextEncoder.encode would defeat the DoS guard on large bodies). + // Valid %XX triplets count as one decoded byte; this matches the bytes that + // decodeURIComponent(body) would produce before Buffer re-encodes the string. + let bytes = 0; + for (let i = 0, len = body.length; i < len; i++) { + const c = body.charCodeAt(i); + if (c === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) { + bytes += 1; + i += 2; + } else if (c < 0x80) { + bytes += 1; + } else if (c < 0x800) { + bytes += 2; + } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < len) { + const next = body.charCodeAt(i + 1); + if (next >= 0xdc00 && next <= 0xdfff) { + bytes += 4; + i++; + } else { + bytes += 3; + } + } else { + bytes += 3; + } + } + return bytes; +} diff --git a/node_modules/axios/lib/helpers/formDataToJSON.js b/node_modules/axios/lib/helpers/formDataToJSON.js new file mode 100644 index 0000000000000000000000000000000000000000..36ef52f26385bf47255d8074e11d70a76cf96181 --- /dev/null +++ b/node_modules/axios/lib/helpers/formDataToJSON.js @@ -0,0 +1,119 @@ +'use strict'; + +import utils from '../utils.js'; +import AxiosError from '../core/AxiosError.js'; +import { DEFAULT_FORM_DATA_MAX_DEPTH } from './toFormData.js'; + +const MAX_DEPTH = DEFAULT_FORM_DATA_MAX_DEPTH; + +function throwIfDepthExceeded(index) { + if (index > MAX_DEPTH) { + throw new AxiosError( + 'FormData field is too deeply nested (' + index + ' levels). Max depth: ' + MAX_DEPTH, + AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED + ); + } +} + +/** + * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z'] + * + * @param {string} name - The name of the property to get. + * + * @returns An array of strings. + */ +function parsePropPath(name) { + // foo[x][y][z] + // foo.x.y.z + // foo-x-y-z + // foo x y z + const path = []; + const pattern = /\w+|\[(\w*)]/g; + let match; + + while ((match = pattern.exec(name)) !== null) { + throwIfDepthExceeded(path.length); + path.push(match[0] === '[]' ? '' : match[1] || match[0]); + } + + return path; +} + +/** + * Convert an array to an object. + * + * @param {Array} arr - The array to convert to an object. + * + * @returns An object with the same keys and values as the array. + */ +function arrayToObject(arr) { + const obj = {}; + const keys = Object.keys(arr); + let i; + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + obj[key] = arr[key]; + } + return obj; +} + +/** + * It takes a FormData object and returns a JavaScript object + * + * @param {string} formData The FormData object to convert to JSON. + * + * @returns {Object | null} The converted object. + */ +function formDataToJSON(formData) { + function buildPath(path, value, target, index) { + throwIfDepthExceeded(index); + + let name = path[index++]; + + if (name === '__proto__') return true; + + const isNumericKey = Number.isFinite(+name); + const isLast = index >= path.length; + name = !name && utils.isArray(target) ? target.length : name; + + if (isLast) { + if (utils.hasOwnProp(target, name)) { + target[name] = utils.isArray(target[name]) + ? target[name].concat(value) + : [target[name], value]; + } else { + target[name] = value; + } + + return !isNumericKey; + } + + if (!utils.hasOwnProp(target, name) || !utils.isObject(target[name])) { + target[name] = []; + } + + const result = buildPath(path, value, target[name], index); + + if (result && utils.isArray(target[name])) { + target[name] = arrayToObject(target[name]); + } + + return !isNumericKey; + } + + if (utils.isFormData(formData) && utils.isFunction(formData.entries)) { + const obj = {}; + + utils.forEachEntry(formData, (name, value) => { + buildPath(parsePropPath(name), value, obj, 0); + }); + + return obj; + } + + return null; +} + +export default formDataToJSON; diff --git a/node_modules/axios/lib/helpers/formDataToStream.js b/node_modules/axios/lib/helpers/formDataToStream.js new file mode 100644 index 0000000000000000000000000000000000000000..17f369dad59fcc09ce659e3a4fc83f7bf0e4ca04 --- /dev/null +++ b/node_modules/axios/lib/helpers/formDataToStream.js @@ -0,0 +1,119 @@ +import util from 'util'; +import { Readable } from 'stream'; +import utils from '../utils.js'; +import readBlob from './readBlob.js'; +import platform from '../platform/index.js'; + +const BOUNDARY_ALPHABET = platform.ALPHABET.ALPHA_DIGIT + '-_'; + +const textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : new util.TextEncoder(); + +const CRLF = '\r\n'; +const CRLF_BYTES = textEncoder.encode(CRLF); +const CRLF_BYTES_COUNT = 2; + +class FormDataPart { + constructor(name, value) { + const { escapeName } = this.constructor; + const isStringValue = utils.isString(value); + + let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${ + !isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : '' + }${CRLF}`; + + if (isStringValue) { + value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF)); + } else { + const safeType = String(value.type || 'application/octet-stream').replace(/[\r\n]/g, ''); + headers += `Content-Type: ${safeType}${CRLF}`; + } + + this.headers = textEncoder.encode(headers + CRLF); + + this.contentLength = isStringValue ? value.byteLength : value.size; + + this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT; + + this.name = name; + this.value = value; + } + + async *encode() { + yield this.headers; + + const { value } = this; + + if (utils.isTypedArray(value)) { + yield value; + } else { + yield* readBlob(value); + } + + yield CRLF_BYTES; + } + + static escapeName(name) { + return String(name).replace( + /[\r\n"]/g, + (match) => + ({ + '\r': '%0D', + '\n': '%0A', + '"': '%22', + })[match] + ); + } +} + +const formDataToStream = (form, headersHandler, options) => { + const { + tag = 'form-data-boundary', + size = 25, + boundary = tag + '-' + platform.generateString(size, BOUNDARY_ALPHABET), + } = options || {}; + + if (!utils.isFormData(form)) { + throw new TypeError('FormData instance required'); + } + + if (boundary.length < 1 || boundary.length > 70) { + throw new Error('boundary must be 1-70 characters long'); + } + + const boundaryBytes = textEncoder.encode('--' + boundary + CRLF); + const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF); + let contentLength = footerBytes.byteLength; + + const parts = Array.from(form.entries()).map(([name, value]) => { + const part = new FormDataPart(name, value); + contentLength += part.size; + return part; + }); + + contentLength += boundaryBytes.byteLength * parts.length; + + contentLength = utils.toFiniteNumber(contentLength); + + const computedHeaders = { + 'Content-Type': `multipart/form-data; boundary=${boundary}`, + }; + + if (Number.isFinite(contentLength)) { + computedHeaders['Content-Length'] = contentLength; + } + + headersHandler && headersHandler(computedHeaders); + + return Readable.from( + (async function* () { + for (const part of parts) { + yield boundaryBytes; + yield* part.encode(); + } + + yield footerBytes; + })() + ); +}; + +export default formDataToStream; diff --git a/node_modules/axios/lib/helpers/fromDataURI.js b/node_modules/axios/lib/helpers/fromDataURI.js new file mode 100644 index 0000000000000000000000000000000000000000..73195889143e3453b24263c096a80595b68d857d --- /dev/null +++ b/node_modules/axios/lib/helpers/fromDataURI.js @@ -0,0 +1,66 @@ +'use strict'; + +import AxiosError from '../core/AxiosError.js'; +import parseProtocol from './parseProtocol.js'; +import platform from '../platform/index.js'; + +// RFC 2397: data:[][;base64], +// mediatype = type/subtype followed by optional ;name=value parameters +const DATA_URL_PATTERN = /^([^,;]+\/[^,;]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/; + +/** + * Parse data uri to a Buffer or Blob + * + * @param {String} uri + * @param {?Boolean} asBlob + * @param {?Object} options + * @param {?Function} options.Blob + * + * @returns {Buffer|Blob} + */ +export default function fromDataURI(uri, asBlob, options) { + const _Blob = (options && options.Blob) || platform.classes.Blob; + const protocol = parseProtocol(uri); + + if (asBlob === undefined && _Blob) { + asBlob = true; + } + + if (protocol === 'data') { + uri = protocol.length ? uri.slice(protocol.length + 1) : uri; + + const match = DATA_URL_PATTERN.exec(uri); + + if (!match) { + throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL); + } + + const type = match[1]; + const params = match[2]; + const encoding = match[3] ? 'base64' : 'utf8'; + const body = match[4]; + + // RFC 2397 section 3: default mediatype is text/plain;charset=US-ASCII + // Bare `data:,` leaves mime undefined; Blob normalises that to "" per spec. + let mime; + if (type) { + mime = params ? type + params : type; + } else if (params) { + mime = 'text/plain' + params; + } + + const buffer = Buffer.from(decodeURIComponent(body), encoding); + + if (asBlob) { + if (!_Blob) { + throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT); + } + + return new _Blob([buffer], { type: mime }); + } + + return buffer; + } + + throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT); +} diff --git a/node_modules/axios/lib/helpers/isAbsoluteURL.js b/node_modules/axios/lib/helpers/isAbsoluteURL.js new file mode 100644 index 0000000000000000000000000000000000000000..c46190020567847180568f5e2c3a17ded8051129 --- /dev/null +++ b/node_modules/axios/lib/helpers/isAbsoluteURL.js @@ -0,0 +1,19 @@ +'use strict'; + +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +export default function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + if (typeof url !== 'string') { + return false; + } + + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); +} diff --git a/node_modules/axios/lib/helpers/isAxiosError.js b/node_modules/axios/lib/helpers/isAxiosError.js new file mode 100644 index 0000000000000000000000000000000000000000..ffba6101b10fdf402caefdd704c11158796540f3 --- /dev/null +++ b/node_modules/axios/lib/helpers/isAxiosError.js @@ -0,0 +1,14 @@ +'use strict'; + +import utils from '../utils.js'; + +/** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ +export default function isAxiosError(payload) { + return utils.isObject(payload) && payload.isAxiosError === true; +} diff --git a/node_modules/axios/lib/helpers/isURLSameOrigin.js b/node_modules/axios/lib/helpers/isURLSameOrigin.js new file mode 100644 index 0000000000000000000000000000000000000000..66af27432d8fafaa6de062f97e429dea8e9647c6 --- /dev/null +++ b/node_modules/axios/lib/helpers/isURLSameOrigin.js @@ -0,0 +1,16 @@ +import platform from '../platform/index.js'; + +export default platform.hasStandardBrowserEnv + ? ((origin, isMSIE) => (url) => { + url = new URL(url, platform.origin); + + return ( + origin.protocol === url.protocol && + origin.host === url.host && + (isMSIE || origin.port === url.port) + ); + })( + new URL(platform.origin), + platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent) + ) + : () => true; diff --git a/node_modules/axios/lib/helpers/null.js b/node_modules/axios/lib/helpers/null.js new file mode 100644 index 0000000000000000000000000000000000000000..b9f82c46434fe514f0c4e20f5e738c077dc6a2d8 --- /dev/null +++ b/node_modules/axios/lib/helpers/null.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line strict +export default null; diff --git a/node_modules/axios/lib/helpers/parseHeaders.js b/node_modules/axios/lib/helpers/parseHeaders.js new file mode 100644 index 0000000000000000000000000000000000000000..fb0eba4454d8f46b1ac6774f6013c7ffc844a9f8 --- /dev/null +++ b/node_modules/axios/lib/helpers/parseHeaders.js @@ -0,0 +1,69 @@ +'use strict'; + +import utils from '../utils.js'; + +// RawAxiosHeaders whose duplicates are ignored by node +// c.f. https://nodejs.org/api/http.html#http_message_headers +const ignoreDuplicateOf = utils.toObjectSet([ + 'age', + 'authorization', + 'content-length', + 'content-type', + 'etag', + 'expires', + 'from', + 'host', + 'if-modified-since', + 'if-unmodified-since', + 'last-modified', + 'location', + 'max-forwards', + 'proxy-authorization', + 'referer', + 'retry-after', + 'user-agent', +]); + +/** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} rawHeaders Headers needing to be parsed + * + * @returns {Object} Headers parsed into an object + */ +export default (rawHeaders) => { + const parsed = {}; + let key; + let val; + let i; + + rawHeaders && + rawHeaders.split('\n').forEach(function parser(line) { + i = line.indexOf(':'); + key = line.substring(0, i).trim().toLowerCase(); + val = line.substring(i + 1).trim(); + + if (!key || (parsed[key] && ignoreDuplicateOf[key])) { + return; + } + + if (key === 'set-cookie') { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + }); + + return parsed; +}; diff --git a/node_modules/axios/lib/helpers/parseProtocol.js b/node_modules/axios/lib/helpers/parseProtocol.js new file mode 100644 index 0000000000000000000000000000000000000000..05a2d6d267e1c881bc3649f518808d160a5c0a73 --- /dev/null +++ b/node_modules/axios/lib/helpers/parseProtocol.js @@ -0,0 +1,6 @@ +'use strict'; + +export default function parseProtocol(url) { + const match = /^([-+\w]{1,25}):(?:\/\/)?/.exec(url); + return (match && match[1]) || ''; +} diff --git a/node_modules/axios/lib/helpers/progressEventReducer.js b/node_modules/axios/lib/helpers/progressEventReducer.js new file mode 100644 index 0000000000000000000000000000000000000000..e2c15c0df4fad4f326bfc334f39afeade948670f --- /dev/null +++ b/node_modules/axios/lib/helpers/progressEventReducer.js @@ -0,0 +1,54 @@ +import speedometer from './speedometer.js'; +import throttle from './throttle.js'; +import utils from '../utils.js'; + +export const progressEventReducer = (listener, isDownloadStream, freq = 3) => { + let bytesNotified = 0; + const _speedometer = speedometer(50, 250); + + return throttle((e) => { + if (!e || typeof e.loaded !== 'number') { + return; + } + const rawLoaded = e.loaded; + const total = e.lengthComputable ? e.total : undefined; + const loaded = total != null ? Math.min(rawLoaded, total) : rawLoaded; + const progressBytes = Math.max(0, loaded - bytesNotified); + const rate = _speedometer(progressBytes); + + bytesNotified = Math.max(bytesNotified, loaded); + + const data = { + loaded, + total, + progress: total ? loaded / total : undefined, + bytes: progressBytes, + rate: rate ? rate : undefined, + estimated: rate && total ? (total - loaded) / rate : undefined, + event: e, + lengthComputable: total != null, + [isDownloadStream ? 'download' : 'upload']: true, + }; + + listener(data); + }, freq); +}; + +export const progressEventDecorator = (total, throttled) => { + const lengthComputable = total != null; + + return [ + (loaded) => + throttled[0]({ + lengthComputable, + total, + loaded, + }), + throttled[1], + ]; +}; + +export const asyncDecorator = + (fn) => + (...args) => + utils.asap(() => fn(...args)); diff --git a/node_modules/axios/lib/helpers/readBlob.js b/node_modules/axios/lib/helpers/readBlob.js new file mode 100644 index 0000000000000000000000000000000000000000..87d0ea8d259daa6e1d2eee7b48799aca0076902d --- /dev/null +++ b/node_modules/axios/lib/helpers/readBlob.js @@ -0,0 +1,15 @@ +const { asyncIterator } = Symbol; + +const readBlob = async function* (blob) { + if (blob.stream) { + yield* blob.stream(); + } else if (blob.arrayBuffer) { + yield await blob.arrayBuffer(); + } else if (blob[asyncIterator]) { + yield* blob[asyncIterator](); + } else { + yield blob; + } +}; + +export default readBlob; diff --git a/node_modules/axios/lib/helpers/resolveConfig.js b/node_modules/axios/lib/helpers/resolveConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..8920b632db9e7fe4a235a03c0910fc7973786ed4 --- /dev/null +++ b/node_modules/axios/lib/helpers/resolveConfig.js @@ -0,0 +1,114 @@ +import platform from '../platform/index.js'; +import utils from '../utils.js'; +import isURLSameOrigin from './isURLSameOrigin.js'; +import cookies from './cookies.js'; +import buildFullPath from '../core/buildFullPath.js'; +import mergeConfig from '../core/mergeConfig.js'; +import AxiosHeaders from '../core/AxiosHeaders.js'; +import buildURL from './buildURL.js'; + +const FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length']; + +function setFormDataHeaders(headers, formHeaders, policy) { + if (policy !== 'content-only') { + headers.set(formHeaders); + return; + } + + Object.entries(formHeaders).forEach(([key, val]) => { + if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) { + headers.set(key, val); + } + }); +} + +/** + * Encode a UTF-8 string to a Latin-1 byte string for use with btoa(). + * This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern. + * + * @param {string} str The string to encode + * + * @returns {string} UTF-8 bytes as a Latin-1 string + */ +const encodeUTF8 = (str) => + encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) => + String.fromCharCode(parseInt(hex, 16)) + ); + +function resolveConfig(config) { + const newConfig = mergeConfig({}, config); + + // Read only own properties to prevent prototype pollution gadgets + // (e.g. Object.prototype.baseURL = 'https://evil.com'). + const own = (key) => (utils.hasOwnProp(newConfig, key) ? newConfig[key] : undefined); + + const data = own('data'); + let withXSRFToken = own('withXSRFToken'); + const xsrfHeaderName = own('xsrfHeaderName'); + const xsrfCookieName = own('xsrfCookieName'); + let headers = own('headers'); + const auth = own('auth'); + const baseURL = own('baseURL'); + const allowAbsoluteUrls = own('allowAbsoluteUrls'); + const url = own('url'); + + newConfig.headers = headers = AxiosHeaders.from(headers); + + newConfig.url = buildURL( + buildFullPath(baseURL, url, allowAbsoluteUrls, newConfig), + own('params'), + own('paramsSerializer') + ); + + // HTTP basic authentication + if (auth) { + const username = utils.getSafeProp(auth, 'username') || ''; + const password = utils.getSafeProp(auth, 'password') || ''; + + headers.set( + 'Authorization', + 'Basic ' + btoa(username + ':' + (password ? encodeUTF8(password) : '')) + ); + } + + if (utils.isFormData(data)) { + if ( + platform.hasStandardBrowserEnv || + platform.hasStandardBrowserWebWorkerEnv || + utils.isReactNative(data) + ) { + headers.setContentType(undefined); // browser/web worker/RN handles it + } else if (utils.isFunction(data.getHeaders)) { + // Node.js FormData (like form-data package) + setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy')); + } + } + + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + + if (platform.hasStandardBrowserEnv) { + if (utils.isFunction(withXSRFToken)) { + withXSRFToken = withXSRFToken(newConfig); + } + + // Strict boolean check — prevents proto-pollution gadgets (e.g. Object.prototype.withXSRFToken = 1) + // and misconfigurations (e.g. "false") from short-circuiting the same-origin check and leaking + // the XSRF token cross-origin. + const shouldSendXSRF = + withXSRFToken === true || (withXSRFToken == null && isURLSameOrigin(newConfig.url)); + + if (shouldSendXSRF) { + const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); + + if (xsrfValue) { + headers.set(xsrfHeaderName, xsrfValue); + } + } + } + + return newConfig; +} + +export default resolveConfig; diff --git a/node_modules/axios/lib/helpers/sanitizeHeaderValue.js b/node_modules/axios/lib/helpers/sanitizeHeaderValue.js new file mode 100644 index 0000000000000000000000000000000000000000..0462fc0e4a8d27c338d9ace78f03e9c762de2d04 --- /dev/null +++ b/node_modules/axios/lib/helpers/sanitizeHeaderValue.js @@ -0,0 +1,60 @@ +'use strict'; + +import utils from '../utils.js'; + +function trimSPorHTAB(str) { + let start = 0; + let end = str.length; + + while (start < end) { + const code = str.charCodeAt(start); + + if (code !== 0x09 && code !== 0x20) { + break; + } + + start += 1; + } + + while (end > start) { + const code = str.charCodeAt(end - 1); + + if (code !== 0x09 && code !== 0x20) { + break; + } + + end -= 1; + } + + return start === 0 && end === str.length ? str : str.slice(start, end); +} + +// The control-code ranges are intentional: header sanitization strips C0/DEL bytes. +// eslint-disable-next-line no-control-regex +const INVALID_UNICODE_HEADER_VALUE_CHARS = new RegExp('[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+', 'g'); +// eslint-disable-next-line no-control-regex +const INVALID_BYTE_STRING_HEADER_VALUE_CHARS = new RegExp('[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+', 'g'); + +function sanitizeValue(value, invalidChars) { + if (utils.isArray(value)) { + return value.map((item) => sanitizeValue(item, invalidChars)); + } + + return trimSPorHTAB(String(value).replace(invalidChars, '')); +} + +export const sanitizeHeaderValue = (value) => + sanitizeValue(value, INVALID_UNICODE_HEADER_VALUE_CHARS); + +export const sanitizeByteStringHeaderValue = (value) => + sanitizeValue(value, INVALID_BYTE_STRING_HEADER_VALUE_CHARS); + +export function toByteStringHeaderObject(headers) { + const byteStringHeaders = Object.create(null); + + utils.forEach(headers.toJSON(), (value, header) => { + byteStringHeaders[header] = sanitizeByteStringHeaderValue(value); + }); + + return byteStringHeaders; +} diff --git a/node_modules/axios/lib/helpers/shouldBypassProxy.js b/node_modules/axios/lib/helpers/shouldBypassProxy.js new file mode 100644 index 0000000000000000000000000000000000000000..0d5cc7fabfc627ee72a4d94f5c82039b9a661489 --- /dev/null +++ b/node_modules/axios/lib/helpers/shouldBypassProxy.js @@ -0,0 +1,210 @@ +const LOOPBACK_HOSTNAMES = new Set(['localhost', '0.0.0.0']); + +const isIPv4Loopback = (host) => { + const parts = host.split('.'); + if (parts.length !== 4) return false; + if (parts[0] !== '127') return false; + return parts.every((p) => /^\d+$/.test(p) && Number(p) >= 0 && Number(p) <= 255); +}; + +const isIPv6ZeroGroup = (group) => /^0{1,4}$/.test(group); + +// The unspecified address (IPv4 0.0.0.0 / IPv6 ::) resolves to the local host +// for outbound connections, so treat it as loopback-equivalent for NO_PROXY +// matching. 0.0.0.0 is covered by LOOPBACK_HOSTNAMES; this handles compressed +// and full IPv6 all-zero forms so both families bypass symmetrically. +const isIPv6Unspecified = (host) => { + if (host === '::') return true; + + const compressionIndex = host.indexOf('::'); + + if (compressionIndex !== -1) { + if (compressionIndex !== host.lastIndexOf('::')) return false; + + const left = host.slice(0, compressionIndex); + const right = host.slice(compressionIndex + 2); + const leftGroups = left ? left.split(':') : []; + const rightGroups = right ? right.split(':') : []; + const explicitGroups = leftGroups.length + rightGroups.length; + + return ( + explicitGroups < 8 && + leftGroups.every(isIPv6ZeroGroup) && + rightGroups.every(isIPv6ZeroGroup) + ); + } + + const groups = host.split(':'); + return groups.length === 8 && groups.every(isIPv6ZeroGroup); +}; + +const isIPv6Loopback = (host) => { + // Collapse all-zero groups: any form of ::1 / 0:0:...:0:1 + // First, strip any leading "::" by normalising with Set lookup of common forms, + // then fall back to structural check. + if (host === '::1') return true; + + // Check IPv4-mapped IPv6 loopback: ::ffff: or ::ffff: + // Node's URL parser normalises ::ffff:127.0.0.1 → ::ffff:7f00:1 + const v4MappedDotted = host.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i); + if (v4MappedDotted) return isIPv4Loopback(v4MappedDotted[1]); + + const v4MappedHex = host.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i); + if (v4MappedHex) { + const high = parseInt(v4MappedHex[1], 16); + // High 16 bits must start with 127 (0x7f) — i.e. 0x7f00..0x7fff + return high >= 0x7f00 && high <= 0x7fff; + } + + // Full-form ::1 variants: any number of zero groups followed by trailing 1 + // e.g. 0:0:0:0:0:0:0:1, 0000:...:0001 + const groups = host.split(':'); + if (groups.length === 8) { + for (let i = 0; i < 7; i++) { + if (!/^0+$/.test(groups[i])) return false; + } + return /^0*1$/.test(groups[7]); + } + + return false; +}; + +const isLoopback = (host) => { + if (!host) return false; + if (LOOPBACK_HOSTNAMES.has(host)) return true; + if (isIPv4Loopback(host)) return true; + if (isIPv6Unspecified(host)) return true; + return isIPv6Loopback(host); +}; + +const DEFAULT_PORTS = { + http: 80, + https: 443, + ws: 80, + wss: 443, + ftp: 21, +}; + +const parseNoProxyEntry = (entry) => { + let entryHost = entry; + let entryPort = 0; + + if (entryHost.charAt(0) === '[') { + const bracketIndex = entryHost.indexOf(']'); + + if (bracketIndex !== -1) { + const host = entryHost.slice(1, bracketIndex); + const rest = entryHost.slice(bracketIndex + 1); + + if (rest.charAt(0) === ':' && /^\d+$/.test(rest.slice(1))) { + entryPort = Number.parseInt(rest.slice(1), 10); + } + + return [host, entryPort]; + } + } + + const firstColon = entryHost.indexOf(':'); + const lastColon = entryHost.lastIndexOf(':'); + + if ( + firstColon !== -1 && + firstColon === lastColon && + /^\d+$/.test(entryHost.slice(lastColon + 1)) + ) { + entryPort = Number.parseInt(entryHost.slice(lastColon + 1), 10); + entryHost = entryHost.slice(0, lastColon); + } + + return [entryHost, entryPort]; +}; + +// Convert IPv4-mapped IPv6 (::ffff:0:0/96 prefix) to IPv4 dotted form so both +// sides of a NO_PROXY comparison see the same canonical address. Without this, +// `NO_PROXY=192.168.1.5` would not match a request to `http://[::ffff:192.168.1.5]/` +// (Node's URL parser normalises that to `[::ffff:c0a8:105]`), and vice-versa, +// allowing the proxy-bypass policy to be circumvented by using the alternate +// representation. Returns the input unchanged when not IPv4-mapped. +const IPV4_MAPPED_DOTTED_RE = /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:(\d+\.\d+\.\d+\.\d+)$/i; +const IPV4_MAPPED_HEX_RE = /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i; + +const unmapIPv4MappedIPv6 = (host) => { + if (typeof host !== 'string' || host.indexOf(':') === -1) return host; + + const dotted = host.match(IPV4_MAPPED_DOTTED_RE); + if (dotted) return dotted[1]; + + const hex = host.match(IPV4_MAPPED_HEX_RE); + if (hex) { + const high = parseInt(hex[1], 16); + const low = parseInt(hex[2], 16); + return `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`; + } + + return host; +}; + +const normalizeNoProxyHost = (hostname) => { + if (!hostname) { + return hostname; + } + + if (hostname.charAt(0) === '[' && hostname.charAt(hostname.length - 1) === ']') { + hostname = hostname.slice(1, -1); + } + + return unmapIPv4MappedIPv6(hostname.replace(/\.+$/, '')); +}; + +export default function shouldBypassProxy(location) { + let parsed; + + try { + parsed = new URL(location); + } catch (_err) { + return false; + } + + const noProxy = (process.env.no_proxy || process.env.NO_PROXY || '').toLowerCase(); + + if (!noProxy) { + return false; + } + + if (noProxy === '*') { + return true; + } + + const port = + Number.parseInt(parsed.port, 10) || DEFAULT_PORTS[parsed.protocol.split(':', 1)[0]] || 0; + + const hostname = normalizeNoProxyHost(parsed.hostname.toLowerCase()); + + return noProxy.split(/[\s,]+/).some((entry) => { + if (!entry) { + return false; + } + + let [entryHost, entryPort] = parseNoProxyEntry(entry); + + entryHost = normalizeNoProxyHost(entryHost); + + if (!entryHost) { + return false; + } + + if (entryPort && entryPort !== port) { + return false; + } + + if (entryHost.charAt(0) === '*') { + entryHost = entryHost.slice(1); + } + + if (entryHost.charAt(0) === '.') { + return hostname.endsWith(entryHost); + } + + return hostname === entryHost || (isLoopback(hostname) && isLoopback(entryHost)); + }); +} diff --git a/node_modules/axios/lib/helpers/speedometer.js b/node_modules/axios/lib/helpers/speedometer.js new file mode 100644 index 0000000000000000000000000000000000000000..566a1fff8615290e1d57823ef468878cbeeb1e90 --- /dev/null +++ b/node_modules/axios/lib/helpers/speedometer.js @@ -0,0 +1,55 @@ +'use strict'; + +/** + * Calculate data maxRate + * @param {Number} [samplesCount= 10] + * @param {Number} [min= 1000] + * @returns {Function} + */ +function speedometer(samplesCount, min) { + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; + + min = min !== undefined ? min : 1000; + + return function push(chunkLength) { + const now = Date.now(); + + const startedAt = timestamps[tail]; + + if (!firstSampleTS) { + firstSampleTS = now; + } + + bytes[head] = chunkLength; + timestamps[head] = now; + + let i = tail; + let bytesCount = 0; + + while (i !== head) { + bytesCount += bytes[i++]; + i = i % samplesCount; + } + + head = (head + 1) % samplesCount; + + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + + if (now - firstSampleTS < min) { + return; + } + + const passed = startedAt && now - startedAt; + + return passed ? Math.round((bytesCount * 1000) / passed) : undefined; + }; +} + +export default speedometer; diff --git a/node_modules/axios/lib/helpers/spread.js b/node_modules/axios/lib/helpers/spread.js new file mode 100644 index 0000000000000000000000000000000000000000..2e72fc88f23fd7b3c4b516e5510c3eb9c82c384d --- /dev/null +++ b/node_modules/axios/lib/helpers/spread.js @@ -0,0 +1,28 @@ +'use strict'; + +/** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * const args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * + * @returns {Function} + */ +export default function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +} diff --git a/node_modules/axios/lib/helpers/throttle.js b/node_modules/axios/lib/helpers/throttle.js new file mode 100644 index 0000000000000000000000000000000000000000..fbef472c516c96696bbd93c5506064ae08b7f241 --- /dev/null +++ b/node_modules/axios/lib/helpers/throttle.js @@ -0,0 +1,44 @@ +/** + * Throttle decorator + * @param {Function} fn + * @param {Number} freq + * @return {Function} + */ +function throttle(fn, freq) { + let timestamp = 0; + let threshold = 1000 / freq; + let lastArgs; + let timer; + + const invoke = (args, now = Date.now()) => { + timestamp = now; + lastArgs = null; + if (timer) { + clearTimeout(timer); + timer = null; + } + fn(...args); + }; + + const throttled = (...args) => { + const now = Date.now(); + const passed = now - timestamp; + if (passed >= threshold) { + invoke(args, now); + } else { + lastArgs = args; + if (!timer) { + timer = setTimeout(() => { + timer = null; + invoke(lastArgs); + }, threshold - passed); + } + } + }; + + const flush = () => lastArgs && invoke(lastArgs); + + return [throttled, flush]; +} + +export default throttle; diff --git a/node_modules/axios/lib/helpers/toFormData.js b/node_modules/axios/lib/helpers/toFormData.js new file mode 100644 index 0000000000000000000000000000000000000000..b63fc2436bd2659e707c91aaa3361a0c8be284b1 --- /dev/null +++ b/node_modules/axios/lib/helpers/toFormData.js @@ -0,0 +1,279 @@ +'use strict'; + +import utils from '../utils.js'; +import AxiosError from '../core/AxiosError.js'; +// temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored +import PlatformFormData from '../platform/node/classes/FormData.js'; + +// Default nesting limit shared with the inverse transform (formDataToJSON) so +// the FormData <-> JSON round-trip stays symmetric. +export const DEFAULT_FORM_DATA_MAX_DEPTH = 100; + +/** + * Determines if the given thing is a array or js object. + * + * @param {string} thing - The object or array to be visited. + * + * @returns {boolean} + */ +function isVisitable(thing) { + return utils.isPlainObject(thing) || utils.isArray(thing); +} + +/** + * It removes the brackets from the end of a string + * + * @param {string} key - The key of the parameter. + * + * @returns {string} the key without the brackets. + */ +function removeBrackets(key) { + return utils.endsWith(key, '[]') ? key.slice(0, -2) : key; +} + +/** + * It takes a path, a key, and a boolean, and returns a string + * + * @param {string} path - The path to the current key. + * @param {string} key - The key of the current object being iterated over. + * @param {string} dots - If true, the key will be rendered with dots instead of brackets. + * + * @returns {string} The path to the current key. + */ +function renderKey(path, key, dots) { + if (!path) return key; + return path + .concat(key) + .map(function each(token, i) { + // eslint-disable-next-line no-param-reassign + token = removeBrackets(token); + return !dots && i ? '[' + token + ']' : token; + }) + .join(dots ? '.' : ''); +} + +/** + * If the array is an array and none of its elements are visitable, then it's a flat array. + * + * @param {Array} arr - The array to check + * + * @returns {boolean} + */ +function isFlatArray(arr) { + return utils.isArray(arr) && !arr.some(isVisitable); +} + +const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) { + return /^is[A-Z]/.test(prop); +}); + +/** + * Convert a data object to FormData + * + * @param {Object} obj + * @param {?Object} [formData] + * @param {?Object} [options] + * @param {Function} [options.visitor] + * @param {Boolean} [options.metaTokens = true] + * @param {Boolean} [options.dots = false] + * @param {?Boolean} [options.indexes = false] + * + * @returns {Object} + **/ + +/** + * It converts an object into a FormData object + * + * @param {Object} obj - The object to convert to form data. + * @param {string} formData - The FormData object to append to. + * @param {Object} options + * + * @returns + */ +function toFormData(obj, formData, options) { + if (!utils.isObject(obj)) { + throw new TypeError('target must be an object'); + } + + // eslint-disable-next-line no-param-reassign + formData = formData || new (PlatformFormData || FormData)(); + + // eslint-disable-next-line no-param-reassign + options = utils.toFlatObject( + options, + { + metaTokens: true, + dots: false, + indexes: false, + }, + false, + function defined(option, source) { + // eslint-disable-next-line no-eq-null,eqeqeq + return !utils.isUndefined(source[option]); + } + ); + + const metaTokens = options.metaTokens; + // eslint-disable-next-line no-use-before-define + const visitor = options.visitor || defaultVisitor; + const dots = options.dots; + const indexes = options.indexes; + const _Blob = options.Blob || (typeof Blob !== 'undefined' && Blob); + const maxDepth = options.maxDepth === undefined ? DEFAULT_FORM_DATA_MAX_DEPTH : options.maxDepth; + const useBlob = _Blob && utils.isSpecCompliantForm(formData); + const stack = []; + + if (!utils.isFunction(visitor)) { + throw new TypeError('visitor must be a function'); + } + + function convertValue(value) { + if (value === null) return ''; + + if (utils.isDate(value)) { + return value.toISOString(); + } + + if (utils.isBoolean(value)) { + return value.toString(); + } + + if (!useBlob && utils.isBlob(value)) { + throw new AxiosError('Blob is not supported. Use a Buffer instead.'); + } + + if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) { + return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); + } + + return value; + } + + function throwIfMaxDepthExceeded(depth) { + if (depth > maxDepth) { + throw new AxiosError( + 'Object is too deeply nested (' + depth + ' levels). Max depth: ' + maxDepth, + AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED + ); + } + } + + function stringifyWithDepthLimit(value, depth) { + if (maxDepth === Infinity) { + return JSON.stringify(value); + } + + const ancestors = []; + + return JSON.stringify(value, function limitDepth(_key, currentValue) { + if (!utils.isObject(currentValue)) { + return currentValue; + } + + while (ancestors.length && ancestors[ancestors.length - 1] !== this) { + ancestors.pop(); + } + + ancestors.push(currentValue); + throwIfMaxDepthExceeded(depth + ancestors.length - 1); + + return currentValue; + }); + } + + /** + * Default visitor. + * + * @param {*} value + * @param {String|Number} key + * @param {Array} path + * @this {FormData} + * + * @returns {boolean} return true to visit the each prop of the value recursively + */ + function defaultVisitor(value, key, path) { + let arr = value; + + if (utils.isReactNative(formData) && utils.isReactNativeBlob(value)) { + formData.append(renderKey(path, key, dots), convertValue(value)); + return false; + } + + if (value && !path && typeof value === 'object') { + if (utils.endsWith(key, '{}')) { + // eslint-disable-next-line no-param-reassign + key = metaTokens ? key : key.slice(0, -2); + // eslint-disable-next-line no-param-reassign + value = stringifyWithDepthLimit(value, 1); + } else if ( + (utils.isArray(value) && isFlatArray(value)) || + ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value))) + ) { + // eslint-disable-next-line no-param-reassign + key = removeBrackets(key); + + arr.forEach(function each(el, index) { + !(utils.isUndefined(el) || el === null) && + formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true + ? renderKey([key], index, dots) + : indexes === null + ? key + : key + '[]', + convertValue(el) + ); + }); + return false; + } + } + + if (isVisitable(value)) { + return true; + } + + formData.append(renderKey(path, key, dots), convertValue(value)); + + return false; + } + + const exposedHelpers = Object.assign(predicates, { + defaultVisitor, + convertValue, + isVisitable, + }); + + function build(value, path, depth = 0) { + if (utils.isUndefined(value)) return; + + throwIfMaxDepthExceeded(depth); + + if (stack.indexOf(value) !== -1) { + throw new Error('Circular reference detected in ' + path.join('.')); + } + + stack.push(value); + + utils.forEach(value, function each(el, key) { + const result = + !(utils.isUndefined(el) || el === null) && + visitor.call(formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers); + + if (result === true) { + build(el, path ? path.concat(key) : [key], depth + 1); + } + }); + + stack.pop(); + } + + if (!utils.isObject(obj)) { + throw new TypeError('data must be an object'); + } + + build(obj); + + return formData; +} + +export default toFormData; diff --git a/node_modules/axios/lib/helpers/toURLEncodedForm.js b/node_modules/axios/lib/helpers/toURLEncodedForm.js new file mode 100644 index 0000000000000000000000000000000000000000..749e13a61624a73d6e556f6b17c349fc0d705761 --- /dev/null +++ b/node_modules/axios/lib/helpers/toURLEncodedForm.js @@ -0,0 +1,19 @@ +'use strict'; + +import utils from '../utils.js'; +import toFormData from './toFormData.js'; +import platform from '../platform/index.js'; + +export default function toURLEncodedForm(data, options) { + return toFormData(data, new platform.classes.URLSearchParams(), { + visitor: function (value, key, path, helpers) { + if (platform.isNode && utils.isBuffer(value)) { + this.append(key, value.toString('base64')); + return false; + } + + return helpers.defaultVisitor.apply(this, arguments); + }, + ...options, + }); +} diff --git a/node_modules/axios/lib/helpers/trackStream.js b/node_modules/axios/lib/helpers/trackStream.js new file mode 100644 index 0000000000000000000000000000000000000000..c75eace5336da15082aec4e8ab667ed4506af27a --- /dev/null +++ b/node_modules/axios/lib/helpers/trackStream.js @@ -0,0 +1,89 @@ +export const streamChunk = function* (chunk, chunkSize) { + let len = chunk.byteLength; + + if (!chunkSize || len < chunkSize) { + yield chunk; + return; + } + + let pos = 0; + let end; + + while (pos < len) { + end = pos + chunkSize; + yield chunk.slice(pos, end); + pos = end; + } +}; + +export const readBytes = async function* (iterable, chunkSize) { + for await (const chunk of readStream(iterable)) { + yield* streamChunk(chunk, chunkSize); + } +}; + +const readStream = async function* (stream) { + if (stream[Symbol.asyncIterator]) { + yield* stream; + return; + } + + const reader = stream.getReader(); + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) { + break; + } + yield value; + } + } finally { + await reader.cancel(); + } +}; + +export const trackStream = (stream, chunkSize, onProgress, onFinish) => { + const iterator = readBytes(stream, chunkSize); + + let bytes = 0; + let done; + let _onFinish = (e) => { + if (!done) { + done = true; + onFinish && onFinish(e); + } + }; + + return new ReadableStream( + { + async pull(controller) { + try { + const { done, value } = await iterator.next(); + + if (done) { + _onFinish(); + controller.close(); + return; + } + + let len = value.byteLength; + if (onProgress) { + let loadedBytes = (bytes += len); + onProgress(loadedBytes); + } + controller.enqueue(new Uint8Array(value)); + } catch (err) { + _onFinish(err); + throw err; + } + }, + cancel(reason) { + _onFinish(reason); + return iterator.return(); + }, + }, + { + highWaterMark: 2, + } + ); +}; diff --git a/node_modules/axios/lib/helpers/validator.js b/node_modules/axios/lib/helpers/validator.js new file mode 100644 index 0000000000000000000000000000000000000000..077f34d079619097dd2948c7b8b03391cc504037 --- /dev/null +++ b/node_modules/axios/lib/helpers/validator.js @@ -0,0 +1,112 @@ +'use strict'; + +import { VERSION } from '../env/data.js'; +import AxiosError from '../core/AxiosError.js'; + +const validators = {}; + +// eslint-disable-next-line func-names +['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => { + validators[type] = function validator(thing) { + return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; + }; +}); + +const deprecatedWarnings = {}; + +/** + * Transitional option validator + * + * @param {function|boolean?} validator - set to false if the transitional option has been removed + * @param {string?} version - deprecated version / removed since version + * @param {string?} message - some message with additional info + * + * @returns {function} + */ +validators.transitional = function transitional(validator, version, message) { + function formatMessage(opt, desc) { + return ( + '[Axios v' + + VERSION + + "] Transitional option '" + + opt + + "'" + + desc + + (message ? '. ' + message : '') + ); + } + + // eslint-disable-next-line func-names + return (value, opt, opts) => { + if (validator === false) { + throw new AxiosError( + formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), + AxiosError.ERR_DEPRECATED + ); + } + + if (version && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + // eslint-disable-next-line no-console + console.warn( + formatMessage( + opt, + ' has been deprecated since v' + version + ' and will be removed in the near future' + ) + ); + } + + return validator ? validator(value, opt, opts) : true; + }; +}; + +validators.spelling = function spelling(correctSpelling) { + return (value, opt) => { + // eslint-disable-next-line no-console + console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); + return true; + }; +}; + +/** + * Assert object's properties type + * + * @param {object} options + * @param {object} schema + * @param {boolean?} allowUnknown + * + * @returns {object} + */ + +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== 'object') { + throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); + } + const keys = Object.keys(options); + let i = keys.length; + while (i-- > 0) { + const opt = keys[i]; + // Use hasOwnProperty so a polluted Object.prototype. cannot supply + // a non-function validator and cause a TypeError. + const validator = Object.prototype.hasOwnProperty.call(schema, opt) ? schema[opt] : undefined; + if (validator) { + const value = options[opt]; + const result = value === undefined || validator(value, opt, options); + if (result !== true) { + throw new AxiosError( + 'option ' + opt + ' must be ' + result, + AxiosError.ERR_BAD_OPTION_VALUE + ); + } + continue; + } + if (allowUnknown !== true) { + throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); + } + } +} + +export default { + assertOptions, + validators, +}; diff --git a/node_modules/axios/lib/platform/browser/classes/Blob.js b/node_modules/axios/lib/platform/browser/classes/Blob.js new file mode 100644 index 0000000000000000000000000000000000000000..9ec4af87861eefb475171de452739c51ad0c4a14 --- /dev/null +++ b/node_modules/axios/lib/platform/browser/classes/Blob.js @@ -0,0 +1,3 @@ +'use strict'; + +export default typeof Blob !== 'undefined' ? Blob : null; diff --git a/node_modules/axios/lib/platform/browser/classes/FormData.js b/node_modules/axios/lib/platform/browser/classes/FormData.js new file mode 100644 index 0000000000000000000000000000000000000000..f36d31b29eba0d79b16f3f08b5477dd473e2c18d --- /dev/null +++ b/node_modules/axios/lib/platform/browser/classes/FormData.js @@ -0,0 +1,3 @@ +'use strict'; + +export default typeof FormData !== 'undefined' ? FormData : null; diff --git a/node_modules/axios/lib/platform/browser/classes/URLSearchParams.js b/node_modules/axios/lib/platform/browser/classes/URLSearchParams.js new file mode 100644 index 0000000000000000000000000000000000000000..b7dae9533e1afd95f3b9740dc77ff494f496716e --- /dev/null +++ b/node_modules/axios/lib/platform/browser/classes/URLSearchParams.js @@ -0,0 +1,4 @@ +'use strict'; + +import AxiosURLSearchParams from '../../../helpers/AxiosURLSearchParams.js'; +export default typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams; diff --git a/node_modules/axios/lib/platform/browser/index.js b/node_modules/axios/lib/platform/browser/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8e5f99cffef7135c3f1d8f815aa0df244f4f0244 --- /dev/null +++ b/node_modules/axios/lib/platform/browser/index.js @@ -0,0 +1,13 @@ +import URLSearchParams from './classes/URLSearchParams.js'; +import FormData from './classes/FormData.js'; +import Blob from './classes/Blob.js'; + +export default { + isBrowser: true, + classes: { + URLSearchParams, + FormData, + Blob, + }, + protocols: ['http', 'https', 'file', 'blob', 'url', 'data'], +}; diff --git a/node_modules/axios/lib/platform/common/utils.js b/node_modules/axios/lib/platform/common/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..e4dfe4693fc4e415c2d35bf2c6ab9a1580a25e9b --- /dev/null +++ b/node_modules/axios/lib/platform/common/utils.js @@ -0,0 +1,52 @@ +const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined'; + +const _navigator = (typeof navigator === 'object' && navigator) || undefined; + +/** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' + * + * @returns {boolean} + */ +const hasStandardBrowserEnv = + hasBrowserEnv && + (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0); + +/** + * Determine if we're running in a standard browser webWorker environment + * + * Although the `isStandardBrowserEnv` method indicates that + * `allows axios to run in a web worker`, the WebWorker will still be + * filtered out due to its judgment standard + * `typeof window !== 'undefined' && typeof document !== 'undefined'`. + * This leads to a problem when axios post `FormData` in webWorker + */ +const hasStandardBrowserWebWorkerEnv = (() => { + return ( + typeof WorkerGlobalScope !== 'undefined' && + // eslint-disable-next-line no-undef + self instanceof WorkerGlobalScope && + typeof self.importScripts === 'function' + ); +})(); + +const origin = (hasBrowserEnv && window.location.href) || 'http://localhost'; + +export { + hasBrowserEnv, + hasStandardBrowserWebWorkerEnv, + hasStandardBrowserEnv, + _navigator as navigator, + origin, +}; diff --git a/node_modules/axios/lib/platform/index.js b/node_modules/axios/lib/platform/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e1094abfb533f41a0f65caad7cdcdddf33435f4e --- /dev/null +++ b/node_modules/axios/lib/platform/index.js @@ -0,0 +1,7 @@ +import platform from './node/index.js'; +import * as utils from './common/utils.js'; + +export default { + ...utils, + ...platform, +}; diff --git a/node_modules/axios/lib/platform/node/classes/FormData.js b/node_modules/axios/lib/platform/node/classes/FormData.js new file mode 100644 index 0000000000000000000000000000000000000000..b07f9476daa615b60e163a63debe2b70a8c7eacc --- /dev/null +++ b/node_modules/axios/lib/platform/node/classes/FormData.js @@ -0,0 +1,3 @@ +import FormData from 'form-data'; + +export default FormData; diff --git a/node_modules/axios/lib/platform/node/classes/URLSearchParams.js b/node_modules/axios/lib/platform/node/classes/URLSearchParams.js new file mode 100644 index 0000000000000000000000000000000000000000..fba584289ac345f64e2e92ee7fa376a949e6ee88 --- /dev/null +++ b/node_modules/axios/lib/platform/node/classes/URLSearchParams.js @@ -0,0 +1,4 @@ +'use strict'; + +import url from 'url'; +export default url.URLSearchParams; diff --git a/node_modules/axios/lib/platform/node/index.js b/node_modules/axios/lib/platform/node/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9979a715f23136a5433f6aeef2f2dee6b06bf865 --- /dev/null +++ b/node_modules/axios/lib/platform/node/index.js @@ -0,0 +1,37 @@ +import crypto from 'crypto'; +import URLSearchParams from './classes/URLSearchParams.js'; +import FormData from './classes/FormData.js'; + +const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; + +const DIGIT = '0123456789'; + +const ALPHABET = { + DIGIT, + ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT, +}; + +const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { + let str = ''; + const { length } = alphabet; + const randomValues = new Uint32Array(size); + crypto.randomFillSync(randomValues); + for (let i = 0; i < size; i++) { + str += alphabet[randomValues[i] % length]; + } + + return str; +}; + +export default { + isNode: true, + classes: { + URLSearchParams, + FormData, + Blob: (typeof Blob !== 'undefined' && Blob) || null, + }, + ALPHABET, + generateString, + protocols: ['http', 'https', 'file', 'data'], +}; diff --git a/node_modules/axios/lib/utils.js b/node_modules/axios/lib/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..6847f70a7652a9952ec82299819c8b9a1e243587 --- /dev/null +++ b/node_modules/axios/lib/utils.js @@ -0,0 +1,1017 @@ +'use strict'; + +import bind from './helpers/bind.js'; + +// utils is a library of generic helper functions non-specific to axios + +const { toString } = Object.prototype; +const { getPrototypeOf } = Object; +const { iterator, toStringTag } = Symbol; + +/* Creating a function that will check if an object has a property. */ +const hasOwnProperty = ( + ({ hasOwnProperty }) => + (obj, prop) => + hasOwnProperty.call(obj, prop) +)(Object.prototype); + +/** + * Walk the prototype chain (excluding the shared Object.prototype) looking for + * an own `prop`. This distinguishes genuine own/inherited members — including + * class accessors and template prototypes — from members injected via + * Object.prototype pollution (e.g. `Object.prototype.username = '...'`), which + * live on Object.prototype itself and are therefore never matched. + * + * @param {*} thing The value whose chain to inspect + * @param {string|symbol} prop The property key to look for + * + * @returns {boolean} True when `prop` is owned below Object.prototype + */ +const hasOwnInPrototypeChain = (thing, prop) => { + let obj = thing; + const seen = []; + + while (obj != null && obj !== Object.prototype) { + if (seen.indexOf(obj) !== -1) { + return false; + } + seen.push(obj); + + if (hasOwnProperty(obj, prop)) { + return true; + } + obj = getPrototypeOf(obj); + } + return false; +}; + +/** + * Read `obj[prop]` only when it is safe from Object.prototype pollution. Own + * properties and members inherited from a non-Object.prototype source (a class + * instance or template object) are honored; a value reachable only through a + * polluted Object.prototype is ignored and `undefined` is returned. + * + * @param {*} obj The source object + * @param {string|symbol} prop The property key to read + * + * @returns {*} The resolved value, or undefined when unsafe/absent + */ +const getSafeProp = (obj, prop) => + obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : undefined; + +const kindOf = ((cache) => (thing) => { + const str = toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); +})(Object.create(null)); + +const kindOfTest = (type) => { + type = type.toLowerCase(); + return (thing) => kindOf(thing) === type; +}; + +const typeOfTest = (type) => (thing) => typeof thing === type; + +/** + * Determine if a value is a non-null object + * + * @param {Object} val The value to test + * + * @returns {boolean} True if value is an Array, otherwise false + */ +const { isArray } = Array; + +/** + * Determine if a value is undefined + * + * @param {*} val The value to test + * + * @returns {boolean} True if the value is undefined, otherwise false + */ +const isUndefined = typeOfTest('undefined'); + +/** + * Determine if a value is a Buffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Buffer, otherwise false + */ +function isBuffer(val) { + return ( + val !== null && + !isUndefined(val) && + val.constructor !== null && + !isUndefined(val.constructor) && + isFunction(val.constructor.isBuffer) && + val.constructor.isBuffer(val) + ); +} + +/** + * Determine if a value is an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +const isArrayBuffer = kindOfTest('ArrayBuffer'); + +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + let result; + if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { + result = ArrayBuffer.isView(val); + } else { + result = val && val.buffer && isArrayBuffer(val.buffer); + } + return result; +} + +/** + * Determine if a value is a String + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a String, otherwise false + */ +const isString = typeOfTest('string'); + +/** + * Determine if a value is a Function + * + * @param {*} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ +const isFunction = typeOfTest('function'); + +/** + * Determine if a value is a Number + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Number, otherwise false + */ +const isNumber = typeOfTest('number'); + +/** + * Determine if a value is an Object + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an Object, otherwise false + */ +const isObject = (thing) => thing !== null && typeof thing === 'object'; + +/** + * Determine if a value is a Boolean + * + * @param {*} thing The value to test + * @returns {boolean} True if value is a Boolean, otherwise false + */ +const isBoolean = (thing) => thing === true || thing === false; + +/** + * Determine if a value is a plain Object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a plain Object, otherwise false + */ +const isPlainObject = (val) => { + if (!isObject(val)) { + return false; + } + + const prototype = getPrototypeOf(val); + return ( + (prototype === null || + prototype === Object.prototype || + getPrototypeOf(prototype) === null) && + // Treat any genuine (non-Object.prototype-polluted) Symbol.toStringTag or + // Symbol.iterator as evidence the value is a tagged/iterable type rather + // than a plain object, while ignoring keys injected onto Object.prototype. + !hasOwnInPrototypeChain(val, toStringTag) && + !hasOwnInPrototypeChain(val, iterator) + ); +}; + +/** + * Determine if a value is an empty object (safely handles Buffers) + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is an empty object, otherwise false + */ +const isEmptyObject = (val) => { + // Early return for non-objects or Buffers to prevent RangeError + if (!isObject(val) || isBuffer(val)) { + return false; + } + + try { + return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype; + } catch (e) { + // Fallback for any other objects that might cause RangeError with Object.keys() + return false; + } +}; + +/** + * Determine if a value is a Date + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Date, otherwise false + */ +const isDate = kindOfTest('Date'); + +/** + * Determine if a value is a File + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ +const isFile = kindOfTest('File'); + +/** + * Determine if a value is a React Native Blob + * React Native "blob": an object with a `uri` attribute. Optionally, it can + * also have a `name` and `type` attribute to specify filename and content type + * + * @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71 + * + * @param {*} value The value to test + * + * @returns {boolean} True if value is a React Native Blob, otherwise false + */ +const isReactNativeBlob = (value) => { + return !!(value && typeof value.uri !== 'undefined'); +}; + +/** + * Determine if environment is React Native + * ReactNative `FormData` has a non-standard `getParts()` method + * + * @param {*} formData The formData to test + * + * @returns {boolean} True if environment is React Native, otherwise false + */ +const isReactNative = (formData) => formData && typeof formData.getParts !== 'undefined'; + +/** + * Determine if a value is a Blob + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Blob, otherwise false + */ +const isBlob = kindOfTest('Blob'); + +/** + * Determine if a value is a FileList + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a FileList, otherwise false + */ +const isFileList = kindOfTest('FileList'); + +/** + * Determine if a value is a Stream + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Stream, otherwise false + */ +const isStream = (val) => isObject(val) && isFunction(val.pipe); + +/** + * Determine if a value is a FormData + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an FormData, otherwise false + */ +function getGlobal() { + if (typeof globalThis !== 'undefined') return globalThis; + if (typeof self !== 'undefined') return self; + if (typeof window !== 'undefined') return window; + if (typeof global !== 'undefined') return global; + return {}; +} + +const G = getGlobal(); +const FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined; + +const isFormData = (thing) => { + if (!thing) return false; + if (FormDataCtor && thing instanceof FormDataCtor) return true; + // Reject plain objects inheriting directly from Object.prototype so prototype-pollution gadgets can't spoof FormData. + const proto = getPrototypeOf(thing); + if (!proto || proto === Object.prototype) return false; + if (!isFunction(thing.append)) return false; + const kind = kindOf(thing); + return ( + kind === 'formdata' || + // detect form-data instance + (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]') + ); +}; + +/** + * Determine if a value is a URLSearchParams object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +const isURLSearchParams = kindOfTest('URLSearchParams'); + +const [isReadableStream, isRequest, isResponse, isHeaders] = [ + 'ReadableStream', + 'Request', + 'Response', + 'Headers', +].map(kindOfTest); + +/** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * + * @returns {String} The String freed of excess whitespace + */ +const trim = (str) => { + return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); +}; +/** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + * + * @param {Object} [options] + * @param {Boolean} [options.allOwnKeys = false] + * @returns {any} + */ +function forEach(obj, fn, { allOwnKeys = false } = {}) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + + let i; + let l; + + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + + if (isArray(obj)) { + // Iterate over array values + for (i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Buffer check + if (isBuffer(obj)) { + return; + } + + // Iterate over object keys + const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys.length; + let key; + + for (i = 0; i < len; i++) { + key = keys[i]; + fn.call(null, obj[key], key, obj); + } + } +} + +/** + * Finds a key in an object, case-insensitive, returning the actual key name. + * Returns null if the object is a Buffer or if no match is found. + * + * @param {Object} obj - The object to search. + * @param {string} key - The key to find (case-insensitive). + * @returns {?string} The actual key name if found, otherwise null. + */ +function findKey(obj, key) { + if (isBuffer(obj)) { + return null; + } + + key = key.toLowerCase(); + const keys = Object.keys(obj); + let i = keys.length; + let _key; + while (i-- > 0) { + _key = keys[i]; + if (key === _key.toLowerCase()) { + return _key; + } + } + return null; +} + +const _global = (() => { + /*eslint no-undef:0*/ + if (typeof globalThis !== 'undefined') return globalThis; + return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global; +})(); + +const isContextDefined = (context) => !isUndefined(context) && context !== _global; + +/** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * const result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * + * @returns {Object} Result of all merge properties + */ +function merge(...objs) { + const { caseless, skipUndefined } = (isContextDefined(this) && this) || {}; + const result = {}; + const assignValue = (val, key) => { + // Skip dangerous property names to prevent prototype pollution + if (key === '__proto__' || key === 'constructor' || key === 'prototype') { + return; + } + + // findKey lowercases the key, so caseless lookup only applies to strings — + // symbol keys are identity-matched. + const targetKey = (caseless && typeof key === 'string' && findKey(result, key)) || key; + // Read via own-prop only — a bare `result[targetKey]` walks the prototype + // chain, so a polluted Object.prototype value could surface here and get + // copied into the merged result. + const existing = hasOwnProperty(result, targetKey) ? result[targetKey] : undefined; + if (isPlainObject(existing) && isPlainObject(val)) { + result[targetKey] = merge(existing, val); + } else if (isPlainObject(val)) { + result[targetKey] = merge({}, val); + } else if (isArray(val)) { + result[targetKey] = val.slice(); + } else if (!skipUndefined || !isUndefined(val)) { + result[targetKey] = val; + } + }; + + for (let i = 0, l = objs.length; i < l; i++) { + const source = objs[i]; + if (!source || isBuffer(source)) { + continue; + } + + forEach(source, assignValue); + + if (typeof source !== 'object' || isArray(source)) { + continue; + } + + const symbols = Object.getOwnPropertySymbols(source); + for (let j = 0; j < symbols.length; j++) { + const symbol = symbols[j]; + if (propertyIsEnumerable.call(source, symbol)) { + assignValue(source[symbol], symbol); + } + } + } + return result; +} + +/** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * + * @param {Object} [options] + * @param {Boolean} [options.allOwnKeys] + * @returns {Object} The resulting value of object a + */ +const extend = (a, b, thisArg, { allOwnKeys } = {}) => { + forEach( + b, + (val, key) => { + if (thisArg && isFunction(val)) { + Object.defineProperty(a, key, { + // Null-proto descriptor so a polluted Object.prototype.get cannot + // hijack defineProperty's accessor-vs-data resolution. + __proto__: null, + value: bind(val, thisArg), + writable: true, + enumerable: true, + configurable: true, + }); + } else { + Object.defineProperty(a, key, { + __proto__: null, + value: val, + writable: true, + enumerable: true, + configurable: true, + }); + } + }, + { allOwnKeys } + ); + return a; +}; + +/** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * + * @returns {string} content value without BOM + */ +const stripBOM = (content) => { + if (content.charCodeAt(0) === 0xfeff) { + content = content.slice(1); + } + return content; +}; + +/** + * Inherit the prototype methods from one constructor into another + * @param {function} constructor + * @param {function} superConstructor + * @param {object} [props] + * @param {object} [descriptors] + * + * @returns {void} + */ +const inherits = (constructor, superConstructor, props, descriptors) => { + constructor.prototype = Object.create(superConstructor.prototype, descriptors); + Object.defineProperty(constructor.prototype, 'constructor', { + __proto__: null, + value: constructor, + writable: true, + enumerable: false, + configurable: true, + }); + Object.defineProperty(constructor, 'super', { + __proto__: null, + value: superConstructor.prototype, + }); + props && Object.assign(constructor.prototype, props); +}; + +/** + * Resolve object with deep prototype chain to a flat object + * @param {Object} sourceObj source object + * @param {Object} [destObj] + * @param {Function|Boolean} [filter] + * @param {Function} [propFilter] + * + * @returns {Object} + */ +const toFlatObject = (sourceObj, destObj, filter, propFilter) => { + let props; + let i; + let prop; + const merged = {}; + + destObj = destObj || {}; + // eslint-disable-next-line no-eq-null,eqeqeq + if (sourceObj == null) return destObj; + + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter !== false && getPrototypeOf(sourceObj); + } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); + + return destObj; +}; + +/** + * Determines whether a string ends with the characters of a specified string + * + * @param {String} str + * @param {String} searchString + * @param {Number} [position= 0] + * + * @returns {boolean} + */ +const endsWith = (str, searchString, position) => { + str = String(str); + if (position === undefined || position > str.length) { + position = str.length; + } + position -= searchString.length; + const lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; +}; + +/** + * Returns new array from array like object or null if failed + * + * @param {*} [thing] + * + * @returns {?Array} + */ +const toArray = (thing) => { + if (!thing) return null; + if (isArray(thing)) return thing; + let i = thing.length; + if (!isNumber(i)) return null; + const arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; +}; + +/** + * Checking if the Uint8Array exists and if it does, it returns a function that checks if the + * thing passed in is an instance of Uint8Array + * + * @param {TypedArray} + * + * @returns {Array} + */ +// eslint-disable-next-line func-names +const isTypedArray = ((TypedArray) => { + // eslint-disable-next-line func-names + return (thing) => { + return TypedArray && thing instanceof TypedArray; + }; +})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); + +/** + * For each entry in the object, call the function with the key and value. + * + * @param {Object} obj - The object to iterate over. + * @param {Function} fn - The function to call for each entry. + * + * @returns {void} + */ +const forEachEntry = (obj, fn) => { + const generator = obj && obj[iterator]; + + const _iterator = generator.call(obj); + + let result; + + while ((result = _iterator.next()) && !result.done) { + const pair = result.value; + fn.call(obj, pair[0], pair[1]); + } +}; + +/** + * It takes a regular expression and a string, and returns an array of all the matches + * + * @param {string} regExp - The regular expression to match against. + * @param {string} str - The string to search. + * + * @returns {Array} + */ +const matchAll = (regExp, str) => { + let matches; + const arr = []; + + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } + + return arr; +}; + +/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ +const isHTMLForm = kindOfTest('HTMLFormElement'); + +const toCamelCase = (str) => { + return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) { + return p1.toUpperCase() + p2; + }); +}; + +const { propertyIsEnumerable } = Object.prototype; + +/** + * Determine if a value is a RegExp object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a RegExp object, otherwise false + */ +const isRegExp = kindOfTest('RegExp'); + +const reduceDescriptors = (obj, reducer) => { + const descriptors = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; + + forEach(descriptors, (descriptor, name) => { + let ret; + if ((ret = reducer(descriptor, name, obj)) !== false) { + reducedDescriptors[name] = ret || descriptor; + } + }); + + Object.defineProperties(obj, reducedDescriptors); +}; + +/** + * Makes all methods read-only + * @param {Object} obj + */ + +const freezeMethods = (obj) => { + reduceDescriptors(obj, (descriptor, name) => { + // skip restricted props in strict mode + if (isFunction(obj) && ['arguments', 'caller', 'callee'].includes(name)) { + return false; + } + + const value = obj[name]; + + if (!isFunction(value)) return; + + descriptor.enumerable = false; + + if ('writable' in descriptor) { + descriptor.writable = false; + return; + } + + if (!descriptor.set) { + descriptor.set = () => { + throw Error("Can not rewrite read-only method '" + name + "'"); + }; + } + }); +}; + +/** + * Converts an array or a delimited string into an object set with values as keys and true as values. + * Useful for fast membership checks. + * + * @param {Array|string} arrayOrString - The array or string to convert. + * @param {string} delimiter - The delimiter to use if input is a string. + * @returns {Object} An object with keys from the array or string, values set to true. + */ +const toObjectSet = (arrayOrString, delimiter) => { + const obj = {}; + + const define = (arr) => { + arr.forEach((value) => { + obj[value] = true; + }); + }; + + isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); + + return obj; +}; + +const noop = () => {}; + +const toFiniteNumber = (value, defaultValue) => { + return value != null && Number.isFinite((value = +value)) ? value : defaultValue; +}; + +/** + * If the thing is a FormData object, return true, otherwise return false. + * + * @param {unknown} thing - The thing to check. + * + * @returns {boolean} + */ +function isSpecCompliantForm(thing) { + return !!( + thing && + isFunction(thing.append) && + thing[toStringTag] === 'FormData' && + thing[iterator] + ); +} + +/** + * Recursively converts an object to a JSON-compatible object, handling circular references and Buffers. + * + * @param {Object} obj - The object to convert. + * @returns {Object} The JSON-compatible object. + */ +const toJSONObject = (obj) => { + const visited = new WeakSet(); + + const visit = (source) => { + if (isObject(source)) { + if (visited.has(source)) { + return; + } + + //Buffer check + if (isBuffer(source)) { + return source; + } + + if (!('toJSON' in source)) { + // add-on descent / delete-on-ascent: preserves path semantics, so DAG nodes serialise at every occurrence (see #7230). + visited.add(source); + const target = isArray(source) ? [] : {}; + + forEach(source, (value, key) => { + const reducedValue = visit(value); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); + + visited.delete(source); + + return target; + } + } + + return source; + }; + + return visit(obj); +}; + +/** + * Determines if a value is an async function. + * + * @param {*} thing - The value to test. + * @returns {boolean} True if value is an async function, otherwise false. + */ +const isAsyncFn = kindOfTest('AsyncFunction'); + +/** + * Determines if a value is thenable (has then and catch methods). + * + * @param {*} thing - The value to test. + * @returns {boolean} True if value is thenable, otherwise false. + */ +const isThenable = (thing) => + thing && + (isObject(thing) || isFunction(thing)) && + isFunction(thing.then) && + isFunction(thing.catch); + +// original code +// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 + +/** + * Provides a cross-platform setImmediate implementation. + * Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout. + * + * @param {boolean} setImmediateSupported - Whether setImmediate is supported. + * @param {boolean} postMessageSupported - Whether postMessage is supported. + * @returns {Function} A function to schedule a callback asynchronously. + */ +const _setImmediate = ((setImmediateSupported, postMessageSupported) => { + if (setImmediateSupported) { + return setImmediate; + } + + return postMessageSupported + ? ((token, callbacks) => { + _global.addEventListener( + 'message', + ({ source, data }) => { + if (source === _global && data === token) { + callbacks.length && callbacks.shift()(); + } + }, + false + ); + + return (cb) => { + callbacks.push(cb); + _global.postMessage(token, '*'); + }; + })(`axios@${Math.random()}`, []) + : (cb) => setTimeout(cb); +})(typeof setImmediate === 'function', isFunction(_global.postMessage)); + +/** + * Schedules a microtask or asynchronous callback as soon as possible. + * Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate. + * + * @type {Function} + */ +const asap = + typeof queueMicrotask !== 'undefined' + ? queueMicrotask.bind(_global) + : (typeof process !== 'undefined' && process.nextTick) || _setImmediate; + +// ********************* + +const isIterable = (thing) => thing != null && isFunction(thing[iterator]); + +/** + * Determine if a value is iterable via an iterator that is NOT sourced solely + * from a polluted Object.prototype. Use this instead of `isIterable` whenever + * the iterable comes from untrusted input (e.g. user-supplied header sources), + * so `Object.prototype[Symbol.iterator] = ...` cannot turn an ordinary object + * into an attacker-controlled entries iterator. + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value has a non-polluted iterator + */ +const isSafeIterable = (thing) => + thing != null && hasOwnInPrototypeChain(thing, iterator) && isIterable(thing); + +export default { + isArray, + isArrayBuffer, + isBuffer, + isFormData, + isArrayBufferView, + isString, + isNumber, + isBoolean, + isObject, + isPlainObject, + isEmptyObject, + isReadableStream, + isRequest, + isResponse, + isHeaders, + isUndefined, + isDate, + isFile, + isReactNativeBlob, + isReactNative, + isBlob, + isRegExp, + isFunction, + isStream, + isURLSearchParams, + isTypedArray, + isFileList, + forEach, + merge, + extend, + trim, + stripBOM, + inherits, + toFlatObject, + kindOf, + kindOfTest, + endsWith, + toArray, + forEachEntry, + matchAll, + isHTMLForm, + hasOwnProperty, + hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection + hasOwnInPrototypeChain, + getSafeProp, + reduceDescriptors, + freezeMethods, + toObjectSet, + toCamelCase, + noop, + toFiniteNumber, + findKey, + global: _global, + isContextDefined, + isSpecCompliantForm, + toJSONObject, + isAsyncFn, + isThenable, + setImmediate: _setImmediate, + asap, + isIterable, + isSafeIterable, +}; diff --git a/node_modules/axios/package.json b/node_modules/axios/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ffc848cb8ad9abf43b89f45d1070e0a3df3e6cf4 --- /dev/null +++ b/node_modules/axios/package.json @@ -0,0 +1,201 @@ +{ + "name": "axios", + "version": "1.18.0", + "description": "Promise based HTTP client for the browser and node.js", + "main": "./dist/node/axios.cjs", + "module": "./index.js", + "type": "module", + "types": "index.d.ts", + "jsdelivr": "dist/axios.min.js", + "unpkg": "dist/axios.min.js", + "typings": "./index.d.ts", + "exports": { + ".": { + "types": { + "require": "./index.d.cts", + "default": "./index.d.ts" + }, + "bun": { + "require": "./dist/node/axios.cjs", + "default": "./index.js" + }, + "react-native": { + "require": "./dist/browser/axios.cjs", + "default": "./dist/esm/axios.js" + }, + "browser": { + "require": "./dist/browser/axios.cjs", + "default": "./index.js" + }, + "default": { + "require": "./dist/node/axios.cjs", + "default": "./index.js" + } + }, + "./lib/adapters/http.js": "./lib/adapters/http.js", + "./lib/adapters/xhr.js": "./lib/adapters/xhr.js", + "./unsafe/*": "./lib/*", + "./unsafe/core/settle.js": "./lib/core/settle.js", + "./unsafe/core/buildFullPath.js": "./lib/core/buildFullPath.js", + "./unsafe/helpers/isAbsoluteURL.js": "./lib/helpers/isAbsoluteURL.js", + "./unsafe/helpers/buildURL.js": "./lib/helpers/buildURL.js", + "./unsafe/helpers/combineURLs.js": "./lib/helpers/combineURLs.js", + "./unsafe/adapters/http.js": "./lib/adapters/http.js", + "./unsafe/adapters/xhr.js": "./lib/adapters/xhr.js", + "./unsafe/utils.js": "./lib/utils.js", + "./package.json": "./package.json", + "./dist/browser/axios.cjs": "./dist/browser/axios.cjs", + "./dist/node/axios.cjs": "./dist/node/axios.cjs" + }, + "browser": { + "./dist/node/axios.cjs": "./dist/browser/axios.cjs", + "./lib/adapters/http.js": "./lib/helpers/null.js", + "./lib/platform/node/index.js": "./lib/platform/browser/index.js", + "./lib/platform/node/classes/FormData.js": "./lib/helpers/null.js" + }, + "react-native": { + "./dist/node/axios.cjs": "./dist/browser/axios.cjs", + "./lib/adapters/http.js": "./lib/helpers/null.js", + "./lib/platform/node/index.js": "./lib/platform/browser/index.js", + "./lib/platform/node/classes/FormData.js": "./lib/helpers/null.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/axios/axios.git" + }, + "keywords": [ + "xhr", + "http", + "ajax", + "promise", + "node", + "browser", + "fetch", + "rest", + "api", + "client" + ], + "author": "Matt Zabriskie", + "contributors": [ + "Matt Zabriskie (https://github.com/mzabriskie)", + "Jay (https://github.com/jasonsaayman)", + "Dmitriy Mozgovoy (https://github.com/DigitalBrainJS)", + "Nick Uraltsev (https://github.com/nickuraltsev)", + "Emily Morehouse (https://github.com/emilyemorehouse)", + "Rubén Norte (https://github.com/rubennorte)", + "Justin Beckwith (https://github.com/JustinBeckwith)", + "Martti Laine (https://github.com/codeclown)", + "Xianming Zhong (https://github.com/chinesedfan)", + "Shaan Majid (https://github.com/shaanmajid)", + "Willian Agostini (https://github.com/WillianAgostini)", + "Remco Haszing (https://github.com/remcohaszing)", + "Rikki Gibson (https://github.com/RikkiGibson)" + ], + "sideEffects": false, + "license": "MIT", + "bugs": { + "url": "https://github.com/axios/axios/issues" + }, + "homepage": "https://axios-http.com", + "files": [ + "index.js", + "index.d.ts", + "index.d.cts", + "CHANGELOG.md", + "MIGRATION_GUIDE.md", + "lib/", + "dist/axios.js", + "dist/axios.min.js", + "dist/axios.min.js.map", + "dist/esm/axios.js", + "dist/esm/axios.min.js", + "dist/esm/axios.min.js.map", + "dist/browser/axios.cjs", + "dist/node/axios.cjs" + ], + "scripts": { + "build": "gulp clear && cross-env NODE_ENV=production rollup -c -m", + "version": "npm run build && git add package.json", + "preversion": "gulp version", + "test": "npm run test:vitest", + "test:vitest": "vitest run", + "test:vitest:unit": "vitest run --project unit", + "test:vitest:browser": "vitest run --project browser", + "test:vitest:browser:headless": "vitest run --project browser-headless", + "test:vitest:watch": "vitest", + "test:smoke:cjs:vitest": "npm --prefix tests/smoke/cjs run test:smoke:cjs:mocha", + "test:smoke:esm:vitest": "npm --prefix tests/smoke/esm run test:smoke:esm:vitest", + "test:smoke:deno": "deno task --cwd tests/smoke/deno test", + "test:smoke:bun": "bun test --cwd tests/smoke/bun", + "test:module:cjs": "npm --prefix tests/module/cjs run test:module:cjs", + "test:module:esm": "npm --prefix tests/module/esm run test:module:esm", + "docs:dev": "cd docs && npm run docs:dev", + "start": "node ./sandbox/server.js", + "examples": "node ./examples/server.js", + "lint": "eslint lib/**/*.js", + "fix": "eslint --fix lib/**/*.js", + "prepare": "husky" + }, + "dependencies": { + "follow-redirects": "^1.16.0", + "form-data": "^4.0.5", + "https-proxy-agent": "^5.0.1", + "proxy-from-env": "^2.1.0" + }, + "devDependencies": { + "@babel/core": "^7.29.0", + "@babel/preset-env": "^7.29.5", + "@commitlint/cli": "^21.0.1", + "@commitlint/config-conventional": "^21.0.1", + "@eslint/js": "^10.0.1", + "@rollup/plugin-alias": "^6.0.0", + "@rollup/plugin-babel": "^7.0.0", + "@rollup/plugin-commonjs": "^29.0.2", + "@rollup/plugin-json": "^6.1.0", + "@rollup/plugin-node-resolve": "^16.0.3", + "@rollup/plugin-terser": "^1.0.0", + "@vitest/browser": "^4.1.7", + "@vitest/browser-playwright": "^4.1.7", + "abortcontroller-polyfill": "^1.7.8", + "acorn": "^8.16.0", + "body-parser": "^2.2.2", + "chalk": "^5.6.2", + "cross-env": "^10.1.0", + "dev-null": "^0.1.1", + "eslint": "^10.4.0", + "express": "^5.2.1", + "formdata-node": "^6.0.3", + "formidable": "^3.5.4", + "fs-extra": "^11.3.4", + "get-stream": "^9.0.1", + "globals": "^17.6.0", + "gulp": "^5.0.1", + "husky": "^9.1.7", + "lint-staged": "^17.0.5", + "minimist": "^1.2.8", + "multer": "^2.1.1", + "playwright": "^1.60.0", + "prettier": "^3.8.3", + "rollup": "^4.60.4", + "rollup-plugin-bundle-size": "^1.0.3", + "selfsigned": "^5.5.0", + "stream-throttle": "^0.1.3", + "typescript": "^5.9.3", + "vitest": "^4.1.7" + }, + "commitlint": { + "rules": { + "header-max-length": [ + 2, + "always", + 130 + ] + }, + "extends": [ + "@commitlint/config-conventional" + ] + }, + "lint-staged": { + "*.{js,cjs,mjs,ts,json,md,yml,yaml}": "prettier --write" + } +} \ No newline at end of file diff --git a/node_modules/b4a/LICENSE b/node_modules/b4a/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/node_modules/b4a/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/b4a/README.md b/node_modules/b4a/README.md new file mode 100644 index 0000000000000000000000000000000000000000..01a6ce76ecab2c2152ab22e3311ad67b7e8e653e --- /dev/null +++ b/node_modules/b4a/README.md @@ -0,0 +1,153 @@ +# Buffer for Array + +Buffer for Array (B4A) provides a set of functions for bridging the gap between the Node.js `Buffer` class and the `Uint8Array` class. A browser compatibility layer is also included, making it possible to use B4A in both Node.js and browsers without having to worry about whether you're dealing with buffers or typed arrays. + +## Installation + +```sh +npm i b4a +``` + +### React Native + +When imported from React Native `b4a` will make use of `react-native-b4a` for optimised buffer operations when available. All you need to do is install it: + +```sh +npm i react-native-b4a +``` + +## API + +#### `b4a.isBuffer(value)` + +See https://nodejs.org/api/buffer.html#static-method-bufferisbufferobj + +This will also return `true` when passed a `Uint8Array`. + +#### `b4a.isEncoding(encoding)` + +See https://nodejs.org/api/buffer.html#static-method-bufferisencodingencoding + +#### `b4a.alloc(size[, fill[, encoding]])` + +See https://nodejs.org/api/buffer.html#static-method-bufferallocsize-fill-encoding + +#### `b4a.allocUnsafe(size)` + +See https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize + +#### `b4a.allocUnsafeSlow(size)` + +See https://nodejs.org/api/buffer.html#static-method-bufferallocunsafeslowsize + +#### `b4a.byteLength(string)` + +See https://nodejs.org/api/buffer.html#static-method-bufferbytelengthstring-encoding + +#### `b4a.compare(buf1, buf2)` + +See https://nodejs.org/api/buffer.html#static-method-buffercomparebuf1-buf2 + +#### `b4a.concat(buffers[, totalLength])` + +See https://nodejs.org/api/buffer.html#static-method-bufferconcatlist-totallength + +#### `b4a.copy(source, target[, targetStart[, sourceStart[, sourceEnd]]])` + +See https://nodejs.org/api/buffer.html#bufcopytarget-targetstart-sourcestart-sourceend + +#### `b4a.equals(buf1, buf2)` + +See https://nodejs.org/api/buffer.html#bufequalsotherbuffer + +#### `b4a.fill(buffer, value[, offset[, end]][, encoding])` + +See https://nodejs.org/api/buffer.html#buffillvalue-offset-end-encoding + +#### `b4a.from(array)` + +See https://nodejs.org/api/buffer.html#static-method-bufferfromarray + +#### `b4a.from(arrayBuffer[, byteOffset[, length]])` + +See https://nodejs.org/api/buffer.html#static-method-bufferfromarraybuffer-byteoffset-length + +#### `b4a.from(buffer)` + +See https://nodejs.org/api/buffer.html#static-method-bufferfrombuffer + +#### `b4a.from(string[, encoding])` + +See https://nodejs.org/api/buffer.html#static-method-bufferfromstring-encoding + +#### `b4a.includes(buffer, value[, byteOffset][, encoding])` + +See https://nodejs.org/api/buffer.html#bufincludesvalue-byteoffset-encoding + +#### `b4a.indexOf(buffer, value[, byteOffset][, encoding])` + +See https://nodejs.org/api/buffer.html#bufindexofvalue-byteoffset-encoding + +#### `b4a.lastIndexOf(buffer, value[, byteOffset][, encoding])` + +See https://nodejs.org/api/buffer.html#buflastindexofvalue-byteoffset-encoding + +#### `b4a.swap16(buffer)` + +See https://nodejs.org/api/buffer.html#bufswap16 + +#### `b4a.swap32(buffer)` + +See https://nodejs.org/api/buffer.html#bufswap32 + +#### `b4a.swap64(buffer)` + +See https://nodejs.org/api/buffer.html#bufswap64 + +#### `b4a.toBuffer(buffer)` + +Convert a buffer to its canonical representation. In Node.js, the canonical representation is a `Buffer`. In the browser, the canonical representation is a `Uint8Array`. + +#### `b4a.toString(buffer, [encoding[, start[, end]]])` + +See https://nodejs.org/api/buffer.html#buftostringencoding-start-end + +#### `b4a.write(buffer, string[, offset[, length]][, encoding])` + +See https://nodejs.org/api/buffer.html#bufwritestring-offset-length-encoding + +#### `b4a.writeDoubleLE(buffer, value[, offset])` + +See https://nodejs.org/api/buffer.html#bufwritedoublelevalue-offset + +#### `b4a.writeFloatLE(buffer, value[, offset])` + +See https://nodejs.org/api/buffer.html#bufwritefloatlevalue-offset + +#### `b4a.writeUInt32LE(buffer, value[, offset])` + +https://nodejs.org/api/buffer.html#bufwriteuint32levalue-offset + +#### `b4a.writeInt32LE(buffer, value[, offset])` + +See https://nodejs.org/api/buffer.html#bufwriteint32levalue-offset + +#### `b4a.readDoubleLE(buffer[, offset])` + +See https://nodejs.org/api/buffer.html#bufreaddoubleleoffset + +#### `b4a.readFloatLE(buffer[, offset])` + +See https://nodejs.org/api/buffer.html#bufreadfloatleoffset + +#### `b4a.readUInt32LE(buffer[, offset])` + +See https://nodejs.org/api/buffer.html#bufreaduint32leoffset + +#### `b4a.readInt32LE(buffer[, offset])` + +See https://nodejs.org/api/buffer.html#bufreadint32leoffset + +## License + +Apache 2.0 diff --git a/node_modules/b4a/browser.js b/node_modules/b4a/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..542ba7bd0ff4ced305372eae2bd441f37de53e68 --- /dev/null +++ b/node_modules/b4a/browser.js @@ -0,0 +1,541 @@ +const ascii = require('./lib/ascii') +const base64 = require('./lib/base64') +const hex = require('./lib/hex') +const latin1 = require('./lib/latin1') +const utf8 = require('./lib/utf8') +const utf16le = require('./lib/utf16le') + +const LE = new Uint8Array(Uint16Array.of(0xff).buffer)[0] === 0xff + +function codecFor(encoding) { + switch (encoding) { + case 'ascii': + return ascii + case 'base64': + return base64 + case 'hex': + return hex + case 'binary': + case 'latin1': + return latin1 + case 'utf8': + case 'utf-8': + case undefined: + case null: + return utf8 + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16le + default: + throw new Error(`Unknown encoding '${encoding}'`) + } +} + +function isBuffer(value) { + return value instanceof Uint8Array +} + +function isEncoding(encoding) { + try { + codecFor(encoding) + return true + } catch { + return false + } +} + +function alloc(size, fill, encoding) { + const buffer = new Uint8Array(size) + if (fill !== undefined) { + exports.fill(buffer, fill, 0, buffer.byteLength, encoding) + } + return buffer +} + +function allocUnsafe(size) { + return new Uint8Array(size) +} + +function allocUnsafeSlow(size) { + return new Uint8Array(size) +} + +function byteLength(string, encoding) { + return codecFor(encoding).byteLength(string) +} + +function compare(a, b) { + if (a === b) return 0 + + const len = Math.min(a.byteLength, b.byteLength) + + a = new DataView(a.buffer, a.byteOffset, a.byteLength) + b = new DataView(b.buffer, b.byteOffset, b.byteLength) + + let i = 0 + + for (let n = len - (len % 4); i < n; i += 4) { + const x = a.getUint32(i, LE) + const y = b.getUint32(i, LE) + if (x !== y) break + } + + for (; i < len; i++) { + const x = a.getUint8(i) + const y = b.getUint8(i) + if (x < y) return -1 + if (x > y) return 1 + } + + return a.byteLength > b.byteLength ? 1 : a.byteLength < b.byteLength ? -1 : 0 +} + +function concat(buffers, length) { + if (length === undefined) { + length = buffers.reduce((len, buffer) => len + buffer.byteLength, 0) + } + + const result = new Uint8Array(length) + + let offset = 0 + + for (const buffer of buffers) { + if (offset + buffer.byteLength > result.byteLength) { + result.set(buffer.subarray(0, result.byteLength - offset), offset) + return result + } + + result.set(buffer, offset) + offset += buffer.byteLength + } + + return result +} + +function copy(source, target, targetStart = 0, sourceStart = 0, sourceEnd = source.byteLength) { + if (targetStart < 0) targetStart = 0 + if (targetStart >= target.byteLength) return 0 + + const targetLength = target.byteLength - targetStart + + if (sourceStart < 0) sourceStart = 0 + if (sourceStart >= source.byteLength) return 0 + + if (sourceEnd <= sourceStart) return 0 + if (sourceEnd > source.byteLength) sourceEnd = source.byteLength + + if (sourceEnd - sourceStart > targetLength) { + sourceEnd = sourceStart + targetLength + } + + const sourceLength = sourceEnd - sourceStart + + if (source === target) { + target.copyWithin(targetStart, sourceStart, sourceEnd) + } else { + if (sourceStart !== 0 || sourceEnd !== source.byteLength) { + source = source.subarray(sourceStart, sourceEnd) + } + + target.set(source, targetStart) + } + + return sourceLength +} + +function equals(a, b) { + if (a === b) return true + if (a.byteLength !== b.byteLength) return false + + return compare(a, b) === 0 +} + +function fill(buffer, value, offset = 0, end = buffer.byteLength, encoding = 'utf8') { + if (typeof value === 'string') { + if (typeof offset === 'string') { + // fill(string, encoding) + encoding = offset + offset = 0 + end = buffer.byteLength + } else if (typeof end === 'string') { + // fill(string, offset, encoding) + encoding = end + end = buffer.byteLength + } + } else if (typeof value === 'number') { + value = value & 0xff + } else if (typeof value === 'boolean') { + value = +value + } + + if (offset < 0) offset = 0 + if (offset >= buffer.byteLength) return buffer + + if (end <= offset) return buffer + if (end > buffer.byteLength) end = buffer.byteLength + + if (typeof value === 'number') return buffer.fill(value, offset, end) + + if (typeof value === 'string') value = exports.from(value, encoding) + + const len = value.byteLength + + for (let i = 0, n = end - offset; i < n; ++i) { + buffer[i + offset] = value[i % len] + } + + return buffer +} + +function from(value, encodingOrOffset, length) { + // from(string, encoding) + if (typeof value === 'string') return fromString(value, encodingOrOffset) + + // from(array) + if (Array.isArray(value)) return fromArray(value) + + // from(buffer) + if (ArrayBuffer.isView(value)) return fromBuffer(value) + + // from(arrayBuffer[, byteOffset[, length]]) + return fromArrayBuffer(value, encodingOrOffset, length) +} + +function fromString(string, encoding) { + const codec = codecFor(encoding) + const buffer = new Uint8Array(codec.byteLength(string)) + codec.write(buffer, string) + return buffer +} + +function fromArray(array) { + const buffer = new Uint8Array(array.length) + buffer.set(array) + return buffer +} + +function fromBuffer(buffer) { + const copy = new Uint8Array(buffer.byteLength) + copy.set(buffer) + return copy +} + +function fromArrayBuffer(arrayBuffer, byteOffset, length) { + return new Uint8Array(arrayBuffer, byteOffset, length) +} + +function includes(buffer, value, byteOffset, encoding) { + return indexOf(buffer, value, byteOffset, encoding) !== -1 +} + +function indexOf(buffer, value, byteOffset, encoding) { + return bidirectionalIndexOf(buffer, value, byteOffset, encoding, true /* first */) +} + +function lastIndexOf(buffer, value, byteOffset, encoding) { + return bidirectionalIndexOf(buffer, value, byteOffset, encoding, false /* last */) +} + +function bidirectionalIndexOf(buffer, value, byteOffset, encoding, first) { + if (buffer.byteLength === 0) return -1 + + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset === undefined) { + byteOffset = first ? 0 : buffer.length - 1 + } else if (byteOffset < 0) { + byteOffset += buffer.byteLength + } + + if (byteOffset >= buffer.byteLength) { + if (first) return -1 + else byteOffset = buffer.byteLength - 1 + } else if (byteOffset < 0) { + if (first) byteOffset = 0 + else return -1 + } + + if (typeof value === 'string') { + value = from(value, encoding) + } else if (typeof value === 'number') { + value = value & 0xff + + if (first) { + return buffer.indexOf(value, byteOffset) + } else { + return buffer.lastIndexOf(value, byteOffset) + } + } + + if (value.byteLength === 0) return -1 + + if (first) { + let foundIndex = -1 + + for (let i = byteOffset; i < buffer.byteLength; i++) { + if (buffer[i] === value[foundIndex === -1 ? 0 : i - foundIndex]) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === value.byteLength) return foundIndex + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + value.byteLength > buffer.byteLength) { + byteOffset = buffer.byteLength - value.byteLength + } + + for (let i = byteOffset; i >= 0; i--) { + let found = true + + for (let j = 0; j < value.byteLength; j++) { + if (buffer[i + j] !== value[j]) { + found = false + break + } + } + + if (found) return i + } + } + + return -1 +} + +function swap(buffer, n, m) { + const i = buffer[n] + buffer[n] = buffer[m] + buffer[m] = i +} + +function swap16(buffer) { + const len = buffer.byteLength + + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + + for (let i = 0; i < len; i += 2) swap(buffer, i, i + 1) + + return buffer +} + +function swap32(buffer) { + const len = buffer.byteLength + + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + + for (let i = 0; i < len; i += 4) { + swap(buffer, i, i + 3) + swap(buffer, i + 1, i + 2) + } + + return buffer +} + +function swap64(buffer) { + const len = buffer.byteLength + + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + + for (let i = 0; i < len; i += 8) { + swap(buffer, i, i + 7) + swap(buffer, i + 1, i + 6) + swap(buffer, i + 2, i + 5) + swap(buffer, i + 3, i + 4) + } + + return buffer +} + +function toBuffer(buffer) { + return buffer +} + +function toString(buffer, encoding = 'utf8', start = 0, end = buffer.byteLength) { + // toString(buffer) + if (arguments.length === 1) return utf8.toString(buffer) + + // toString(buffer, encoding) + if (arguments.length === 2) return codecFor(encoding).toString(buffer) + + if (start < 0) start = 0 + if (start >= buffer.byteLength) return '' + + if (end <= start) return '' + if (end > buffer.byteLength) end = buffer.byteLength + + if (start !== 0 || end !== buffer.byteLength) { + buffer = buffer.subarray(start, end) + } + + return codecFor(encoding).toString(buffer) +} + +function write(buffer, string, offset = 0, length = buffer.byteLength, encoding) { + // write(buffer, string) + if (arguments.length === 2) return utf8.write(buffer, string) + + if (typeof offset === 'string') { + // write(buffer, string, encoding) + encoding = offset + offset = 0 + length = buffer.byteLength + } else if (typeof length === 'string') { + // write(buffer, string, offset, encoding) + encoding = length + length = buffer.byteLength - offset + } + + length = Math.min(length, exports.byteLength(string, encoding)) + + let start = offset + if (start < 0) start = 0 + if (start >= buffer.byteLength) return 0 + + let end = offset + length + if (end <= start) return 0 + if (end > buffer.byteLength) end = buffer.byteLength + + if (start !== 0 || end !== buffer.byteLength) { + buffer = buffer.subarray(start, end) + } + + return codecFor(encoding).write(buffer, string) +} + +function readDoubleBE(buffer, offset = 0) { + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + return view.getFloat64(offset, false) +} + +function readDoubleLE(buffer, offset = 0) { + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + return view.getFloat64(offset, true) +} + +function readFloatBE(buffer, offset = 0) { + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + return view.getFloat32(offset, false) +} + +function readFloatLE(buffer, offset = 0) { + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + return view.getFloat32(offset, true) +} + +function readInt32BE(buffer, offset = 0) { + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + return view.getInt32(offset, false) +} + +function readInt32LE(buffer, offset = 0) { + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + return view.getInt32(offset, true) +} + +function readUInt32BE(buffer, offset = 0) { + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + return view.getUint32(offset, false) +} + +function readUInt32LE(buffer, offset = 0) { + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + return view.getUint32(offset, true) +} + +function writeDoubleBE(buffer, value, offset = 0) { + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + view.setFloat64(offset, value, false) + return offset + 8 +} + +function writeDoubleLE(buffer, value, offset = 0) { + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + view.setFloat64(offset, value, true) + return offset + 8 +} + +function writeFloatBE(buffer, value, offset = 0) { + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + view.setFloat32(offset, value, false) + return offset + 4 +} + +function writeFloatLE(buffer, value, offset = 0) { + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + view.setFloat32(offset, value, true) + return offset + 4 +} + +function writeInt32BE(buffer, value, offset = 0) { + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + view.setInt32(offset, value, false) + return offset + 4 +} + +function writeInt32LE(buffer, value, offset = 0) { + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + view.setInt32(offset, value, true) + return offset + 4 +} + +function writeUInt32BE(buffer, value, offset = 0) { + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + view.setUint32(offset, value, false) + return offset + 4 +} + +function writeUInt32LE(buffer, value, offset = 0) { + const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) + view.setUint32(offset, value, true) + return offset + 4 +} + +module.exports = exports = { + isBuffer, + isEncoding, + alloc, + allocUnsafe, + allocUnsafeSlow, + byteLength, + compare, + concat, + copy, + equals, + fill, + from, + includes, + indexOf, + lastIndexOf, + swap16, + swap32, + swap64, + toBuffer, + toString, + write, + readDoubleBE, + readDoubleLE, + readFloatBE, + readFloatLE, + readInt32BE, + readInt32LE, + readUInt32BE, + readUInt32LE, + writeDoubleBE, + writeDoubleLE, + writeFloatBE, + writeFloatLE, + writeInt32BE, + writeInt32LE, + writeUInt32BE, + writeUInt32LE +} diff --git a/node_modules/b4a/index.js b/node_modules/b4a/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7e0251a978ebd2ff09bb86f2f196987d9f147c9d --- /dev/null +++ b/node_modules/b4a/index.js @@ -0,0 +1,188 @@ +function isBuffer(value) { + return Buffer.isBuffer(value) || value instanceof Uint8Array +} + +function isEncoding(encoding) { + return Buffer.isEncoding(encoding) +} + +function alloc(size, fill, encoding) { + return Buffer.alloc(size, fill, encoding) +} + +function allocUnsafe(size) { + return Buffer.allocUnsafe(size) +} + +function allocUnsafeSlow(size) { + return Buffer.allocUnsafeSlow(size) +} + +function byteLength(string, encoding) { + return Buffer.byteLength(string, encoding) +} + +function compare(a, b) { + return Buffer.compare(a, b) +} + +function concat(buffers, totalLength) { + return Buffer.concat(buffers, totalLength) +} + +function copy(source, target, targetStart, start, end) { + return toBuffer(source).copy(target, targetStart, start, end) +} + +function equals(a, b) { + return toBuffer(a).equals(b) +} + +function fill(buffer, value, offset, end, encoding) { + return toBuffer(buffer).fill(value, offset, end, encoding) +} + +function from(value, encodingOrOffset, length) { + return Buffer.from(value, encodingOrOffset, length) +} + +function includes(buffer, value, byteOffset, encoding) { + return toBuffer(buffer).includes(value, byteOffset, encoding) +} + +function indexOf(buffer, value, byfeOffset, encoding) { + return toBuffer(buffer).indexOf(value, byfeOffset, encoding) +} + +function lastIndexOf(buffer, value, byteOffset, encoding) { + return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding) +} + +function swap16(buffer) { + return toBuffer(buffer).swap16() +} + +function swap32(buffer) { + return toBuffer(buffer).swap32() +} + +function swap64(buffer) { + return toBuffer(buffer).swap64() +} + +function toBuffer(buffer) { + if (Buffer.isBuffer(buffer)) return buffer + return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength) +} + +function toString(buffer, encoding, start, end) { + return toBuffer(buffer).toString(encoding, start, end) +} + +function write(buffer, string, offset, length, encoding) { + return toBuffer(buffer).write(string, offset, length, encoding) +} + +function readDoubleBE(buffer, offset) { + return toBuffer(buffer).readDoubleBE(offset) +} + +function readDoubleLE(buffer, offset) { + return toBuffer(buffer).readDoubleLE(offset) +} + +function readFloatBE(buffer, offset) { + return toBuffer(buffer).readFloatBE(offset) +} + +function readFloatLE(buffer, offset) { + return toBuffer(buffer).readFloatLE(offset) +} + +function readInt32BE(buffer, offset) { + return toBuffer(buffer).readInt32BE(offset) +} + +function readInt32LE(buffer, offset) { + return toBuffer(buffer).readInt32LE(offset) +} + +function readUInt32BE(buffer, offset) { + return toBuffer(buffer).readUInt32BE(offset) +} + +function readUInt32LE(buffer, offset) { + return toBuffer(buffer).readUInt32LE(offset) +} + +function writeDoubleBE(buffer, value, offset) { + return toBuffer(buffer).writeDoubleBE(value, offset) +} + +function writeDoubleLE(buffer, value, offset) { + return toBuffer(buffer).writeDoubleLE(value, offset) +} + +function writeFloatBE(buffer, value, offset) { + return toBuffer(buffer).writeFloatBE(value, offset) +} + +function writeFloatLE(buffer, value, offset) { + return toBuffer(buffer).writeFloatLE(value, offset) +} + +function writeInt32BE(buffer, value, offset) { + return toBuffer(buffer).writeInt32BE(value, offset) +} + +function writeInt32LE(buffer, value, offset) { + return toBuffer(buffer).writeInt32LE(value, offset) +} + +function writeUInt32BE(buffer, value, offset) { + return toBuffer(buffer).writeUInt32BE(value, offset) +} + +function writeUInt32LE(buffer, value, offset) { + return toBuffer(buffer).writeUInt32LE(value, offset) +} + +module.exports = { + isBuffer, + isEncoding, + alloc, + allocUnsafe, + allocUnsafeSlow, + byteLength, + compare, + concat, + copy, + equals, + fill, + from, + includes, + indexOf, + lastIndexOf, + swap16, + swap32, + swap64, + toBuffer, + toString, + write, + readDoubleBE, + readDoubleLE, + readFloatBE, + readFloatLE, + readInt32BE, + readInt32LE, + readUInt32BE, + readUInt32LE, + writeDoubleBE, + writeDoubleLE, + writeFloatBE, + writeFloatLE, + writeInt32BE, + writeInt32LE, + writeUInt32BE, + writeUInt32LE +} diff --git a/node_modules/b4a/lib/ascii.js b/node_modules/b4a/lib/ascii.js new file mode 100644 index 0000000000000000000000000000000000000000..0e2f80915c629ff26c3255a22ad8cd1f921995bc --- /dev/null +++ b/node_modules/b4a/lib/ascii.js @@ -0,0 +1,31 @@ +function byteLength(string) { + return string.length +} + +function toString(buffer) { + const len = buffer.byteLength + + let result = '' + + for (let i = 0; i < len; i++) { + result += String.fromCharCode(buffer[i] & 0x7f) + } + + return result +} + +function write(buffer, string) { + const len = buffer.byteLength + + for (let i = 0; i < len; i++) { + buffer[i] = string.charCodeAt(i) + } + + return len +} + +module.exports = { + byteLength, + toString, + write +} diff --git a/node_modules/b4a/lib/base64.js b/node_modules/b4a/lib/base64.js new file mode 100644 index 0000000000000000000000000000000000000000..4523800b6e3dafb458b92d3f42b9126e8101b356 --- /dev/null +++ b/node_modules/b4a/lib/base64.js @@ -0,0 +1,64 @@ +const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + +const codes = new Uint8Array(256) + +for (let i = 0; i < alphabet.length; i++) { + codes[alphabet.charCodeAt(i)] = i +} + +codes[/* - */ 0x2d] = 62 +codes[/* _ */ 0x5f] = 63 + +function byteLength(string) { + let len = string.length + + if (string.charCodeAt(len - 1) === 0x3d) len-- + if (len > 1 && string.charCodeAt(len - 1) === 0x3d) len-- + + return (len * 3) >>> 2 +} + +function toString(buffer) { + const len = buffer.byteLength + + let result = '' + + for (let i = 0; i < len; i += 3) { + result += + alphabet[buffer[i] >> 2] + + alphabet[((buffer[i] & 3) << 4) | (buffer[i + 1] >> 4)] + + alphabet[((buffer[i + 1] & 15) << 2) | (buffer[i + 2] >> 6)] + + alphabet[buffer[i + 2] & 63] + } + + if (len % 3 === 2) { + result = result.substring(0, result.length - 1) + '=' + } else if (len % 3 === 1) { + result = result.substring(0, result.length - 2) + '==' + } + + return result +} + +function write(buffer, string) { + const len = buffer.byteLength + + for (let i = 0, j = 0; j < len; i += 4) { + const a = codes[string.charCodeAt(i)] + const b = codes[string.charCodeAt(i + 1)] + const c = codes[string.charCodeAt(i + 2)] + const d = codes[string.charCodeAt(i + 3)] + + buffer[j++] = (a << 2) | (b >> 4) + buffer[j++] = ((b & 15) << 4) | (c >> 2) + buffer[j++] = ((c & 3) << 6) | (d & 63) + } + + return len +} + +module.exports = { + byteLength, + toString, + write +} diff --git a/node_modules/b4a/lib/hex.js b/node_modules/b4a/lib/hex.js new file mode 100644 index 0000000000000000000000000000000000000000..e72bb86ac95f4a40c71612522636654b7ba88574 --- /dev/null +++ b/node_modules/b4a/lib/hex.js @@ -0,0 +1,51 @@ +function byteLength(string) { + return string.length >>> 1 +} + +function toString(buffer) { + const len = buffer.byteLength + + buffer = new DataView(buffer.buffer, buffer.byteOffset, len) + + let result = '' + let i = 0 + + for (let n = len - (len % 4); i < n; i += 4) { + result += buffer.getUint32(i).toString(16).padStart(8, '0') + } + + for (; i < len; i++) { + result += buffer.getUint8(i).toString(16).padStart(2, '0') + } + + return result +} + +function write(buffer, string) { + const len = buffer.byteLength + + for (let i = 0; i < len; i++) { + const a = hexValue(string.charCodeAt(i * 2)) + const b = hexValue(string.charCodeAt(i * 2 + 1)) + + if (a === undefined || b === undefined) { + return i + } + + buffer[i] = (a << 4) | b + } + + return len +} + +module.exports = { + byteLength, + toString, + write +} + +function hexValue(char) { + if (char >= 0x30 && char <= 0x39) return char - 0x30 + if (char >= 0x41 && char <= 0x46) return char - 0x41 + 10 + if (char >= 0x61 && char <= 0x66) return char - 0x61 + 10 +} diff --git a/node_modules/b4a/lib/latin1.js b/node_modules/b4a/lib/latin1.js new file mode 100644 index 0000000000000000000000000000000000000000..f2714378bc95f6a92181e0f8976905cb2b3c39c0 --- /dev/null +++ b/node_modules/b4a/lib/latin1.js @@ -0,0 +1,31 @@ +function byteLength(string) { + return string.length +} + +function toString(buffer) { + const len = buffer.byteLength + + let result = '' + + for (let i = 0; i < len; i++) { + result += String.fromCharCode(buffer[i]) + } + + return result +} + +function write(buffer, string) { + const len = buffer.byteLength + + for (let i = 0; i < len; i++) { + buffer[i] = string.charCodeAt(i) + } + + return len +} + +module.exports = { + byteLength, + toString, + write +} diff --git a/node_modules/b4a/lib/utf16le.js b/node_modules/b4a/lib/utf16le.js new file mode 100644 index 0000000000000000000000000000000000000000..77f75d4271cab37cb3187ef19afef2b4930999f5 --- /dev/null +++ b/node_modules/b4a/lib/utf16le.js @@ -0,0 +1,40 @@ +function byteLength(string) { + return string.length * 2 +} + +function toString(buffer) { + const len = buffer.byteLength + + let result = '' + + for (let i = 0; i < len - 1; i += 2) { + result += String.fromCharCode(buffer[i] + buffer[i + 1] * 256) + } + + return result +} + +function write(buffer, string) { + const len = buffer.byteLength + + let units = len + + for (let i = 0; i < string.length; ++i) { + if ((units -= 2) < 0) break + + const c = string.charCodeAt(i) + const hi = c >> 8 + const lo = c % 256 + + buffer[i * 2] = lo + buffer[i * 2 + 1] = hi + } + + return len +} + +module.exports = { + byteLength, + toString, + write +} diff --git a/node_modules/b4a/lib/utf8.js b/node_modules/b4a/lib/utf8.js new file mode 100644 index 0000000000000000000000000000000000000000..ad15bfa9127ee511cb858c263da9d6e6c825705e --- /dev/null +++ b/node_modules/b4a/lib/utf8.js @@ -0,0 +1,144 @@ +function byteLength(string) { + let length = 0 + + for (let i = 0, n = string.length; i < n; i++) { + const code = string.charCodeAt(i) + + if (code >= 0xd800 && code <= 0xdbff && i + 1 < n) { + const code = string.charCodeAt(i + 1) + + if (code >= 0xdc00 && code <= 0xdfff) { + length += 4 + i++ + continue + } + } + + if (code <= 0x7f) length += 1 + else if (code <= 0x7ff) length += 2 + else length += 3 + } + + return length +} + +let toString + +if (typeof TextDecoder !== 'undefined') { + const decoder = new TextDecoder() + + toString = function toString(buffer) { + return decoder.decode(buffer) + } +} else { + toString = function toString(buffer) { + const len = buffer.byteLength + + let output = '' + let i = 0 + + while (i < len) { + let byte = buffer[i] + + if (byte <= 0x7f) { + output += String.fromCharCode(byte) + i++ + continue + } + + let bytesNeeded = 0 + let codePoint = 0 + + if (byte <= 0xdf) { + bytesNeeded = 1 + codePoint = byte & 0x1f + } else if (byte <= 0xef) { + bytesNeeded = 2 + codePoint = byte & 0x0f + } else if (byte <= 0xf4) { + bytesNeeded = 3 + codePoint = byte & 0x07 + } + + if (len - i - bytesNeeded > 0) { + let k = 0 + + while (k < bytesNeeded) { + byte = buffer[i + k + 1] + codePoint = (codePoint << 6) | (byte & 0x3f) + k += 1 + } + } else { + codePoint = 0xfffd + bytesNeeded = len - i + } + + output += String.fromCodePoint(codePoint) + i += bytesNeeded + 1 + } + + return output + } +} + +let write + +if (typeof TextEncoder !== 'undefined') { + const encoder = new TextEncoder() + + write = function write(buffer, string) { + return encoder.encodeInto(string, buffer).written + } +} else { + write = function write(buffer, string) { + const len = buffer.byteLength + + let i = 0 + let j = 0 + + while (i < string.length) { + const code = string.codePointAt(i) + + if (code <= 0x7f) { + if (j + 1 > len) break + buffer[j++] = code + i++ + continue + } + + let count = 0 + let bits = 0 + + if (code <= 0x7ff) { + count = 6 + bits = 0xc0 + } else if (code <= 0xffff) { + count = 12 + bits = 0xe0 + } else if (code <= 0x1fffff) { + count = 18 + bits = 0xf0 + } + + if (j + count / 6 + 1 > len) break + + buffer[j++] = bits | (code >> count) + count -= 6 + + while (count >= 0) { + buffer[j++] = 0x80 | ((code >> count) & 0x3f) + count -= 6 + } + + i += code >= 0x10000 ? 2 : 1 + } + + return j + } +} + +module.exports = { + byteLength, + toString, + write +} diff --git a/node_modules/b4a/package.json b/node_modules/b4a/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e5405a160b5f3adff762833e27964d0baac621a0 --- /dev/null +++ b/node_modules/b4a/package.json @@ -0,0 +1,51 @@ +{ + "name": "b4a", + "version": "1.8.1", + "description": "Bridging the gap between buffers and typed arrays", + "exports": { + "./package": "./package.json", + ".": { + "react-native": "./react-native.js", + "browser": "./browser.js", + "default": "./index.js" + } + }, + "files": [ + "browser.js", + "index.js", + "react-native.js", + "lib" + ], + "scripts": { + "format": "prettier --write . && lunte --fix", + "lint": "prettier --check . && lunte", + "test": "npm run test:bare && npm run test:node", + "test:bare": "brittle-bare --coverage test.mjs", + "test:node": "brittle-node --coverage test.mjs" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/holepunchto/b4a.git" + }, + "author": "Holepunch", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/holepunchto/b4a/issues" + }, + "homepage": "https://github.com/holepunchto/b4a#readme", + "devDependencies": { + "brittle": "^3.5.2", + "lunte": "^1.7.0", + "nanobench": "^3.0.0", + "prettier": "^3.6.2", + "prettier-config-holepunch": "^2.0.0" + }, + "peerDependencies": { + "react-native-b4a": "*" + }, + "peerDependenciesMeta": { + "react-native-b4a": { + "optional": true + } + } +} diff --git a/node_modules/b4a/react-native.js b/node_modules/b4a/react-native.js new file mode 100644 index 0000000000000000000000000000000000000000..0bf04e8e858646306d569fd3ee625fe6ef2966d0 --- /dev/null +++ b/node_modules/b4a/react-native.js @@ -0,0 +1,5 @@ +try { + module.exports = require('react-native-b4a') +} catch { + module.exports = require('./browser') +} diff --git a/node_modules/babel-plugin-polyfill-corejs2/LICENSE b/node_modules/babel-plugin-polyfill-corejs2/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b74971fede812cae3d1b3d7db474db739fac2d53 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs2/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Nicolò Ribaudo and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/babel-plugin-polyfill-corejs2/README.md b/node_modules/babel-plugin-polyfill-corejs2/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c5dfdc5c88a4414245eb09c9bdb4b4c3d01cc085 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs2/README.md @@ -0,0 +1,28 @@ +# babel-plugin-polyfill-corejs2 + +## Install + +Using npm: + +```sh +npm install --save-dev babel-plugin-polyfill-corejs2 +``` + +or using yarn: + +```sh +yarn add babel-plugin-polyfill-corejs2 --dev +``` + +## Usage + +Add this plugin to your Babel configuration: + +```json +{ + "plugins": [["polyfill-corejs2", { "method": "usage-global" }]] +} +``` + +This package supports the `usage-pure`, `usage-global`, and `entry-global` methods. +When `entry-global` is used, it replaces imports to `core-js`. diff --git a/node_modules/babel-plugin-polyfill-corejs2/esm/index.mjs b/node_modules/babel-plugin-polyfill-corejs2/esm/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b850877869aacaf0715ff77643ae0e075bad62f5 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs2/esm/index.mjs @@ -0,0 +1,395 @@ +import corejs2Polyfills from '@babel/compat-data/corejs2-built-ins'; +import semver from 'semver'; +import defineProvider from '@babel/helper-define-polyfill-provider'; +import * as _babel from '@babel/core'; + +const define = (name, pure, global = [], meta) => { + return { + name, + pure, + global, + meta + }; +}; +const pureAndGlobal = (pure, global, minRuntimeVersion = null) => define(global[0], pure, global, { + minRuntimeVersion +}); +const globalOnly = global => define(global[0], null, global); +const pureOnly = (pure, name) => define(name, pure, []); +const ArrayNatureIterators = ["es6.object.to-string", "es6.array.iterator", "web.dom.iterable"]; +const CommonIterators = ["es6.string.iterator", ...ArrayNatureIterators]; +const PromiseDependencies = ["es6.object.to-string", "es6.promise"]; +const BuiltIns = { + DataView: globalOnly(["es6.typed.data-view"]), + Float32Array: globalOnly(["es6.typed.float32-array"]), + Float64Array: globalOnly(["es6.typed.float64-array"]), + Int8Array: globalOnly(["es6.typed.int8-array"]), + Int16Array: globalOnly(["es6.typed.int16-array"]), + Int32Array: globalOnly(["es6.typed.int32-array"]), + Map: pureAndGlobal("map", ["es6.map", ...CommonIterators]), + Number: globalOnly(["es6.number.constructor"]), + Promise: pureAndGlobal("promise", PromiseDependencies), + RegExp: globalOnly(["es6.regexp.constructor"]), + Set: pureAndGlobal("set", ["es6.set", ...CommonIterators]), + Symbol: pureAndGlobal("symbol/index", ["es6.symbol"]), + Uint8Array: globalOnly(["es6.typed.uint8-array"]), + Uint8ClampedArray: globalOnly(["es6.typed.uint8-clamped-array"]), + Uint16Array: globalOnly(["es6.typed.uint16-array"]), + Uint32Array: globalOnly(["es6.typed.uint32-array"]), + WeakMap: pureAndGlobal("weak-map", ["es6.weak-map", ...CommonIterators]), + WeakSet: pureAndGlobal("weak-set", ["es6.weak-set", ...CommonIterators]), + setImmediate: pureOnly("set-immediate", "web.immediate"), + clearImmediate: pureOnly("clear-immediate", "web.immediate"), + parseFloat: pureOnly("parse-float", "es6.parse-float"), + parseInt: pureOnly("parse-int", "es6.parse-int") +}; +const InstanceProperties = { + __defineGetter__: globalOnly(["es7.object.define-getter"]), + __defineSetter__: globalOnly(["es7.object.define-setter"]), + __lookupGetter__: globalOnly(["es7.object.lookup-getter"]), + __lookupSetter__: globalOnly(["es7.object.lookup-setter"]), + anchor: globalOnly(["es6.string.anchor"]), + big: globalOnly(["es6.string.big"]), + bind: globalOnly(["es6.function.bind"]), + blink: globalOnly(["es6.string.blink"]), + bold: globalOnly(["es6.string.bold"]), + codePointAt: globalOnly(["es6.string.code-point-at"]), + copyWithin: globalOnly(["es6.array.copy-within"]), + endsWith: globalOnly(["es6.string.ends-with"]), + entries: globalOnly(ArrayNatureIterators), + every: globalOnly(["es6.array.every"]), + fill: globalOnly(["es6.array.fill"]), + filter: globalOnly(["es6.array.filter"]), + finally: globalOnly(["es7.promise.finally", ...PromiseDependencies]), + find: globalOnly(["es6.array.find"]), + findIndex: globalOnly(["es6.array.find-index"]), + fixed: globalOnly(["es6.string.fixed"]), + flags: globalOnly(["es6.regexp.flags"]), + flatMap: globalOnly(["es7.array.flat-map"]), + fontcolor: globalOnly(["es6.string.fontcolor"]), + fontsize: globalOnly(["es6.string.fontsize"]), + forEach: globalOnly(["es6.array.for-each"]), + includes: globalOnly(["es6.string.includes", "es7.array.includes"]), + indexOf: globalOnly(["es6.array.index-of"]), + italics: globalOnly(["es6.string.italics"]), + keys: globalOnly(ArrayNatureIterators), + lastIndexOf: globalOnly(["es6.array.last-index-of"]), + link: globalOnly(["es6.string.link"]), + map: globalOnly(["es6.array.map"]), + match: globalOnly(["es6.regexp.match"]), + name: globalOnly(["es6.function.name"]), + padStart: globalOnly(["es7.string.pad-start"]), + padEnd: globalOnly(["es7.string.pad-end"]), + reduce: globalOnly(["es6.array.reduce"]), + reduceRight: globalOnly(["es6.array.reduce-right"]), + repeat: globalOnly(["es6.string.repeat"]), + replace: globalOnly(["es6.regexp.replace"]), + search: globalOnly(["es6.regexp.search"]), + small: globalOnly(["es6.string.small"]), + some: globalOnly(["es6.array.some"]), + sort: globalOnly(["es6.array.sort"]), + split: globalOnly(["es6.regexp.split"]), + startsWith: globalOnly(["es6.string.starts-with"]), + strike: globalOnly(["es6.string.strike"]), + sub: globalOnly(["es6.string.sub"]), + sup: globalOnly(["es6.string.sup"]), + toISOString: globalOnly(["es6.date.to-iso-string"]), + toJSON: globalOnly(["es6.date.to-json"]), + toString: globalOnly(["es6.object.to-string", "es6.date.to-string", "es6.regexp.to-string"]), + trim: globalOnly(["es6.string.trim"]), + trimEnd: globalOnly(["es7.string.trim-right"]), + trimLeft: globalOnly(["es7.string.trim-left"]), + trimRight: globalOnly(["es7.string.trim-right"]), + trimStart: globalOnly(["es7.string.trim-left"]), + values: globalOnly(ArrayNatureIterators) +}; + +// This isn't present in older @babel/compat-data versions +if ("es6.array.slice" in corejs2Polyfills) { + InstanceProperties.slice = globalOnly(["es6.array.slice"]); +} +const StaticProperties = { + Array: { + from: pureAndGlobal("array/from", ["es6.symbol", "es6.array.from", ...CommonIterators]), + isArray: pureAndGlobal("array/is-array", ["es6.array.is-array"]), + of: pureAndGlobal("array/of", ["es6.array.of"]) + }, + Date: { + now: pureAndGlobal("date/now", ["es6.date.now"]) + }, + JSON: { + stringify: pureOnly("json/stringify", "es6.symbol") + }, + Math: { + // 'Math' was not included in the 7.0.0 + // release of '@babel/runtime'. See issue https://github.com/babel/babel/pull/8616. + acosh: pureAndGlobal("math/acosh", ["es6.math.acosh"], "7.0.1"), + asinh: pureAndGlobal("math/asinh", ["es6.math.asinh"], "7.0.1"), + atanh: pureAndGlobal("math/atanh", ["es6.math.atanh"], "7.0.1"), + cbrt: pureAndGlobal("math/cbrt", ["es6.math.cbrt"], "7.0.1"), + clz32: pureAndGlobal("math/clz32", ["es6.math.clz32"], "7.0.1"), + cosh: pureAndGlobal("math/cosh", ["es6.math.cosh"], "7.0.1"), + expm1: pureAndGlobal("math/expm1", ["es6.math.expm1"], "7.0.1"), + fround: pureAndGlobal("math/fround", ["es6.math.fround"], "7.0.1"), + hypot: pureAndGlobal("math/hypot", ["es6.math.hypot"], "7.0.1"), + imul: pureAndGlobal("math/imul", ["es6.math.imul"], "7.0.1"), + log1p: pureAndGlobal("math/log1p", ["es6.math.log1p"], "7.0.1"), + log10: pureAndGlobal("math/log10", ["es6.math.log10"], "7.0.1"), + log2: pureAndGlobal("math/log2", ["es6.math.log2"], "7.0.1"), + sign: pureAndGlobal("math/sign", ["es6.math.sign"], "7.0.1"), + sinh: pureAndGlobal("math/sinh", ["es6.math.sinh"], "7.0.1"), + tanh: pureAndGlobal("math/tanh", ["es6.math.tanh"], "7.0.1"), + trunc: pureAndGlobal("math/trunc", ["es6.math.trunc"], "7.0.1") + }, + Number: { + EPSILON: pureAndGlobal("number/epsilon", ["es6.number.epsilon"]), + MIN_SAFE_INTEGER: pureAndGlobal("number/min-safe-integer", ["es6.number.min-safe-integer"]), + MAX_SAFE_INTEGER: pureAndGlobal("number/max-safe-integer", ["es6.number.max-safe-integer"]), + isFinite: pureAndGlobal("number/is-finite", ["es6.number.is-finite"]), + isInteger: pureAndGlobal("number/is-integer", ["es6.number.is-integer"]), + isSafeInteger: pureAndGlobal("number/is-safe-integer", ["es6.number.is-safe-integer"]), + isNaN: pureAndGlobal("number/is-nan", ["es6.number.is-nan"]), + parseFloat: pureAndGlobal("number/parse-float", ["es6.number.parse-float"]), + parseInt: pureAndGlobal("number/parse-int", ["es6.number.parse-int"]) + }, + Object: { + assign: pureAndGlobal("object/assign", ["es6.object.assign"]), + create: pureAndGlobal("object/create", ["es6.object.create"]), + defineProperties: pureAndGlobal("object/define-properties", ["es6.object.define-properties"]), + defineProperty: pureAndGlobal("object/define-property", ["es6.object.define-property"]), + entries: pureAndGlobal("object/entries", ["es7.object.entries"]), + freeze: pureAndGlobal("object/freeze", ["es6.object.freeze"]), + getOwnPropertyDescriptor: pureAndGlobal("object/get-own-property-descriptor", ["es6.object.get-own-property-descriptor"]), + getOwnPropertyDescriptors: pureAndGlobal("object/get-own-property-descriptors", ["es7.object.get-own-property-descriptors"]), + getOwnPropertyNames: pureAndGlobal("object/get-own-property-names", ["es6.object.get-own-property-names"]), + getOwnPropertySymbols: pureAndGlobal("object/get-own-property-symbols", ["es6.symbol"]), + getPrototypeOf: pureAndGlobal("object/get-prototype-of", ["es6.object.get-prototype-of"]), + is: pureAndGlobal("object/is", ["es6.object.is"]), + isExtensible: pureAndGlobal("object/is-extensible", ["es6.object.is-extensible"]), + isFrozen: pureAndGlobal("object/is-frozen", ["es6.object.is-frozen"]), + isSealed: pureAndGlobal("object/is-sealed", ["es6.object.is-sealed"]), + keys: pureAndGlobal("object/keys", ["es6.object.keys"]), + preventExtensions: pureAndGlobal("object/prevent-extensions", ["es6.object.prevent-extensions"]), + seal: pureAndGlobal("object/seal", ["es6.object.seal"]), + setPrototypeOf: pureAndGlobal("object/set-prototype-of", ["es6.object.set-prototype-of"]), + values: pureAndGlobal("object/values", ["es7.object.values"]) + }, + Promise: { + all: globalOnly(CommonIterators), + race: globalOnly(CommonIterators) + }, + Reflect: { + apply: pureAndGlobal("reflect/apply", ["es6.reflect.apply"]), + construct: pureAndGlobal("reflect/construct", ["es6.reflect.construct"]), + defineProperty: pureAndGlobal("reflect/define-property", ["es6.reflect.define-property"]), + deleteProperty: pureAndGlobal("reflect/delete-property", ["es6.reflect.delete-property"]), + get: pureAndGlobal("reflect/get", ["es6.reflect.get"]), + getOwnPropertyDescriptor: pureAndGlobal("reflect/get-own-property-descriptor", ["es6.reflect.get-own-property-descriptor"]), + getPrototypeOf: pureAndGlobal("reflect/get-prototype-of", ["es6.reflect.get-prototype-of"]), + has: pureAndGlobal("reflect/has", ["es6.reflect.has"]), + isExtensible: pureAndGlobal("reflect/is-extensible", ["es6.reflect.is-extensible"]), + ownKeys: pureAndGlobal("reflect/own-keys", ["es6.reflect.own-keys"]), + preventExtensions: pureAndGlobal("reflect/prevent-extensions", ["es6.reflect.prevent-extensions"]), + set: pureAndGlobal("reflect/set", ["es6.reflect.set"]), + setPrototypeOf: pureAndGlobal("reflect/set-prototype-of", ["es6.reflect.set-prototype-of"]) + }, + String: { + at: pureOnly("string/at", "es7.string.at"), + fromCodePoint: pureAndGlobal("string/from-code-point", ["es6.string.from-code-point"]), + raw: pureAndGlobal("string/raw", ["es6.string.raw"]) + }, + Symbol: { + // FIXME: Pure disabled to work around zloirock/core-js#262. + asyncIterator: globalOnly(["es6.symbol", "es7.symbol.async-iterator"]), + for: pureOnly("symbol/for", "es6.symbol"), + hasInstance: pureOnly("symbol/has-instance", "es6.symbol"), + isConcatSpreadable: pureOnly("symbol/is-concat-spreadable", "es6.symbol"), + iterator: define("es6.symbol", "symbol/iterator", CommonIterators), + keyFor: pureOnly("symbol/key-for", "es6.symbol"), + match: pureAndGlobal("symbol/match", ["es6.regexp.match"]), + replace: pureOnly("symbol/replace", "es6.symbol"), + search: pureOnly("symbol/search", "es6.symbol"), + species: pureOnly("symbol/species", "es6.symbol"), + split: pureOnly("symbol/split", "es6.symbol"), + toPrimitive: pureOnly("symbol/to-primitive", "es6.symbol"), + toStringTag: pureOnly("symbol/to-string-tag", "es6.symbol"), + unscopables: pureOnly("symbol/unscopables", "es6.symbol") + } +}; + +const webPolyfills = { + "web.timers": {}, + "web.immediate": {}, + "web.dom.iterable": {} +}; +const purePolyfills = { + "es6.parse-float": {}, + "es6.parse-int": {}, + "es7.string.at": {} +}; +function addPlatformSpecificPolyfills (targets, method, polyfills) { + const targetNames = Object.keys(targets); + const isAnyTarget = !targetNames.length; + const isWebTarget = targetNames.some(name => name !== "node"); + return { + ...polyfills, + ...(method === "usage-pure" ? purePolyfills : null), + ...(isAnyTarget || isWebTarget ? webPolyfills : null) + }; +} + +function hasMinVersion(minVersion, runtimeVersion) { + // If the range is unavailable, we're running the script during Babel's + // build process, and we want to assume that all versions are satisfied so + // that the built output will include all definitions. + if (!runtimeVersion || !minVersion) return true; + runtimeVersion = String(runtimeVersion); + + // semver.intersects() has some surprising behavior with comparing ranges + // with preprelease versions. We add '^' to ensure that we are always + // comparing ranges with ranges, which sidesteps this logic. + // For example: + // + // semver.intersects(`<7.0.1`, "7.0.0-beta.0") // false - surprising + // semver.intersects(`<7.0.1`, "^7.0.0-beta.0") // true - expected + // + // This is because the first falls back to + // + // semver.satisfies("7.0.0-beta.0", `<7.0.1`) // false - surprising + // + // and this fails because a prerelease version can only satisfy a range + // if it is a prerelease within the same major/minor/patch range. + // + // Note: If this is found to have issues, please also revist the logic in + // babel-core's availableHelper() API. + if (semver.valid(runtimeVersion)) runtimeVersion = `^${runtimeVersion}`; + return !semver.intersects(`<${minVersion}`, runtimeVersion) && !semver.intersects(`>=8.0.0`, runtimeVersion); +} + +const { + types: t +} = _babel.default || _babel; +const BABEL_RUNTIME = "@babel/runtime-corejs2"; +const presetEnvCompat = "#__secret_key__@babel/preset-env__compatibility"; +const runtimeCompat = "#__secret_key__@babel/runtime__compatibility"; +const has = Function.call.bind(Object.hasOwnProperty); +var index = defineProvider(function (api, { + [presetEnvCompat]: { + entryInjectRegenerator = false, + noRuntimeName = false + } = {}, + [runtimeCompat]: { + useBabelRuntime = false, + runtimeVersion = "", + ext = ".js" + } = {} +}) { + const resolve = api.createMetaResolver({ + global: BuiltIns, + static: StaticProperties, + instance: InstanceProperties + }); + const { + debug, + shouldInjectPolyfill, + method + } = api; + const polyfills = addPlatformSpecificPolyfills(api.targets, method, corejs2Polyfills); + const coreJSBase = useBabelRuntime ? `${BABEL_RUNTIME}/core-js` : method === "usage-pure" ? "core-js/library/fn" : "core-js/modules"; + function inject(name, utils) { + if (typeof name === "string") { + // Some polyfills aren't always available, for example + // web.dom.iterable when targeting node + if (has(polyfills, name) && shouldInjectPolyfill(name)) { + debug(name); + utils.injectGlobalImport(`${coreJSBase}/${name}.js`); + } + return; + } + name.forEach(name => inject(name, utils)); + } + function maybeInjectPure(desc, hint, utils) { + let { + pure, + meta, + name + } = desc; + if (!pure || !shouldInjectPolyfill(name)) return; + if (runtimeVersion && meta && meta.minRuntimeVersion && !hasMinVersion(meta && meta.minRuntimeVersion, runtimeVersion)) { + return; + } + + // Unfortunately core-js and @babel/runtime-corejs2 don't have the same + // directory structure, so we need to special case this. + if (useBabelRuntime && pure === "symbol/index") pure = "symbol"; + return utils.injectDefaultImport(`${coreJSBase}/${pure}${ext}`, hint); + } + return { + name: "corejs2", + runtimeName: noRuntimeName ? null : BABEL_RUNTIME, + polyfills, + entryGlobal(meta, utils, path) { + if (meta.kind === "import" && meta.source === "core-js") { + debug(null); + inject(Object.keys(polyfills), utils); + if (entryInjectRegenerator) { + utils.injectGlobalImport("regenerator-runtime/runtime.js"); + } + path.remove(); + } + }, + usageGlobal(meta, utils) { + const resolved = resolve(meta); + if (!resolved) return; + let deps = resolved.desc.global; + if (resolved.kind !== "global" && "object" in meta && meta.object && meta.placement === "prototype") { + const low = meta.object.toLowerCase(); + deps = deps.filter(m => m.includes(low)); + } + inject(deps, utils); + }, + usagePure(meta, utils, path) { + if (meta.kind === "in") { + if (meta.key === "Symbol.iterator") { + path.replaceWith(t.callExpression(utils.injectDefaultImport(`${coreJSBase}/is-iterable${ext}`, "isIterable"), [path.node.right] // meta.kind === "in" narrows this + )); + } + return; + } + if (path.parentPath.isUnaryExpression({ + operator: "delete" + })) return; + if (meta.kind === "property") { + // We can't compile destructuring. + if (!path.isMemberExpression()) return; + if (!path.isReferenced()) return; + if (meta.key === "Symbol.iterator" && shouldInjectPolyfill("es6.symbol") && path.parentPath.isCallExpression({ + callee: path.node + }) && path.parentPath.node.arguments.length === 0) { + path.parentPath.replaceWith(t.callExpression(utils.injectDefaultImport(`${coreJSBase}/get-iterator${ext}`, "getIterator"), [path.node.object])); + path.skip(); + return; + } + } + const resolved = resolve(meta); + if (!resolved) return; + const id = maybeInjectPure(resolved.desc, resolved.name, utils); + if (id) path.replaceWith(id); + }, + visitor: method === "usage-global" && { + // yield* + YieldExpression(path) { + if (path.node.delegate) { + inject("web.dom.iterable", api.getUtils(path)); + } + }, + // for-of, [a, b] = c + "ForOfStatement|ArrayPattern"(path) { + CommonIterators.forEach(name => inject(name, api.getUtils(path))); + } + } + }; +}); + +export { index as default }; +//# sourceMappingURL=index.mjs.map diff --git a/node_modules/babel-plugin-polyfill-corejs2/esm/index.mjs.map b/node_modules/babel-plugin-polyfill-corejs2/esm/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..b5613e96e615ea634195666c0d692f83893b3dec --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs2/esm/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sources":["../src/built-in-definitions.ts","../src/add-platform-specific-polyfills.ts","../src/helpers.ts","../src/index.ts"],"sourcesContent":["import corejs2Polyfills from \"@babel/compat-data/corejs2-built-ins\";\n\ntype ObjectMap = { [name: string]: V };\n\ntype PolyfillDescriptor = {\n name: string;\n pure: string | null;\n global: string[];\n meta: T | null;\n};\n\ntype CoreJS2Meta = {\n minRuntimeVersion: string | null;\n};\n\nconst define = (\n name: string,\n pure?: string | null,\n global: string[] = [],\n meta?: T | null,\n): PolyfillDescriptor => {\n return { name, pure, global, meta };\n};\n\nconst pureAndGlobal = (\n pure: string,\n global: string[],\n minRuntimeVersion: string | null = null,\n) => define(global[0], pure, global, { minRuntimeVersion });\n\nconst globalOnly = (global: string[]) =>\n define(global[0], null, global);\n\nconst pureOnly = (pure: string, name: string) =>\n define(name, pure, []);\n\nconst ArrayNatureIterators = [\n \"es6.object.to-string\",\n \"es6.array.iterator\",\n \"web.dom.iterable\",\n];\n\nexport const CommonIterators = [\"es6.string.iterator\", ...ArrayNatureIterators];\n\nconst PromiseDependencies = [\"es6.object.to-string\", \"es6.promise\"];\n\nexport const BuiltIns: ObjectMap> = {\n DataView: globalOnly([\"es6.typed.data-view\"]),\n Float32Array: globalOnly([\"es6.typed.float32-array\"]),\n Float64Array: globalOnly([\"es6.typed.float64-array\"]),\n Int8Array: globalOnly([\"es6.typed.int8-array\"]),\n Int16Array: globalOnly([\"es6.typed.int16-array\"]),\n Int32Array: globalOnly([\"es6.typed.int32-array\"]),\n Map: pureAndGlobal(\"map\", [\"es6.map\", ...CommonIterators]),\n Number: globalOnly([\"es6.number.constructor\"]),\n Promise: pureAndGlobal(\"promise\", PromiseDependencies),\n RegExp: globalOnly([\"es6.regexp.constructor\"]),\n Set: pureAndGlobal(\"set\", [\"es6.set\", ...CommonIterators]),\n Symbol: pureAndGlobal(\"symbol/index\", [\"es6.symbol\"]),\n Uint8Array: globalOnly([\"es6.typed.uint8-array\"]),\n Uint8ClampedArray: globalOnly([\"es6.typed.uint8-clamped-array\"]),\n Uint16Array: globalOnly([\"es6.typed.uint16-array\"]),\n Uint32Array: globalOnly([\"es6.typed.uint32-array\"]),\n WeakMap: pureAndGlobal(\"weak-map\", [\"es6.weak-map\", ...CommonIterators]),\n WeakSet: pureAndGlobal(\"weak-set\", [\"es6.weak-set\", ...CommonIterators]),\n\n setImmediate: pureOnly(\"set-immediate\", \"web.immediate\"),\n clearImmediate: pureOnly(\"clear-immediate\", \"web.immediate\"),\n parseFloat: pureOnly(\"parse-float\", \"es6.parse-float\"),\n parseInt: pureOnly(\"parse-int\", \"es6.parse-int\"),\n};\n\nexport const InstanceProperties: ObjectMap> = {\n __defineGetter__: globalOnly([\"es7.object.define-getter\"]),\n __defineSetter__: globalOnly([\"es7.object.define-setter\"]),\n __lookupGetter__: globalOnly([\"es7.object.lookup-getter\"]),\n __lookupSetter__: globalOnly([\"es7.object.lookup-setter\"]),\n anchor: globalOnly([\"es6.string.anchor\"]),\n big: globalOnly([\"es6.string.big\"]),\n bind: globalOnly([\"es6.function.bind\"]),\n blink: globalOnly([\"es6.string.blink\"]),\n bold: globalOnly([\"es6.string.bold\"]),\n codePointAt: globalOnly([\"es6.string.code-point-at\"]),\n copyWithin: globalOnly([\"es6.array.copy-within\"]),\n endsWith: globalOnly([\"es6.string.ends-with\"]),\n entries: globalOnly(ArrayNatureIterators),\n every: globalOnly([\"es6.array.every\"]),\n fill: globalOnly([\"es6.array.fill\"]),\n filter: globalOnly([\"es6.array.filter\"]),\n finally: globalOnly([\"es7.promise.finally\", ...PromiseDependencies]),\n find: globalOnly([\"es6.array.find\"]),\n findIndex: globalOnly([\"es6.array.find-index\"]),\n fixed: globalOnly([\"es6.string.fixed\"]),\n flags: globalOnly([\"es6.regexp.flags\"]),\n flatMap: globalOnly([\"es7.array.flat-map\"]),\n fontcolor: globalOnly([\"es6.string.fontcolor\"]),\n fontsize: globalOnly([\"es6.string.fontsize\"]),\n forEach: globalOnly([\"es6.array.for-each\"]),\n includes: globalOnly([\"es6.string.includes\", \"es7.array.includes\"]),\n indexOf: globalOnly([\"es6.array.index-of\"]),\n italics: globalOnly([\"es6.string.italics\"]),\n keys: globalOnly(ArrayNatureIterators),\n lastIndexOf: globalOnly([\"es6.array.last-index-of\"]),\n link: globalOnly([\"es6.string.link\"]),\n map: globalOnly([\"es6.array.map\"]),\n match: globalOnly([\"es6.regexp.match\"]),\n name: globalOnly([\"es6.function.name\"]),\n padStart: globalOnly([\"es7.string.pad-start\"]),\n padEnd: globalOnly([\"es7.string.pad-end\"]),\n reduce: globalOnly([\"es6.array.reduce\"]),\n reduceRight: globalOnly([\"es6.array.reduce-right\"]),\n repeat: globalOnly([\"es6.string.repeat\"]),\n replace: globalOnly([\"es6.regexp.replace\"]),\n search: globalOnly([\"es6.regexp.search\"]),\n small: globalOnly([\"es6.string.small\"]),\n some: globalOnly([\"es6.array.some\"]),\n sort: globalOnly([\"es6.array.sort\"]),\n split: globalOnly([\"es6.regexp.split\"]),\n startsWith: globalOnly([\"es6.string.starts-with\"]),\n strike: globalOnly([\"es6.string.strike\"]),\n sub: globalOnly([\"es6.string.sub\"]),\n sup: globalOnly([\"es6.string.sup\"]),\n toISOString: globalOnly([\"es6.date.to-iso-string\"]),\n toJSON: globalOnly([\"es6.date.to-json\"]),\n toString: globalOnly([\n \"es6.object.to-string\",\n \"es6.date.to-string\",\n \"es6.regexp.to-string\",\n ]),\n trim: globalOnly([\"es6.string.trim\"]),\n trimEnd: globalOnly([\"es7.string.trim-right\"]),\n trimLeft: globalOnly([\"es7.string.trim-left\"]),\n trimRight: globalOnly([\"es7.string.trim-right\"]),\n trimStart: globalOnly([\"es7.string.trim-left\"]),\n values: globalOnly(ArrayNatureIterators),\n};\n\n// This isn't present in older @babel/compat-data versions\nif (\"es6.array.slice\" in corejs2Polyfills) {\n InstanceProperties.slice = globalOnly([\"es6.array.slice\"]);\n}\n\nexport const StaticProperties: ObjectMap<\n ObjectMap>\n> = {\n Array: {\n from: pureAndGlobal(\"array/from\", [\n \"es6.symbol\",\n \"es6.array.from\",\n ...CommonIterators,\n ]),\n isArray: pureAndGlobal(\"array/is-array\", [\"es6.array.is-array\"]),\n of: pureAndGlobal(\"array/of\", [\"es6.array.of\"]),\n },\n\n Date: {\n now: pureAndGlobal(\"date/now\", [\"es6.date.now\"]),\n },\n\n JSON: {\n stringify: pureOnly(\"json/stringify\", \"es6.symbol\"),\n },\n\n Math: {\n // 'Math' was not included in the 7.0.0\n // release of '@babel/runtime'. See issue https://github.com/babel/babel/pull/8616.\n acosh: pureAndGlobal(\"math/acosh\", [\"es6.math.acosh\"], \"7.0.1\"),\n asinh: pureAndGlobal(\"math/asinh\", [\"es6.math.asinh\"], \"7.0.1\"),\n atanh: pureAndGlobal(\"math/atanh\", [\"es6.math.atanh\"], \"7.0.1\"),\n cbrt: pureAndGlobal(\"math/cbrt\", [\"es6.math.cbrt\"], \"7.0.1\"),\n clz32: pureAndGlobal(\"math/clz32\", [\"es6.math.clz32\"], \"7.0.1\"),\n cosh: pureAndGlobal(\"math/cosh\", [\"es6.math.cosh\"], \"7.0.1\"),\n expm1: pureAndGlobal(\"math/expm1\", [\"es6.math.expm1\"], \"7.0.1\"),\n fround: pureAndGlobal(\"math/fround\", [\"es6.math.fround\"], \"7.0.1\"),\n hypot: pureAndGlobal(\"math/hypot\", [\"es6.math.hypot\"], \"7.0.1\"),\n imul: pureAndGlobal(\"math/imul\", [\"es6.math.imul\"], \"7.0.1\"),\n log1p: pureAndGlobal(\"math/log1p\", [\"es6.math.log1p\"], \"7.0.1\"),\n log10: pureAndGlobal(\"math/log10\", [\"es6.math.log10\"], \"7.0.1\"),\n log2: pureAndGlobal(\"math/log2\", [\"es6.math.log2\"], \"7.0.1\"),\n sign: pureAndGlobal(\"math/sign\", [\"es6.math.sign\"], \"7.0.1\"),\n sinh: pureAndGlobal(\"math/sinh\", [\"es6.math.sinh\"], \"7.0.1\"),\n tanh: pureAndGlobal(\"math/tanh\", [\"es6.math.tanh\"], \"7.0.1\"),\n trunc: pureAndGlobal(\"math/trunc\", [\"es6.math.trunc\"], \"7.0.1\"),\n },\n\n Number: {\n EPSILON: pureAndGlobal(\"number/epsilon\", [\"es6.number.epsilon\"]),\n MIN_SAFE_INTEGER: pureAndGlobal(\"number/min-safe-integer\", [\n \"es6.number.min-safe-integer\",\n ]),\n MAX_SAFE_INTEGER: pureAndGlobal(\"number/max-safe-integer\", [\n \"es6.number.max-safe-integer\",\n ]),\n isFinite: pureAndGlobal(\"number/is-finite\", [\"es6.number.is-finite\"]),\n isInteger: pureAndGlobal(\"number/is-integer\", [\"es6.number.is-integer\"]),\n isSafeInteger: pureAndGlobal(\"number/is-safe-integer\", [\n \"es6.number.is-safe-integer\",\n ]),\n isNaN: pureAndGlobal(\"number/is-nan\", [\"es6.number.is-nan\"]),\n parseFloat: pureAndGlobal(\"number/parse-float\", [\"es6.number.parse-float\"]),\n parseInt: pureAndGlobal(\"number/parse-int\", [\"es6.number.parse-int\"]),\n },\n\n Object: {\n assign: pureAndGlobal(\"object/assign\", [\"es6.object.assign\"]),\n create: pureAndGlobal(\"object/create\", [\"es6.object.create\"]),\n defineProperties: pureAndGlobal(\"object/define-properties\", [\n \"es6.object.define-properties\",\n ]),\n defineProperty: pureAndGlobal(\"object/define-property\", [\n \"es6.object.define-property\",\n ]),\n entries: pureAndGlobal(\"object/entries\", [\"es7.object.entries\"]),\n freeze: pureAndGlobal(\"object/freeze\", [\"es6.object.freeze\"]),\n getOwnPropertyDescriptor: pureAndGlobal(\n \"object/get-own-property-descriptor\",\n [\"es6.object.get-own-property-descriptor\"],\n ),\n getOwnPropertyDescriptors: pureAndGlobal(\n \"object/get-own-property-descriptors\",\n [\"es7.object.get-own-property-descriptors\"],\n ),\n getOwnPropertyNames: pureAndGlobal(\"object/get-own-property-names\", [\n \"es6.object.get-own-property-names\",\n ]),\n getOwnPropertySymbols: pureAndGlobal(\"object/get-own-property-symbols\", [\n \"es6.symbol\",\n ]),\n getPrototypeOf: pureAndGlobal(\"object/get-prototype-of\", [\n \"es6.object.get-prototype-of\",\n ]),\n is: pureAndGlobal(\"object/is\", [\"es6.object.is\"]),\n isExtensible: pureAndGlobal(\"object/is-extensible\", [\n \"es6.object.is-extensible\",\n ]),\n isFrozen: pureAndGlobal(\"object/is-frozen\", [\"es6.object.is-frozen\"]),\n isSealed: pureAndGlobal(\"object/is-sealed\", [\"es6.object.is-sealed\"]),\n keys: pureAndGlobal(\"object/keys\", [\"es6.object.keys\"]),\n preventExtensions: pureAndGlobal(\"object/prevent-extensions\", [\n \"es6.object.prevent-extensions\",\n ]),\n seal: pureAndGlobal(\"object/seal\", [\"es6.object.seal\"]),\n setPrototypeOf: pureAndGlobal(\"object/set-prototype-of\", [\n \"es6.object.set-prototype-of\",\n ]),\n values: pureAndGlobal(\"object/values\", [\"es7.object.values\"]),\n },\n\n Promise: {\n all: globalOnly(CommonIterators),\n race: globalOnly(CommonIterators),\n },\n\n Reflect: {\n apply: pureAndGlobal(\"reflect/apply\", [\"es6.reflect.apply\"]),\n construct: pureAndGlobal(\"reflect/construct\", [\"es6.reflect.construct\"]),\n defineProperty: pureAndGlobal(\"reflect/define-property\", [\n \"es6.reflect.define-property\",\n ]),\n deleteProperty: pureAndGlobal(\"reflect/delete-property\", [\n \"es6.reflect.delete-property\",\n ]),\n get: pureAndGlobal(\"reflect/get\", [\"es6.reflect.get\"]),\n getOwnPropertyDescriptor: pureAndGlobal(\n \"reflect/get-own-property-descriptor\",\n [\"es6.reflect.get-own-property-descriptor\"],\n ),\n getPrototypeOf: pureAndGlobal(\"reflect/get-prototype-of\", [\n \"es6.reflect.get-prototype-of\",\n ]),\n has: pureAndGlobal(\"reflect/has\", [\"es6.reflect.has\"]),\n isExtensible: pureAndGlobal(\"reflect/is-extensible\", [\n \"es6.reflect.is-extensible\",\n ]),\n ownKeys: pureAndGlobal(\"reflect/own-keys\", [\"es6.reflect.own-keys\"]),\n preventExtensions: pureAndGlobal(\"reflect/prevent-extensions\", [\n \"es6.reflect.prevent-extensions\",\n ]),\n set: pureAndGlobal(\"reflect/set\", [\"es6.reflect.set\"]),\n setPrototypeOf: pureAndGlobal(\"reflect/set-prototype-of\", [\n \"es6.reflect.set-prototype-of\",\n ]),\n },\n\n String: {\n at: pureOnly(\"string/at\", \"es7.string.at\"),\n fromCodePoint: pureAndGlobal(\"string/from-code-point\", [\n \"es6.string.from-code-point\",\n ]),\n raw: pureAndGlobal(\"string/raw\", [\"es6.string.raw\"]),\n },\n\n Symbol: {\n // FIXME: Pure disabled to work around zloirock/core-js#262.\n asyncIterator: globalOnly([\"es6.symbol\", \"es7.symbol.async-iterator\"]),\n for: pureOnly(\"symbol/for\", \"es6.symbol\"),\n hasInstance: pureOnly(\"symbol/has-instance\", \"es6.symbol\"),\n isConcatSpreadable: pureOnly(\"symbol/is-concat-spreadable\", \"es6.symbol\"),\n iterator: define(\"es6.symbol\", \"symbol/iterator\", CommonIterators),\n keyFor: pureOnly(\"symbol/key-for\", \"es6.symbol\"),\n match: pureAndGlobal(\"symbol/match\", [\"es6.regexp.match\"]),\n replace: pureOnly(\"symbol/replace\", \"es6.symbol\"),\n search: pureOnly(\"symbol/search\", \"es6.symbol\"),\n species: pureOnly(\"symbol/species\", \"es6.symbol\"),\n split: pureOnly(\"symbol/split\", \"es6.symbol\"),\n toPrimitive: pureOnly(\"symbol/to-primitive\", \"es6.symbol\"),\n toStringTag: pureOnly(\"symbol/to-string-tag\", \"es6.symbol\"),\n unscopables: pureOnly(\"symbol/unscopables\", \"es6.symbol\"),\n },\n};\n","import type { Targets } from \"@babel/helper-define-polyfill-provider\";\n\nconst webPolyfills = {\n \"web.timers\": {},\n \"web.immediate\": {},\n \"web.dom.iterable\": {},\n};\n\nconst purePolyfills = {\n \"es6.parse-float\": {},\n \"es6.parse-int\": {},\n \"es7.string.at\": {},\n};\n\nexport default function (targets: Targets, method: string, polyfills: any) {\n const targetNames = Object.keys(targets);\n const isAnyTarget = !targetNames.length;\n const isWebTarget = targetNames.some(name => name !== \"node\");\n\n return {\n ...polyfills,\n ...(method === \"usage-pure\" ? purePolyfills : null),\n ...(isAnyTarget || isWebTarget ? webPolyfills : null),\n };\n}\n","import semver from \"semver\";\n\nexport function hasMinVersion(\n minVersion?: string | null,\n runtimeVersion?: string | number | null,\n) {\n // If the range is unavailable, we're running the script during Babel's\n // build process, and we want to assume that all versions are satisfied so\n // that the built output will include all definitions.\n if (!runtimeVersion || !minVersion) return true;\n\n runtimeVersion = String(runtimeVersion);\n\n // semver.intersects() has some surprising behavior with comparing ranges\n // with preprelease versions. We add '^' to ensure that we are always\n // comparing ranges with ranges, which sidesteps this logic.\n // For example:\n //\n // semver.intersects(`<7.0.1`, \"7.0.0-beta.0\") // false - surprising\n // semver.intersects(`<7.0.1`, \"^7.0.0-beta.0\") // true - expected\n //\n // This is because the first falls back to\n //\n // semver.satisfies(\"7.0.0-beta.0\", `<7.0.1`) // false - surprising\n //\n // and this fails because a prerelease version can only satisfy a range\n // if it is a prerelease within the same major/minor/patch range.\n //\n // Note: If this is found to have issues, please also revist the logic in\n // babel-core's availableHelper() API.\n if (semver.valid(runtimeVersion)) runtimeVersion = `^${runtimeVersion}`;\n\n return (\n !semver.intersects(`<${minVersion}`, runtimeVersion) &&\n !semver.intersects(`>=8.0.0`, runtimeVersion)\n );\n}\n","import corejs2Polyfills from \"@babel/compat-data/corejs2-built-ins\";\nimport {\n BuiltIns,\n StaticProperties,\n InstanceProperties,\n CommonIterators,\n} from \"./built-in-definitions\";\nimport addPlatformSpecificPolyfills from \"./add-platform-specific-polyfills\";\nimport { hasMinVersion } from \"./helpers\";\n\nimport defineProvider from \"@babel/helper-define-polyfill-provider\";\nimport type { NodePath } from \"@babel/traverse\";\nimport { types as t } from \"@babel/core\";\n\nconst BABEL_RUNTIME = \"@babel/runtime-corejs2\";\n\nconst presetEnvCompat = \"#__secret_key__@babel/preset-env__compatibility\";\nconst runtimeCompat = \"#__secret_key__@babel/runtime__compatibility\";\n\nconst has = Function.call.bind(Object.hasOwnProperty);\n\ntype Options = {\n [presetEnvCompat]?: {\n entryInjectRegenerator: boolean;\n noRuntimeName: boolean;\n };\n [runtimeCompat]?: {\n useBabelRuntime: boolean;\n runtimeVersion: string;\n ext: string;\n };\n};\n\nexport default defineProvider(function (\n api,\n {\n [presetEnvCompat]: {\n entryInjectRegenerator = false,\n noRuntimeName = false,\n } = {},\n [runtimeCompat]: {\n useBabelRuntime = false,\n runtimeVersion = \"\",\n ext = \".js\",\n } = {},\n },\n) {\n const resolve = api.createMetaResolver({\n global: BuiltIns,\n static: StaticProperties,\n instance: InstanceProperties,\n });\n\n const { debug, shouldInjectPolyfill, method } = api;\n\n const polyfills = addPlatformSpecificPolyfills(\n api.targets,\n method,\n corejs2Polyfills,\n );\n\n const coreJSBase = useBabelRuntime\n ? `${BABEL_RUNTIME}/core-js`\n : method === \"usage-pure\"\n ? \"core-js/library/fn\"\n : \"core-js/modules\";\n\n function inject(name: string | string[], utils) {\n if (typeof name === \"string\") {\n // Some polyfills aren't always available, for example\n // web.dom.iterable when targeting node\n if (has(polyfills, name) && shouldInjectPolyfill(name)) {\n debug(name);\n utils.injectGlobalImport(`${coreJSBase}/${name}.js`);\n }\n return;\n }\n\n name.forEach(name => inject(name, utils));\n }\n\n function maybeInjectPure(desc, hint, utils) {\n let { pure, meta, name } = desc;\n\n if (!pure || !shouldInjectPolyfill(name)) return;\n\n if (\n runtimeVersion &&\n meta &&\n meta.minRuntimeVersion &&\n !hasMinVersion(meta && meta.minRuntimeVersion, runtimeVersion)\n ) {\n return;\n }\n\n // Unfortunately core-js and @babel/runtime-corejs2 don't have the same\n // directory structure, so we need to special case this.\n if (useBabelRuntime && pure === \"symbol/index\") pure = \"symbol\";\n\n return utils.injectDefaultImport(`${coreJSBase}/${pure}${ext}`, hint);\n }\n\n return {\n name: \"corejs2\",\n\n runtimeName: noRuntimeName ? null : BABEL_RUNTIME,\n\n polyfills,\n\n entryGlobal(meta, utils, path) {\n if (meta.kind === \"import\" && meta.source === \"core-js\") {\n debug(null);\n\n inject(Object.keys(polyfills), utils);\n\n if (entryInjectRegenerator) {\n utils.injectGlobalImport(\"regenerator-runtime/runtime.js\");\n }\n\n path.remove();\n }\n },\n\n usageGlobal(meta, utils): undefined {\n const resolved = resolve(meta);\n if (!resolved) return;\n\n let deps = resolved.desc.global;\n\n if (\n resolved.kind !== \"global\" &&\n \"object\" in meta &&\n meta.object &&\n meta.placement === \"prototype\"\n ) {\n const low = meta.object.toLowerCase();\n deps = deps.filter(m => m.includes(low));\n }\n\n inject(deps, utils);\n },\n\n usagePure(meta, utils, path) {\n if (meta.kind === \"in\") {\n if (meta.key === \"Symbol.iterator\") {\n path.replaceWith(\n t.callExpression(\n utils.injectDefaultImport(\n `${coreJSBase}/is-iterable${ext}`,\n \"isIterable\",\n ),\n [(path.node as t.BinaryExpression).right], // meta.kind === \"in\" narrows this\n ),\n );\n }\n\n return;\n }\n\n if (path.parentPath.isUnaryExpression({ operator: \"delete\" })) return;\n\n if (meta.kind === \"property\") {\n // We can't compile destructuring.\n if (!path.isMemberExpression()) return;\n if (!path.isReferenced()) return;\n\n if (\n meta.key === \"Symbol.iterator\" &&\n shouldInjectPolyfill(\"es6.symbol\") &&\n path.parentPath.isCallExpression({ callee: path.node }) &&\n path.parentPath.node.arguments.length === 0\n ) {\n path.parentPath.replaceWith(\n t.callExpression(\n utils.injectDefaultImport(\n `${coreJSBase}/get-iterator${ext}`,\n \"getIterator\",\n ),\n [path.node.object],\n ),\n );\n path.skip();\n\n return;\n }\n }\n\n const resolved = resolve(meta);\n if (!resolved) return;\n\n const id = maybeInjectPure(resolved.desc, resolved.name, utils);\n if (id) path.replaceWith(id);\n },\n\n visitor: method === \"usage-global\" && {\n // yield*\n YieldExpression(path: NodePath) {\n if (path.node.delegate) {\n inject(\"web.dom.iterable\", api.getUtils(path));\n }\n },\n\n // for-of, [a, b] = c\n \"ForOfStatement|ArrayPattern\"(\n path: NodePath,\n ) {\n CommonIterators.forEach(name => inject(name, api.getUtils(path)));\n },\n },\n };\n});\n"],"names":["define","name","pure","global","meta","pureAndGlobal","minRuntimeVersion","globalOnly","pureOnly","ArrayNatureIterators","CommonIterators","PromiseDependencies","BuiltIns","DataView","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Map","Number","Promise","RegExp","Set","Symbol","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","WeakSet","setImmediate","clearImmediate","parseFloat","parseInt","InstanceProperties","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","anchor","big","bind","blink","bold","codePointAt","copyWithin","endsWith","entries","every","fill","filter","finally","find","findIndex","fixed","flags","flatMap","fontcolor","fontsize","forEach","includes","indexOf","italics","keys","lastIndexOf","link","map","match","padStart","padEnd","reduce","reduceRight","repeat","replace","search","small","some","sort","split","startsWith","strike","sub","sup","toISOString","toJSON","toString","trim","trimEnd","trimLeft","trimRight","trimStart","values","corejs2Polyfills","slice","StaticProperties","Array","from","isArray","of","Date","now","JSON","stringify","Math","acosh","asinh","atanh","cbrt","clz32","cosh","expm1","fround","hypot","imul","log1p","log10","log2","sign","sinh","tanh","trunc","EPSILON","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","isFinite","isInteger","isSafeInteger","isNaN","Object","assign","create","defineProperties","defineProperty","freeze","getOwnPropertyDescriptor","getOwnPropertyDescriptors","getOwnPropertyNames","getOwnPropertySymbols","getPrototypeOf","is","isExtensible","isFrozen","isSealed","preventExtensions","seal","setPrototypeOf","all","race","Reflect","apply","construct","deleteProperty","get","has","ownKeys","set","String","at","fromCodePoint","raw","asyncIterator","for","hasInstance","isConcatSpreadable","iterator","keyFor","species","toPrimitive","toStringTag","unscopables","webPolyfills","purePolyfills","targets","method","polyfills","targetNames","isAnyTarget","length","isWebTarget","hasMinVersion","minVersion","runtimeVersion","semver","valid","intersects","types","t","_babel","default","BABEL_RUNTIME","presetEnvCompat","runtimeCompat","Function","call","hasOwnProperty","defineProvider","api","entryInjectRegenerator","noRuntimeName","useBabelRuntime","ext","resolve","createMetaResolver","static","instance","debug","shouldInjectPolyfill","addPlatformSpecificPolyfills","coreJSBase","inject","utils","injectGlobalImport","maybeInjectPure","desc","hint","injectDefaultImport","runtimeName","entryGlobal","path","kind","source","remove","usageGlobal","resolved","deps","object","placement","low","toLowerCase","m","usagePure","key","replaceWith","callExpression","node","right","parentPath","isUnaryExpression","operator","isMemberExpression","isReferenced","isCallExpression","callee","arguments","skip","id","visitor","YieldExpression","delegate","getUtils","ForOfStatement|ArrayPattern"],"mappings":";;;;;AAeA,MAAMA,MAAM,GAAGA,CACbC,IAAY,EACZC,IAAoB,EACpBC,MAAgB,GAAG,EAAE,EACrBC,IAAe,KACW;EAC1B,OAAO;IAAEH,IAAI;IAAEC,IAAI;IAAEC,MAAM;AAAEC,IAAAA,IAAAA;GAAM,CAAA;AACrC,CAAC,CAAA;AAED,MAAMC,aAAa,GAAGA,CACpBH,IAAY,EACZC,MAAgB,EAChBG,iBAAgC,GAAG,IAAI,KACpCN,MAAM,CAAcG,MAAM,CAAC,CAAC,CAAC,EAAED,IAAI,EAAEC,MAAM,EAAE;AAAEG,EAAAA,iBAAAA;AAAkB,CAAC,CAAC,CAAA;AAExE,MAAMC,UAAU,GAAIJ,MAAgB,IAClCH,MAAM,CAAcG,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,EAAEA,MAAM,CAAC,CAAA;AAE9C,MAAMK,QAAQ,GAAGA,CAACN,IAAY,EAAED,IAAY,KAC1CD,MAAM,CAAcC,IAAI,EAAEC,IAAI,EAAE,EAAE,CAAC,CAAA;AAErC,MAAMO,oBAAoB,GAAG,CAC3B,sBAAsB,EACtB,oBAAoB,EACpB,kBAAkB,CACnB,CAAA;AAEM,MAAMC,eAAe,GAAG,CAAC,qBAAqB,EAAE,GAAGD,oBAAoB,CAAC,CAAA;AAE/E,MAAME,mBAAmB,GAAG,CAAC,sBAAsB,EAAE,aAAa,CAAC,CAAA;AAE5D,MAAMC,QAAoD,GAAG;AAClEC,EAAAA,QAAQ,EAAEN,UAAU,CAAC,CAAC,qBAAqB,CAAC,CAAC;AAC7CO,EAAAA,YAAY,EAAEP,UAAU,CAAC,CAAC,yBAAyB,CAAC,CAAC;AACrDQ,EAAAA,YAAY,EAAER,UAAU,CAAC,CAAC,yBAAyB,CAAC,CAAC;AACrDS,EAAAA,SAAS,EAAET,UAAU,CAAC,CAAC,sBAAsB,CAAC,CAAC;AAC/CU,EAAAA,UAAU,EAAEV,UAAU,CAAC,CAAC,uBAAuB,CAAC,CAAC;AACjDW,EAAAA,UAAU,EAAEX,UAAU,CAAC,CAAC,uBAAuB,CAAC,CAAC;EACjDY,GAAG,EAAEd,aAAa,CAAC,KAAK,EAAE,CAAC,SAAS,EAAE,GAAGK,eAAe,CAAC,CAAC;AAC1DU,EAAAA,MAAM,EAAEb,UAAU,CAAC,CAAC,wBAAwB,CAAC,CAAC;AAC9Cc,EAAAA,OAAO,EAAEhB,aAAa,CAAC,SAAS,EAAEM,mBAAmB,CAAC;AACtDW,EAAAA,MAAM,EAAEf,UAAU,CAAC,CAAC,wBAAwB,CAAC,CAAC;EAC9CgB,GAAG,EAAElB,aAAa,CAAC,KAAK,EAAE,CAAC,SAAS,EAAE,GAAGK,eAAe,CAAC,CAAC;EAC1Dc,MAAM,EAAEnB,aAAa,CAAC,cAAc,EAAE,CAAC,YAAY,CAAC,CAAC;AACrDoB,EAAAA,UAAU,EAAElB,UAAU,CAAC,CAAC,uBAAuB,CAAC,CAAC;AACjDmB,EAAAA,iBAAiB,EAAEnB,UAAU,CAAC,CAAC,+BAA+B,CAAC,CAAC;AAChEoB,EAAAA,WAAW,EAAEpB,UAAU,CAAC,CAAC,wBAAwB,CAAC,CAAC;AACnDqB,EAAAA,WAAW,EAAErB,UAAU,CAAC,CAAC,wBAAwB,CAAC,CAAC;EACnDsB,OAAO,EAAExB,aAAa,CAAC,UAAU,EAAE,CAAC,cAAc,EAAE,GAAGK,eAAe,CAAC,CAAC;EACxEoB,OAAO,EAAEzB,aAAa,CAAC,UAAU,EAAE,CAAC,cAAc,EAAE,GAAGK,eAAe,CAAC,CAAC;AAExEqB,EAAAA,YAAY,EAAEvB,QAAQ,CAAC,eAAe,EAAE,eAAe,CAAC;AACxDwB,EAAAA,cAAc,EAAExB,QAAQ,CAAC,iBAAiB,EAAE,eAAe,CAAC;AAC5DyB,EAAAA,UAAU,EAAEzB,QAAQ,CAAC,aAAa,EAAE,iBAAiB,CAAC;AACtD0B,EAAAA,QAAQ,EAAE1B,QAAQ,CAAC,WAAW,EAAE,eAAe,CAAA;AACjD,CAAC,CAAA;AAEM,MAAM2B,kBAA8D,GAAG;AAC5EC,EAAAA,gBAAgB,EAAE7B,UAAU,CAAC,CAAC,0BAA0B,CAAC,CAAC;AAC1D8B,EAAAA,gBAAgB,EAAE9B,UAAU,CAAC,CAAC,0BAA0B,CAAC,CAAC;AAC1D+B,EAAAA,gBAAgB,EAAE/B,UAAU,CAAC,CAAC,0BAA0B,CAAC,CAAC;AAC1DgC,EAAAA,gBAAgB,EAAEhC,UAAU,CAAC,CAAC,0BAA0B,CAAC,CAAC;AAC1DiC,EAAAA,MAAM,EAAEjC,UAAU,CAAC,CAAC,mBAAmB,CAAC,CAAC;AACzCkC,EAAAA,GAAG,EAAElC,UAAU,CAAC,CAAC,gBAAgB,CAAC,CAAC;AACnCmC,EAAAA,IAAI,EAAEnC,UAAU,CAAC,CAAC,mBAAmB,CAAC,CAAC;AACvCoC,EAAAA,KAAK,EAAEpC,UAAU,CAAC,CAAC,kBAAkB,CAAC,CAAC;AACvCqC,EAAAA,IAAI,EAAErC,UAAU,CAAC,CAAC,iBAAiB,CAAC,CAAC;AACrCsC,EAAAA,WAAW,EAAEtC,UAAU,CAAC,CAAC,0BAA0B,CAAC,CAAC;AACrDuC,EAAAA,UAAU,EAAEvC,UAAU,CAAC,CAAC,uBAAuB,CAAC,CAAC;AACjDwC,EAAAA,QAAQ,EAAExC,UAAU,CAAC,CAAC,sBAAsB,CAAC,CAAC;AAC9CyC,EAAAA,OAAO,EAAEzC,UAAU,CAACE,oBAAoB,CAAC;AACzCwC,EAAAA,KAAK,EAAE1C,UAAU,CAAC,CAAC,iBAAiB,CAAC,CAAC;AACtC2C,EAAAA,IAAI,EAAE3C,UAAU,CAAC,CAAC,gBAAgB,CAAC,CAAC;AACpC4C,EAAAA,MAAM,EAAE5C,UAAU,CAAC,CAAC,kBAAkB,CAAC,CAAC;EACxC6C,OAAO,EAAE7C,UAAU,CAAC,CAAC,qBAAqB,EAAE,GAAGI,mBAAmB,CAAC,CAAC;AACpE0C,EAAAA,IAAI,EAAE9C,UAAU,CAAC,CAAC,gBAAgB,CAAC,CAAC;AACpC+C,EAAAA,SAAS,EAAE/C,UAAU,CAAC,CAAC,sBAAsB,CAAC,CAAC;AAC/CgD,EAAAA,KAAK,EAAEhD,UAAU,CAAC,CAAC,kBAAkB,CAAC,CAAC;AACvCiD,EAAAA,KAAK,EAAEjD,UAAU,CAAC,CAAC,kBAAkB,CAAC,CAAC;AACvCkD,EAAAA,OAAO,EAAElD,UAAU,CAAC,CAAC,oBAAoB,CAAC,CAAC;AAC3CmD,EAAAA,SAAS,EAAEnD,UAAU,CAAC,CAAC,sBAAsB,CAAC,CAAC;AAC/CoD,EAAAA,QAAQ,EAAEpD,UAAU,CAAC,CAAC,qBAAqB,CAAC,CAAC;AAC7CqD,EAAAA,OAAO,EAAErD,UAAU,CAAC,CAAC,oBAAoB,CAAC,CAAC;EAC3CsD,QAAQ,EAAEtD,UAAU,CAAC,CAAC,qBAAqB,EAAE,oBAAoB,CAAC,CAAC;AACnEuD,EAAAA,OAAO,EAAEvD,UAAU,CAAC,CAAC,oBAAoB,CAAC,CAAC;AAC3CwD,EAAAA,OAAO,EAAExD,UAAU,CAAC,CAAC,oBAAoB,CAAC,CAAC;AAC3CyD,EAAAA,IAAI,EAAEzD,UAAU,CAACE,oBAAoB,CAAC;AACtCwD,EAAAA,WAAW,EAAE1D,UAAU,CAAC,CAAC,yBAAyB,CAAC,CAAC;AACpD2D,EAAAA,IAAI,EAAE3D,UAAU,CAAC,CAAC,iBAAiB,CAAC,CAAC;AACrC4D,EAAAA,GAAG,EAAE5D,UAAU,CAAC,CAAC,eAAe,CAAC,CAAC;AAClC6D,EAAAA,KAAK,EAAE7D,UAAU,CAAC,CAAC,kBAAkB,CAAC,CAAC;AACvCN,EAAAA,IAAI,EAAEM,UAAU,CAAC,CAAC,mBAAmB,CAAC,CAAC;AACvC8D,EAAAA,QAAQ,EAAE9D,UAAU,CAAC,CAAC,sBAAsB,CAAC,CAAC;AAC9C+D,EAAAA,MAAM,EAAE/D,UAAU,CAAC,CAAC,oBAAoB,CAAC,CAAC;AAC1CgE,EAAAA,MAAM,EAAEhE,UAAU,CAAC,CAAC,kBAAkB,CAAC,CAAC;AACxCiE,EAAAA,WAAW,EAAEjE,UAAU,CAAC,CAAC,wBAAwB,CAAC,CAAC;AACnDkE,EAAAA,MAAM,EAAElE,UAAU,CAAC,CAAC,mBAAmB,CAAC,CAAC;AACzCmE,EAAAA,OAAO,EAAEnE,UAAU,CAAC,CAAC,oBAAoB,CAAC,CAAC;AAC3CoE,EAAAA,MAAM,EAAEpE,UAAU,CAAC,CAAC,mBAAmB,CAAC,CAAC;AACzCqE,EAAAA,KAAK,EAAErE,UAAU,CAAC,CAAC,kBAAkB,CAAC,CAAC;AACvCsE,EAAAA,IAAI,EAAEtE,UAAU,CAAC,CAAC,gBAAgB,CAAC,CAAC;AACpCuE,EAAAA,IAAI,EAAEvE,UAAU,CAAC,CAAC,gBAAgB,CAAC,CAAC;AACpCwE,EAAAA,KAAK,EAAExE,UAAU,CAAC,CAAC,kBAAkB,CAAC,CAAC;AACvCyE,EAAAA,UAAU,EAAEzE,UAAU,CAAC,CAAC,wBAAwB,CAAC,CAAC;AAClD0E,EAAAA,MAAM,EAAE1E,UAAU,CAAC,CAAC,mBAAmB,CAAC,CAAC;AACzC2E,EAAAA,GAAG,EAAE3E,UAAU,CAAC,CAAC,gBAAgB,CAAC,CAAC;AACnC4E,EAAAA,GAAG,EAAE5E,UAAU,CAAC,CAAC,gBAAgB,CAAC,CAAC;AACnC6E,EAAAA,WAAW,EAAE7E,UAAU,CAAC,CAAC,wBAAwB,CAAC,CAAC;AACnD8E,EAAAA,MAAM,EAAE9E,UAAU,CAAC,CAAC,kBAAkB,CAAC,CAAC;EACxC+E,QAAQ,EAAE/E,UAAU,CAAC,CACnB,sBAAsB,EACtB,oBAAoB,EACpB,sBAAsB,CACvB,CAAC;AACFgF,EAAAA,IAAI,EAAEhF,UAAU,CAAC,CAAC,iBAAiB,CAAC,CAAC;AACrCiF,EAAAA,OAAO,EAAEjF,UAAU,CAAC,CAAC,uBAAuB,CAAC,CAAC;AAC9CkF,EAAAA,QAAQ,EAAElF,UAAU,CAAC,CAAC,sBAAsB,CAAC,CAAC;AAC9CmF,EAAAA,SAAS,EAAEnF,UAAU,CAAC,CAAC,uBAAuB,CAAC,CAAC;AAChDoF,EAAAA,SAAS,EAAEpF,UAAU,CAAC,CAAC,sBAAsB,CAAC,CAAC;EAC/CqF,MAAM,EAAErF,UAAU,CAACE,oBAAoB,CAAA;AACzC,CAAC,CAAA;;AAED;AACA,IAAI,iBAAiB,IAAIoF,gBAAgB,EAAE;EACzC1D,kBAAkB,CAAC2D,KAAK,GAAGvF,UAAU,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAA;AAC5D,CAAA;AAEO,MAAMwF,gBAEZ,GAAG;AACFC,EAAAA,KAAK,EAAE;AACLC,IAAAA,IAAI,EAAE5F,aAAa,CAAC,YAAY,EAAE,CAChC,YAAY,EACZ,gBAAgB,EAChB,GAAGK,eAAe,CACnB,CAAC;IACFwF,OAAO,EAAE7F,aAAa,CAAC,gBAAgB,EAAE,CAAC,oBAAoB,CAAC,CAAC;AAChE8F,IAAAA,EAAE,EAAE9F,aAAa,CAAC,UAAU,EAAE,CAAC,cAAc,CAAC,CAAA;GAC/C;AAED+F,EAAAA,IAAI,EAAE;AACJC,IAAAA,GAAG,EAAEhG,aAAa,CAAC,UAAU,EAAE,CAAC,cAAc,CAAC,CAAA;GAChD;AAEDiG,EAAAA,IAAI,EAAE;AACJC,IAAAA,SAAS,EAAE/F,QAAQ,CAAC,gBAAgB,EAAE,YAAY,CAAA;GACnD;AAEDgG,EAAAA,IAAI,EAAE;AACJ;AACA;IACAC,KAAK,EAAEpG,aAAa,CAAC,YAAY,EAAE,CAAC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC/DqG,KAAK,EAAErG,aAAa,CAAC,YAAY,EAAE,CAAC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC/DsG,KAAK,EAAEtG,aAAa,CAAC,YAAY,EAAE,CAAC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC/DuG,IAAI,EAAEvG,aAAa,CAAC,WAAW,EAAE,CAAC,eAAe,CAAC,EAAE,OAAO,CAAC;IAC5DwG,KAAK,EAAExG,aAAa,CAAC,YAAY,EAAE,CAAC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC/DyG,IAAI,EAAEzG,aAAa,CAAC,WAAW,EAAE,CAAC,eAAe,CAAC,EAAE,OAAO,CAAC;IAC5D0G,KAAK,EAAE1G,aAAa,CAAC,YAAY,EAAE,CAAC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC/D2G,MAAM,EAAE3G,aAAa,CAAC,aAAa,EAAE,CAAC,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAClE4G,KAAK,EAAE5G,aAAa,CAAC,YAAY,EAAE,CAAC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC/D6G,IAAI,EAAE7G,aAAa,CAAC,WAAW,EAAE,CAAC,eAAe,CAAC,EAAE,OAAO,CAAC;IAC5D8G,KAAK,EAAE9G,aAAa,CAAC,YAAY,EAAE,CAAC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC/D+G,KAAK,EAAE/G,aAAa,CAAC,YAAY,EAAE,CAAC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC/DgH,IAAI,EAAEhH,aAAa,CAAC,WAAW,EAAE,CAAC,eAAe,CAAC,EAAE,OAAO,CAAC;IAC5DiH,IAAI,EAAEjH,aAAa,CAAC,WAAW,EAAE,CAAC,eAAe,CAAC,EAAE,OAAO,CAAC;IAC5DkH,IAAI,EAAElH,aAAa,CAAC,WAAW,EAAE,CAAC,eAAe,CAAC,EAAE,OAAO,CAAC;IAC5DmH,IAAI,EAAEnH,aAAa,CAAC,WAAW,EAAE,CAAC,eAAe,CAAC,EAAE,OAAO,CAAC;IAC5DoH,KAAK,EAAEpH,aAAa,CAAC,YAAY,EAAE,CAAC,gBAAgB,CAAC,EAAE,OAAO,CAAA;GAC/D;AAEDe,EAAAA,MAAM,EAAE;IACNsG,OAAO,EAAErH,aAAa,CAAC,gBAAgB,EAAE,CAAC,oBAAoB,CAAC,CAAC;IAChEsH,gBAAgB,EAAEtH,aAAa,CAAC,yBAAyB,EAAE,CACzD,6BAA6B,CAC9B,CAAC;IACFuH,gBAAgB,EAAEvH,aAAa,CAAC,yBAAyB,EAAE,CACzD,6BAA6B,CAC9B,CAAC;IACFwH,QAAQ,EAAExH,aAAa,CAAC,kBAAkB,EAAE,CAAC,sBAAsB,CAAC,CAAC;IACrEyH,SAAS,EAAEzH,aAAa,CAAC,mBAAmB,EAAE,CAAC,uBAAuB,CAAC,CAAC;IACxE0H,aAAa,EAAE1H,aAAa,CAAC,wBAAwB,EAAE,CACrD,4BAA4B,CAC7B,CAAC;IACF2H,KAAK,EAAE3H,aAAa,CAAC,eAAe,EAAE,CAAC,mBAAmB,CAAC,CAAC;IAC5D4B,UAAU,EAAE5B,aAAa,CAAC,oBAAoB,EAAE,CAAC,wBAAwB,CAAC,CAAC;AAC3E6B,IAAAA,QAAQ,EAAE7B,aAAa,CAAC,kBAAkB,EAAE,CAAC,sBAAsB,CAAC,CAAA;GACrE;AAED4H,EAAAA,MAAM,EAAE;IACNC,MAAM,EAAE7H,aAAa,CAAC,eAAe,EAAE,CAAC,mBAAmB,CAAC,CAAC;IAC7D8H,MAAM,EAAE9H,aAAa,CAAC,eAAe,EAAE,CAAC,mBAAmB,CAAC,CAAC;IAC7D+H,gBAAgB,EAAE/H,aAAa,CAAC,0BAA0B,EAAE,CAC1D,8BAA8B,CAC/B,CAAC;IACFgI,cAAc,EAAEhI,aAAa,CAAC,wBAAwB,EAAE,CACtD,4BAA4B,CAC7B,CAAC;IACF2C,OAAO,EAAE3C,aAAa,CAAC,gBAAgB,EAAE,CAAC,oBAAoB,CAAC,CAAC;IAChEiI,MAAM,EAAEjI,aAAa,CAAC,eAAe,EAAE,CAAC,mBAAmB,CAAC,CAAC;IAC7DkI,wBAAwB,EAAElI,aAAa,CACrC,oCAAoC,EACpC,CAAC,wCAAwC,CAC3C,CAAC;IACDmI,yBAAyB,EAAEnI,aAAa,CACtC,qCAAqC,EACrC,CAAC,yCAAyC,CAC5C,CAAC;IACDoI,mBAAmB,EAAEpI,aAAa,CAAC,+BAA+B,EAAE,CAClE,mCAAmC,CACpC,CAAC;IACFqI,qBAAqB,EAAErI,aAAa,CAAC,iCAAiC,EAAE,CACtE,YAAY,CACb,CAAC;IACFsI,cAAc,EAAEtI,aAAa,CAAC,yBAAyB,EAAE,CACvD,6BAA6B,CAC9B,CAAC;IACFuI,EAAE,EAAEvI,aAAa,CAAC,WAAW,EAAE,CAAC,eAAe,CAAC,CAAC;IACjDwI,YAAY,EAAExI,aAAa,CAAC,sBAAsB,EAAE,CAClD,0BAA0B,CAC3B,CAAC;IACFyI,QAAQ,EAAEzI,aAAa,CAAC,kBAAkB,EAAE,CAAC,sBAAsB,CAAC,CAAC;IACrE0I,QAAQ,EAAE1I,aAAa,CAAC,kBAAkB,EAAE,CAAC,sBAAsB,CAAC,CAAC;IACrE2D,IAAI,EAAE3D,aAAa,CAAC,aAAa,EAAE,CAAC,iBAAiB,CAAC,CAAC;IACvD2I,iBAAiB,EAAE3I,aAAa,CAAC,2BAA2B,EAAE,CAC5D,+BAA+B,CAChC,CAAC;IACF4I,IAAI,EAAE5I,aAAa,CAAC,aAAa,EAAE,CAAC,iBAAiB,CAAC,CAAC;IACvD6I,cAAc,EAAE7I,aAAa,CAAC,yBAAyB,EAAE,CACvD,6BAA6B,CAC9B,CAAC;AACFuF,IAAAA,MAAM,EAAEvF,aAAa,CAAC,eAAe,EAAE,CAAC,mBAAmB,CAAC,CAAA;GAC7D;AAEDgB,EAAAA,OAAO,EAAE;AACP8H,IAAAA,GAAG,EAAE5I,UAAU,CAACG,eAAe,CAAC;IAChC0I,IAAI,EAAE7I,UAAU,CAACG,eAAe,CAAA;GACjC;AAED2I,EAAAA,OAAO,EAAE;IACPC,KAAK,EAAEjJ,aAAa,CAAC,eAAe,EAAE,CAAC,mBAAmB,CAAC,CAAC;IAC5DkJ,SAAS,EAAElJ,aAAa,CAAC,mBAAmB,EAAE,CAAC,uBAAuB,CAAC,CAAC;IACxEgI,cAAc,EAAEhI,aAAa,CAAC,yBAAyB,EAAE,CACvD,6BAA6B,CAC9B,CAAC;IACFmJ,cAAc,EAAEnJ,aAAa,CAAC,yBAAyB,EAAE,CACvD,6BAA6B,CAC9B,CAAC;IACFoJ,GAAG,EAAEpJ,aAAa,CAAC,aAAa,EAAE,CAAC,iBAAiB,CAAC,CAAC;IACtDkI,wBAAwB,EAAElI,aAAa,CACrC,qCAAqC,EACrC,CAAC,yCAAyC,CAC5C,CAAC;IACDsI,cAAc,EAAEtI,aAAa,CAAC,0BAA0B,EAAE,CACxD,8BAA8B,CAC/B,CAAC;IACFqJ,GAAG,EAAErJ,aAAa,CAAC,aAAa,EAAE,CAAC,iBAAiB,CAAC,CAAC;IACtDwI,YAAY,EAAExI,aAAa,CAAC,uBAAuB,EAAE,CACnD,2BAA2B,CAC5B,CAAC;IACFsJ,OAAO,EAAEtJ,aAAa,CAAC,kBAAkB,EAAE,CAAC,sBAAsB,CAAC,CAAC;IACpE2I,iBAAiB,EAAE3I,aAAa,CAAC,4BAA4B,EAAE,CAC7D,gCAAgC,CACjC,CAAC;IACFuJ,GAAG,EAAEvJ,aAAa,CAAC,aAAa,EAAE,CAAC,iBAAiB,CAAC,CAAC;AACtD6I,IAAAA,cAAc,EAAE7I,aAAa,CAAC,0BAA0B,EAAE,CACxD,8BAA8B,CAC/B,CAAA;GACF;AAEDwJ,EAAAA,MAAM,EAAE;AACNC,IAAAA,EAAE,EAAEtJ,QAAQ,CAAC,WAAW,EAAE,eAAe,CAAC;IAC1CuJ,aAAa,EAAE1J,aAAa,CAAC,wBAAwB,EAAE,CACrD,4BAA4B,CAC7B,CAAC;AACF2J,IAAAA,GAAG,EAAE3J,aAAa,CAAC,YAAY,EAAE,CAAC,gBAAgB,CAAC,CAAA;GACpD;AAEDmB,EAAAA,MAAM,EAAE;AACN;IACAyI,aAAa,EAAE1J,UAAU,CAAC,CAAC,YAAY,EAAE,2BAA2B,CAAC,CAAC;AACtE2J,IAAAA,GAAG,EAAE1J,QAAQ,CAAC,YAAY,EAAE,YAAY,CAAC;AACzC2J,IAAAA,WAAW,EAAE3J,QAAQ,CAAC,qBAAqB,EAAE,YAAY,CAAC;AAC1D4J,IAAAA,kBAAkB,EAAE5J,QAAQ,CAAC,6BAA6B,EAAE,YAAY,CAAC;IACzE6J,QAAQ,EAAErK,MAAM,CAAC,YAAY,EAAE,iBAAiB,EAAEU,eAAe,CAAC;AAClE4J,IAAAA,MAAM,EAAE9J,QAAQ,CAAC,gBAAgB,EAAE,YAAY,CAAC;IAChD4D,KAAK,EAAE/D,aAAa,CAAC,cAAc,EAAE,CAAC,kBAAkB,CAAC,CAAC;AAC1DqE,IAAAA,OAAO,EAAElE,QAAQ,CAAC,gBAAgB,EAAE,YAAY,CAAC;AACjDmE,IAAAA,MAAM,EAAEnE,QAAQ,CAAC,eAAe,EAAE,YAAY,CAAC;AAC/C+J,IAAAA,OAAO,EAAE/J,QAAQ,CAAC,gBAAgB,EAAE,YAAY,CAAC;AACjDuE,IAAAA,KAAK,EAAEvE,QAAQ,CAAC,cAAc,EAAE,YAAY,CAAC;AAC7CgK,IAAAA,WAAW,EAAEhK,QAAQ,CAAC,qBAAqB,EAAE,YAAY,CAAC;AAC1DiK,IAAAA,WAAW,EAAEjK,QAAQ,CAAC,sBAAsB,EAAE,YAAY,CAAC;AAC3DkK,IAAAA,WAAW,EAAElK,QAAQ,CAAC,oBAAoB,EAAE,YAAY,CAAA;AAC1D,GAAA;AACF,CAAC;;ACnTD,MAAMmK,YAAY,GAAG;EACnB,YAAY,EAAE,EAAE;EAChB,eAAe,EAAE,EAAE;AACnB,EAAA,kBAAkB,EAAE,EAAC;AACvB,CAAC,CAAA;AAED,MAAMC,aAAa,GAAG;EACpB,iBAAiB,EAAE,EAAE;EACrB,eAAe,EAAE,EAAE;AACnB,EAAA,eAAe,EAAE,EAAC;AACpB,CAAC,CAAA;AAEc,uCAAUC,OAAgB,EAAEC,MAAc,EAAEC,SAAc,EAAE;AACzE,EAAA,MAAMC,WAAW,GAAG/C,MAAM,CAACjE,IAAI,CAAC6G,OAAO,CAAC,CAAA;AACxC,EAAA,MAAMI,WAAW,GAAG,CAACD,WAAW,CAACE,MAAM,CAAA;EACvC,MAAMC,WAAW,GAAGH,WAAW,CAACnG,IAAI,CAAC5E,IAAI,IAAIA,IAAI,KAAK,MAAM,CAAC,CAAA;EAE7D,OAAO;AACL,IAAA,GAAG8K,SAAS;AACZ,IAAA,IAAID,MAAM,KAAK,YAAY,GAAGF,aAAa,GAAG,IAAI,CAAC;AACnD,IAAA,IAAIK,WAAW,IAAIE,WAAW,GAAGR,YAAY,GAAG,IAAI,CAAA;GACrD,CAAA;AACH;;ACtBO,SAASS,aAAaA,CAC3BC,UAA0B,EAC1BC,cAAuC,EACvC;AACA;AACA;AACA;AACA,EAAA,IAAI,CAACA,cAAc,IAAI,CAACD,UAAU,EAAE,OAAO,IAAI,CAAA;AAE/CC,EAAAA,cAAc,GAAGzB,MAAM,CAACyB,cAAc,CAAC,CAAA;;AAEvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACA,IAAIC,MAAM,CAACC,KAAK,CAACF,cAAc,CAAC,EAAEA,cAAc,GAAG,CAAIA,CAAAA,EAAAA,cAAc,CAAE,CAAA,CAAA;EAEvE,OACE,CAACC,MAAM,CAACE,UAAU,CAAC,CAAIJ,CAAAA,EAAAA,UAAU,EAAE,EAAEC,cAAc,CAAC,IACpD,CAACC,MAAM,CAACE,UAAU,CAAC,CAAS,OAAA,CAAA,EAAEH,cAAc,CAAC,CAAA;AAEjD;;AC1BoE,MAAA;AAE3DI,EAAAA,KAAK,EAAIC,CAAAA;AAAC,CAAA,GAAAC,MAAA,CAAAC,OAAA,IAAAD,MAAA,CAAA;AAEnB,MAAME,aAAa,GAAG,wBAAwB,CAAA;AAE9C,MAAMC,eAAe,GAAG,iDAAiD,CAAA;AACzE,MAAMC,aAAa,GAAG,8CAA8C,CAAA;AAEpE,MAAMtC,GAAG,GAAGuC,QAAQ,CAACC,IAAI,CAACxJ,IAAI,CAACuF,MAAM,CAACkE,cAAc,CAAC,CAAA;AAcrD,YAAeC,cAAc,CAAU,UACrCC,GAAG,EACH;AACE,EAAA,CAACN,eAAe,GAAG;AACjBO,IAAAA,sBAAsB,GAAG,KAAK;AAC9BC,IAAAA,aAAa,GAAG,KAAA;GACjB,GAAG,EAAE;AACN,EAAA,CAACP,aAAa,GAAG;AACfQ,IAAAA,eAAe,GAAG,KAAK;AACvBlB,IAAAA,cAAc,GAAG,EAAE;AACnBmB,IAAAA,GAAG,GAAG,KAAA;AACR,GAAC,GAAG,EAAC;AACP,CAAC,EACD;AACA,EAAA,MAAMC,OAAO,GAAGL,GAAG,CAACM,kBAAkB,CAAC;AACrCxM,IAAAA,MAAM,EAAES,QAAQ;AAChBgM,IAAAA,MAAM,EAAE7G,gBAAgB;AACxB8G,IAAAA,QAAQ,EAAE1K,kBAAAA;AACZ,GAAC,CAAC,CAAA;EAEF,MAAM;IAAE2K,KAAK;IAAEC,oBAAoB;AAAEjC,IAAAA,MAAAA;AAAO,GAAC,GAAGuB,GAAG,CAAA;EAEnD,MAAMtB,SAAS,GAAGiC,4BAA4B,CAC5CX,GAAG,CAACxB,OAAO,EACXC,MAAM,EACNjF,gBACF,CAAC,CAAA;AAED,EAAA,MAAMoH,UAAU,GAAGT,eAAe,GAC9B,GAAGV,aAAa,CAAA,QAAA,CAAU,GAC1BhB,MAAM,KAAK,YAAY,GACrB,oBAAoB,GACpB,iBAAiB,CAAA;AAEvB,EAAA,SAASoC,MAAMA,CAACjN,IAAuB,EAAEkN,KAAK,EAAE;AAC9C,IAAA,IAAI,OAAOlN,IAAI,KAAK,QAAQ,EAAE;AAC5B;AACA;MACA,IAAIyJ,GAAG,CAACqB,SAAS,EAAE9K,IAAI,CAAC,IAAI8M,oBAAoB,CAAC9M,IAAI,CAAC,EAAE;QACtD6M,KAAK,CAAC7M,IAAI,CAAC,CAAA;QACXkN,KAAK,CAACC,kBAAkB,CAAC,CAAA,EAAGH,UAAU,CAAIhN,CAAAA,EAAAA,IAAI,KAAK,CAAC,CAAA;AACtD,OAAA;AACA,MAAA,OAAA;AACF,KAAA;IAEAA,IAAI,CAAC2D,OAAO,CAAC3D,IAAI,IAAIiN,MAAM,CAACjN,IAAI,EAAEkN,KAAK,CAAC,CAAC,CAAA;AAC3C,GAAA;AAEA,EAAA,SAASE,eAAeA,CAACC,IAAI,EAAEC,IAAI,EAAEJ,KAAK,EAAE;IAC1C,IAAI;MAAEjN,IAAI;MAAEE,IAAI;AAAEH,MAAAA,IAAAA;AAAK,KAAC,GAAGqN,IAAI,CAAA;IAE/B,IAAI,CAACpN,IAAI,IAAI,CAAC6M,oBAAoB,CAAC9M,IAAI,CAAC,EAAE,OAAA;AAE1C,IAAA,IACEqL,cAAc,IACdlL,IAAI,IACJA,IAAI,CAACE,iBAAiB,IACtB,CAAC8K,aAAa,CAAChL,IAAI,IAAIA,IAAI,CAACE,iBAAiB,EAAEgL,cAAc,CAAC,EAC9D;AACA,MAAA,OAAA;AACF,KAAA;;AAEA;AACA;IACA,IAAIkB,eAAe,IAAItM,IAAI,KAAK,cAAc,EAAEA,IAAI,GAAG,QAAQ,CAAA;AAE/D,IAAA,OAAOiN,KAAK,CAACK,mBAAmB,CAAC,CAAGP,EAAAA,UAAU,CAAI/M,CAAAA,EAAAA,IAAI,CAAGuM,EAAAA,GAAG,CAAE,CAAA,EAAEc,IAAI,CAAC,CAAA;AACvE,GAAA;EAEA,OAAO;AACLtN,IAAAA,IAAI,EAAE,SAAS;AAEfwN,IAAAA,WAAW,EAAElB,aAAa,GAAG,IAAI,GAAGT,aAAa;IAEjDf,SAAS;AAET2C,IAAAA,WAAWA,CAACtN,IAAI,EAAE+M,KAAK,EAAEQ,IAAI,EAAE;MAC7B,IAAIvN,IAAI,CAACwN,IAAI,KAAK,QAAQ,IAAIxN,IAAI,CAACyN,MAAM,KAAK,SAAS,EAAE;QACvDf,KAAK,CAAC,IAAI,CAAC,CAAA;QAEXI,MAAM,CAACjF,MAAM,CAACjE,IAAI,CAAC+G,SAAS,CAAC,EAAEoC,KAAK,CAAC,CAAA;AAErC,QAAA,IAAIb,sBAAsB,EAAE;AAC1Ba,UAAAA,KAAK,CAACC,kBAAkB,CAAC,gCAAgC,CAAC,CAAA;AAC5D,SAAA;QAEAO,IAAI,CAACG,MAAM,EAAE,CAAA;AACf,OAAA;KACD;AAEDC,IAAAA,WAAWA,CAAC3N,IAAI,EAAE+M,KAAK,EAAa;AAClC,MAAA,MAAMa,QAAQ,GAAGtB,OAAO,CAACtM,IAAI,CAAC,CAAA;MAC9B,IAAI,CAAC4N,QAAQ,EAAE,OAAA;AAEf,MAAA,IAAIC,IAAI,GAAGD,QAAQ,CAACV,IAAI,CAACnN,MAAM,CAAA;AAE/B,MAAA,IACE6N,QAAQ,CAACJ,IAAI,KAAK,QAAQ,IAC1B,QAAQ,IAAIxN,IAAI,IAChBA,IAAI,CAAC8N,MAAM,IACX9N,IAAI,CAAC+N,SAAS,KAAK,WAAW,EAC9B;QACA,MAAMC,GAAG,GAAGhO,IAAI,CAAC8N,MAAM,CAACG,WAAW,EAAE,CAAA;AACrCJ,QAAAA,IAAI,GAAGA,IAAI,CAAC9K,MAAM,CAACmL,CAAC,IAAIA,CAAC,CAACzK,QAAQ,CAACuK,GAAG,CAAC,CAAC,CAAA;AAC1C,OAAA;AAEAlB,MAAAA,MAAM,CAACe,IAAI,EAAEd,KAAK,CAAC,CAAA;KACpB;AAEDoB,IAAAA,SAASA,CAACnO,IAAI,EAAE+M,KAAK,EAAEQ,IAAI,EAAE;AAC3B,MAAA,IAAIvN,IAAI,CAACwN,IAAI,KAAK,IAAI,EAAE;AACtB,QAAA,IAAIxN,IAAI,CAACoO,GAAG,KAAK,iBAAiB,EAAE;UAClCb,IAAI,CAACc,WAAW,CACd9C,CAAC,CAAC+C,cAAc,CACdvB,KAAK,CAACK,mBAAmB,CACvB,CAAGP,EAAAA,UAAU,CAAeR,YAAAA,EAAAA,GAAG,CAAE,CAAA,EACjC,YACF,CAAC,EACD,CAAEkB,IAAI,CAACgB,IAAI,CAAwBC,KAAK,CAAC;AAC3C,WACF,CAAC,CAAA;AACH,SAAA;AAEA,QAAA,OAAA;AACF,OAAA;AAEA,MAAA,IAAIjB,IAAI,CAACkB,UAAU,CAACC,iBAAiB,CAAC;AAAEC,QAAAA,QAAQ,EAAE,QAAA;AAAS,OAAC,CAAC,EAAE,OAAA;AAE/D,MAAA,IAAI3O,IAAI,CAACwN,IAAI,KAAK,UAAU,EAAE;AAC5B;AACA,QAAA,IAAI,CAACD,IAAI,CAACqB,kBAAkB,EAAE,EAAE,OAAA;AAChC,QAAA,IAAI,CAACrB,IAAI,CAACsB,YAAY,EAAE,EAAE,OAAA;AAE1B,QAAA,IACE7O,IAAI,CAACoO,GAAG,KAAK,iBAAiB,IAC9BzB,oBAAoB,CAAC,YAAY,CAAC,IAClCY,IAAI,CAACkB,UAAU,CAACK,gBAAgB,CAAC;UAAEC,MAAM,EAAExB,IAAI,CAACgB,IAAAA;AAAK,SAAC,CAAC,IACvDhB,IAAI,CAACkB,UAAU,CAACF,IAAI,CAACS,SAAS,CAAClE,MAAM,KAAK,CAAC,EAC3C;AACAyC,UAAAA,IAAI,CAACkB,UAAU,CAACJ,WAAW,CACzB9C,CAAC,CAAC+C,cAAc,CACdvB,KAAK,CAACK,mBAAmB,CACvB,CAAGP,EAAAA,UAAU,CAAgBR,aAAAA,EAAAA,GAAG,CAAE,CAAA,EAClC,aACF,CAAC,EACD,CAACkB,IAAI,CAACgB,IAAI,CAACT,MAAM,CACnB,CACF,CAAC,CAAA;UACDP,IAAI,CAAC0B,IAAI,EAAE,CAAA;AAEX,UAAA,OAAA;AACF,SAAA;AACF,OAAA;AAEA,MAAA,MAAMrB,QAAQ,GAAGtB,OAAO,CAACtM,IAAI,CAAC,CAAA;MAC9B,IAAI,CAAC4N,QAAQ,EAAE,OAAA;AAEf,MAAA,MAAMsB,EAAE,GAAGjC,eAAe,CAACW,QAAQ,CAACV,IAAI,EAAEU,QAAQ,CAAC/N,IAAI,EAAEkN,KAAK,CAAC,CAAA;AAC/D,MAAA,IAAImC,EAAE,EAAE3B,IAAI,CAACc,WAAW,CAACa,EAAE,CAAC,CAAA;KAC7B;AAEDC,IAAAA,OAAO,EAAEzE,MAAM,KAAK,cAAc,IAAI;AACpC;MACA0E,eAAeA,CAAC7B,IAAiC,EAAE;AACjD,QAAA,IAAIA,IAAI,CAACgB,IAAI,CAACc,QAAQ,EAAE;UACtBvC,MAAM,CAAC,kBAAkB,EAAEb,GAAG,CAACqD,QAAQ,CAAC/B,IAAI,CAAC,CAAC,CAAA;AAChD,SAAA;OACD;AAED;MACA,6BAA6BgC,CAC3BhC,IAAiD,EACjD;AACAjN,QAAAA,eAAe,CAACkD,OAAO,CAAC3D,IAAI,IAAIiN,MAAM,CAACjN,IAAI,EAAEoM,GAAG,CAACqD,QAAQ,CAAC/B,IAAI,CAAC,CAAC,CAAC,CAAA;AACnE,OAAA;AACF,KAAA;GACD,CAAA;AACH,CAAC,CAAC;;;;"} \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-corejs2/lib/add-platform-specific-polyfills.js b/node_modules/babel-plugin-polyfill-corejs2/lib/add-platform-specific-polyfills.js new file mode 100644 index 0000000000000000000000000000000000000000..4521c8516d900ca8c7e21516f975c77a34542dfb --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs2/lib/add-platform-specific-polyfills.js @@ -0,0 +1,21 @@ +"use strict"; + +exports.__esModule = true; +exports.default = _default; +function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } +const webPolyfills = { + "web.timers": {}, + "web.immediate": {}, + "web.dom.iterable": {} +}; +const purePolyfills = { + "es6.parse-float": {}, + "es6.parse-int": {}, + "es7.string.at": {} +}; +function _default(targets, method, polyfills) { + const targetNames = Object.keys(targets); + const isAnyTarget = !targetNames.length; + const isWebTarget = targetNames.some(name => name !== "node"); + return _extends({}, polyfills, method === "usage-pure" ? purePolyfills : null, isAnyTarget || isWebTarget ? webPolyfills : null); +} \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-corejs2/lib/built-in-definitions.js b/node_modules/babel-plugin-polyfill-corejs2/lib/built-in-definitions.js new file mode 100644 index 0000000000000000000000000000000000000000..5d618695009b00af370c28a95474a7b695f34fab --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs2/lib/built-in-definitions.js @@ -0,0 +1,219 @@ +"use strict"; + +exports.__esModule = true; +exports.StaticProperties = exports.InstanceProperties = exports.CommonIterators = exports.BuiltIns = void 0; +var _corejs2BuiltIns = _interopRequireDefault(require("@babel/compat-data/corejs2-built-ins")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +const define = (name, pure, global = [], meta) => { + return { + name, + pure, + global, + meta + }; +}; +const pureAndGlobal = (pure, global, minRuntimeVersion = null) => define(global[0], pure, global, { + minRuntimeVersion +}); +const globalOnly = global => define(global[0], null, global); +const pureOnly = (pure, name) => define(name, pure, []); +const ArrayNatureIterators = ["es6.object.to-string", "es6.array.iterator", "web.dom.iterable"]; +const CommonIterators = exports.CommonIterators = ["es6.string.iterator", ...ArrayNatureIterators]; +const PromiseDependencies = ["es6.object.to-string", "es6.promise"]; +const BuiltIns = exports.BuiltIns = { + DataView: globalOnly(["es6.typed.data-view"]), + Float32Array: globalOnly(["es6.typed.float32-array"]), + Float64Array: globalOnly(["es6.typed.float64-array"]), + Int8Array: globalOnly(["es6.typed.int8-array"]), + Int16Array: globalOnly(["es6.typed.int16-array"]), + Int32Array: globalOnly(["es6.typed.int32-array"]), + Map: pureAndGlobal("map", ["es6.map", ...CommonIterators]), + Number: globalOnly(["es6.number.constructor"]), + Promise: pureAndGlobal("promise", PromiseDependencies), + RegExp: globalOnly(["es6.regexp.constructor"]), + Set: pureAndGlobal("set", ["es6.set", ...CommonIterators]), + Symbol: pureAndGlobal("symbol/index", ["es6.symbol"]), + Uint8Array: globalOnly(["es6.typed.uint8-array"]), + Uint8ClampedArray: globalOnly(["es6.typed.uint8-clamped-array"]), + Uint16Array: globalOnly(["es6.typed.uint16-array"]), + Uint32Array: globalOnly(["es6.typed.uint32-array"]), + WeakMap: pureAndGlobal("weak-map", ["es6.weak-map", ...CommonIterators]), + WeakSet: pureAndGlobal("weak-set", ["es6.weak-set", ...CommonIterators]), + setImmediate: pureOnly("set-immediate", "web.immediate"), + clearImmediate: pureOnly("clear-immediate", "web.immediate"), + parseFloat: pureOnly("parse-float", "es6.parse-float"), + parseInt: pureOnly("parse-int", "es6.parse-int") +}; +const InstanceProperties = exports.InstanceProperties = { + __defineGetter__: globalOnly(["es7.object.define-getter"]), + __defineSetter__: globalOnly(["es7.object.define-setter"]), + __lookupGetter__: globalOnly(["es7.object.lookup-getter"]), + __lookupSetter__: globalOnly(["es7.object.lookup-setter"]), + anchor: globalOnly(["es6.string.anchor"]), + big: globalOnly(["es6.string.big"]), + bind: globalOnly(["es6.function.bind"]), + blink: globalOnly(["es6.string.blink"]), + bold: globalOnly(["es6.string.bold"]), + codePointAt: globalOnly(["es6.string.code-point-at"]), + copyWithin: globalOnly(["es6.array.copy-within"]), + endsWith: globalOnly(["es6.string.ends-with"]), + entries: globalOnly(ArrayNatureIterators), + every: globalOnly(["es6.array.every"]), + fill: globalOnly(["es6.array.fill"]), + filter: globalOnly(["es6.array.filter"]), + finally: globalOnly(["es7.promise.finally", ...PromiseDependencies]), + find: globalOnly(["es6.array.find"]), + findIndex: globalOnly(["es6.array.find-index"]), + fixed: globalOnly(["es6.string.fixed"]), + flags: globalOnly(["es6.regexp.flags"]), + flatMap: globalOnly(["es7.array.flat-map"]), + fontcolor: globalOnly(["es6.string.fontcolor"]), + fontsize: globalOnly(["es6.string.fontsize"]), + forEach: globalOnly(["es6.array.for-each"]), + includes: globalOnly(["es6.string.includes", "es7.array.includes"]), + indexOf: globalOnly(["es6.array.index-of"]), + italics: globalOnly(["es6.string.italics"]), + keys: globalOnly(ArrayNatureIterators), + lastIndexOf: globalOnly(["es6.array.last-index-of"]), + link: globalOnly(["es6.string.link"]), + map: globalOnly(["es6.array.map"]), + match: globalOnly(["es6.regexp.match"]), + name: globalOnly(["es6.function.name"]), + padStart: globalOnly(["es7.string.pad-start"]), + padEnd: globalOnly(["es7.string.pad-end"]), + reduce: globalOnly(["es6.array.reduce"]), + reduceRight: globalOnly(["es6.array.reduce-right"]), + repeat: globalOnly(["es6.string.repeat"]), + replace: globalOnly(["es6.regexp.replace"]), + search: globalOnly(["es6.regexp.search"]), + small: globalOnly(["es6.string.small"]), + some: globalOnly(["es6.array.some"]), + sort: globalOnly(["es6.array.sort"]), + split: globalOnly(["es6.regexp.split"]), + startsWith: globalOnly(["es6.string.starts-with"]), + strike: globalOnly(["es6.string.strike"]), + sub: globalOnly(["es6.string.sub"]), + sup: globalOnly(["es6.string.sup"]), + toISOString: globalOnly(["es6.date.to-iso-string"]), + toJSON: globalOnly(["es6.date.to-json"]), + toString: globalOnly(["es6.object.to-string", "es6.date.to-string", "es6.regexp.to-string"]), + trim: globalOnly(["es6.string.trim"]), + trimEnd: globalOnly(["es7.string.trim-right"]), + trimLeft: globalOnly(["es7.string.trim-left"]), + trimRight: globalOnly(["es7.string.trim-right"]), + trimStart: globalOnly(["es7.string.trim-left"]), + values: globalOnly(ArrayNatureIterators) +}; + +// This isn't present in older @babel/compat-data versions +if ("es6.array.slice" in _corejs2BuiltIns.default) { + InstanceProperties.slice = globalOnly(["es6.array.slice"]); +} +const StaticProperties = exports.StaticProperties = { + Array: { + from: pureAndGlobal("array/from", ["es6.symbol", "es6.array.from", ...CommonIterators]), + isArray: pureAndGlobal("array/is-array", ["es6.array.is-array"]), + of: pureAndGlobal("array/of", ["es6.array.of"]) + }, + Date: { + now: pureAndGlobal("date/now", ["es6.date.now"]) + }, + JSON: { + stringify: pureOnly("json/stringify", "es6.symbol") + }, + Math: { + // 'Math' was not included in the 7.0.0 + // release of '@babel/runtime'. See issue https://github.com/babel/babel/pull/8616. + acosh: pureAndGlobal("math/acosh", ["es6.math.acosh"], "7.0.1"), + asinh: pureAndGlobal("math/asinh", ["es6.math.asinh"], "7.0.1"), + atanh: pureAndGlobal("math/atanh", ["es6.math.atanh"], "7.0.1"), + cbrt: pureAndGlobal("math/cbrt", ["es6.math.cbrt"], "7.0.1"), + clz32: pureAndGlobal("math/clz32", ["es6.math.clz32"], "7.0.1"), + cosh: pureAndGlobal("math/cosh", ["es6.math.cosh"], "7.0.1"), + expm1: pureAndGlobal("math/expm1", ["es6.math.expm1"], "7.0.1"), + fround: pureAndGlobal("math/fround", ["es6.math.fround"], "7.0.1"), + hypot: pureAndGlobal("math/hypot", ["es6.math.hypot"], "7.0.1"), + imul: pureAndGlobal("math/imul", ["es6.math.imul"], "7.0.1"), + log1p: pureAndGlobal("math/log1p", ["es6.math.log1p"], "7.0.1"), + log10: pureAndGlobal("math/log10", ["es6.math.log10"], "7.0.1"), + log2: pureAndGlobal("math/log2", ["es6.math.log2"], "7.0.1"), + sign: pureAndGlobal("math/sign", ["es6.math.sign"], "7.0.1"), + sinh: pureAndGlobal("math/sinh", ["es6.math.sinh"], "7.0.1"), + tanh: pureAndGlobal("math/tanh", ["es6.math.tanh"], "7.0.1"), + trunc: pureAndGlobal("math/trunc", ["es6.math.trunc"], "7.0.1") + }, + Number: { + EPSILON: pureAndGlobal("number/epsilon", ["es6.number.epsilon"]), + MIN_SAFE_INTEGER: pureAndGlobal("number/min-safe-integer", ["es6.number.min-safe-integer"]), + MAX_SAFE_INTEGER: pureAndGlobal("number/max-safe-integer", ["es6.number.max-safe-integer"]), + isFinite: pureAndGlobal("number/is-finite", ["es6.number.is-finite"]), + isInteger: pureAndGlobal("number/is-integer", ["es6.number.is-integer"]), + isSafeInteger: pureAndGlobal("number/is-safe-integer", ["es6.number.is-safe-integer"]), + isNaN: pureAndGlobal("number/is-nan", ["es6.number.is-nan"]), + parseFloat: pureAndGlobal("number/parse-float", ["es6.number.parse-float"]), + parseInt: pureAndGlobal("number/parse-int", ["es6.number.parse-int"]) + }, + Object: { + assign: pureAndGlobal("object/assign", ["es6.object.assign"]), + create: pureAndGlobal("object/create", ["es6.object.create"]), + defineProperties: pureAndGlobal("object/define-properties", ["es6.object.define-properties"]), + defineProperty: pureAndGlobal("object/define-property", ["es6.object.define-property"]), + entries: pureAndGlobal("object/entries", ["es7.object.entries"]), + freeze: pureAndGlobal("object/freeze", ["es6.object.freeze"]), + getOwnPropertyDescriptor: pureAndGlobal("object/get-own-property-descriptor", ["es6.object.get-own-property-descriptor"]), + getOwnPropertyDescriptors: pureAndGlobal("object/get-own-property-descriptors", ["es7.object.get-own-property-descriptors"]), + getOwnPropertyNames: pureAndGlobal("object/get-own-property-names", ["es6.object.get-own-property-names"]), + getOwnPropertySymbols: pureAndGlobal("object/get-own-property-symbols", ["es6.symbol"]), + getPrototypeOf: pureAndGlobal("object/get-prototype-of", ["es6.object.get-prototype-of"]), + is: pureAndGlobal("object/is", ["es6.object.is"]), + isExtensible: pureAndGlobal("object/is-extensible", ["es6.object.is-extensible"]), + isFrozen: pureAndGlobal("object/is-frozen", ["es6.object.is-frozen"]), + isSealed: pureAndGlobal("object/is-sealed", ["es6.object.is-sealed"]), + keys: pureAndGlobal("object/keys", ["es6.object.keys"]), + preventExtensions: pureAndGlobal("object/prevent-extensions", ["es6.object.prevent-extensions"]), + seal: pureAndGlobal("object/seal", ["es6.object.seal"]), + setPrototypeOf: pureAndGlobal("object/set-prototype-of", ["es6.object.set-prototype-of"]), + values: pureAndGlobal("object/values", ["es7.object.values"]) + }, + Promise: { + all: globalOnly(CommonIterators), + race: globalOnly(CommonIterators) + }, + Reflect: { + apply: pureAndGlobal("reflect/apply", ["es6.reflect.apply"]), + construct: pureAndGlobal("reflect/construct", ["es6.reflect.construct"]), + defineProperty: pureAndGlobal("reflect/define-property", ["es6.reflect.define-property"]), + deleteProperty: pureAndGlobal("reflect/delete-property", ["es6.reflect.delete-property"]), + get: pureAndGlobal("reflect/get", ["es6.reflect.get"]), + getOwnPropertyDescriptor: pureAndGlobal("reflect/get-own-property-descriptor", ["es6.reflect.get-own-property-descriptor"]), + getPrototypeOf: pureAndGlobal("reflect/get-prototype-of", ["es6.reflect.get-prototype-of"]), + has: pureAndGlobal("reflect/has", ["es6.reflect.has"]), + isExtensible: pureAndGlobal("reflect/is-extensible", ["es6.reflect.is-extensible"]), + ownKeys: pureAndGlobal("reflect/own-keys", ["es6.reflect.own-keys"]), + preventExtensions: pureAndGlobal("reflect/prevent-extensions", ["es6.reflect.prevent-extensions"]), + set: pureAndGlobal("reflect/set", ["es6.reflect.set"]), + setPrototypeOf: pureAndGlobal("reflect/set-prototype-of", ["es6.reflect.set-prototype-of"]) + }, + String: { + at: pureOnly("string/at", "es7.string.at"), + fromCodePoint: pureAndGlobal("string/from-code-point", ["es6.string.from-code-point"]), + raw: pureAndGlobal("string/raw", ["es6.string.raw"]) + }, + Symbol: { + // FIXME: Pure disabled to work around zloirock/core-js#262. + asyncIterator: globalOnly(["es6.symbol", "es7.symbol.async-iterator"]), + for: pureOnly("symbol/for", "es6.symbol"), + hasInstance: pureOnly("symbol/has-instance", "es6.symbol"), + isConcatSpreadable: pureOnly("symbol/is-concat-spreadable", "es6.symbol"), + iterator: define("es6.symbol", "symbol/iterator", CommonIterators), + keyFor: pureOnly("symbol/key-for", "es6.symbol"), + match: pureAndGlobal("symbol/match", ["es6.regexp.match"]), + replace: pureOnly("symbol/replace", "es6.symbol"), + search: pureOnly("symbol/search", "es6.symbol"), + species: pureOnly("symbol/species", "es6.symbol"), + split: pureOnly("symbol/split", "es6.symbol"), + toPrimitive: pureOnly("symbol/to-primitive", "es6.symbol"), + toStringTag: pureOnly("symbol/to-string-tag", "es6.symbol"), + unscopables: pureOnly("symbol/unscopables", "es6.symbol") + } +}; \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-corejs2/lib/helpers.js b/node_modules/babel-plugin-polyfill-corejs2/lib/helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..c15b6e5f8b0812bfc16af0007c611c3ce3d1ef91 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs2/lib/helpers.js @@ -0,0 +1,33 @@ +"use strict"; + +exports.__esModule = true; +exports.hasMinVersion = hasMinVersion; +var _semver = _interopRequireDefault(require("semver")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function hasMinVersion(minVersion, runtimeVersion) { + // If the range is unavailable, we're running the script during Babel's + // build process, and we want to assume that all versions are satisfied so + // that the built output will include all definitions. + if (!runtimeVersion || !minVersion) return true; + runtimeVersion = String(runtimeVersion); + + // semver.intersects() has some surprising behavior with comparing ranges + // with preprelease versions. We add '^' to ensure that we are always + // comparing ranges with ranges, which sidesteps this logic. + // For example: + // + // semver.intersects(`<7.0.1`, "7.0.0-beta.0") // false - surprising + // semver.intersects(`<7.0.1`, "^7.0.0-beta.0") // true - expected + // + // This is because the first falls back to + // + // semver.satisfies("7.0.0-beta.0", `<7.0.1`) // false - surprising + // + // and this fails because a prerelease version can only satisfy a range + // if it is a prerelease within the same major/minor/patch range. + // + // Note: If this is found to have issues, please also revist the logic in + // babel-core's availableHelper() API. + if (_semver.default.valid(runtimeVersion)) runtimeVersion = `^${runtimeVersion}`; + return !_semver.default.intersects(`<${minVersion}`, runtimeVersion) && !_semver.default.intersects(`>=8.0.0`, runtimeVersion); +} \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-corejs2/lib/index.js b/node_modules/babel-plugin-polyfill-corejs2/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d46d87badc9023d384d85f8417445abbff10e255 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs2/lib/index.js @@ -0,0 +1,136 @@ +"use strict"; + +exports.__esModule = true; +exports.default = void 0; +var _corejs2BuiltIns = _interopRequireDefault(require("@babel/compat-data/corejs2-built-ins")); +var _builtInDefinitions = require("./built-in-definitions"); +var _addPlatformSpecificPolyfills = _interopRequireDefault(require("./add-platform-specific-polyfills")); +var _helpers = require("./helpers"); +var _helperDefinePolyfillProvider = _interopRequireDefault(require("@babel/helper-define-polyfill-provider")); +var _babel = _interopRequireWildcard(require("@babel/core")); +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +const { + types: t +} = _babel.default || _babel; +const BABEL_RUNTIME = "@babel/runtime-corejs2"; +const presetEnvCompat = "#__secret_key__@babel/preset-env__compatibility"; +const runtimeCompat = "#__secret_key__@babel/runtime__compatibility"; +const has = Function.call.bind(Object.hasOwnProperty); +var _default = exports.default = (0, _helperDefinePolyfillProvider.default)(function (api, { + [presetEnvCompat]: { + entryInjectRegenerator = false, + noRuntimeName = false + } = {}, + [runtimeCompat]: { + useBabelRuntime = false, + runtimeVersion = "", + ext = ".js" + } = {} +}) { + const resolve = api.createMetaResolver({ + global: _builtInDefinitions.BuiltIns, + static: _builtInDefinitions.StaticProperties, + instance: _builtInDefinitions.InstanceProperties + }); + const { + debug, + shouldInjectPolyfill, + method + } = api; + const polyfills = (0, _addPlatformSpecificPolyfills.default)(api.targets, method, _corejs2BuiltIns.default); + const coreJSBase = useBabelRuntime ? `${BABEL_RUNTIME}/core-js` : method === "usage-pure" ? "core-js/library/fn" : "core-js/modules"; + function inject(name, utils) { + if (typeof name === "string") { + // Some polyfills aren't always available, for example + // web.dom.iterable when targeting node + if (has(polyfills, name) && shouldInjectPolyfill(name)) { + debug(name); + utils.injectGlobalImport(`${coreJSBase}/${name}.js`); + } + return; + } + name.forEach(name => inject(name, utils)); + } + function maybeInjectPure(desc, hint, utils) { + let { + pure, + meta, + name + } = desc; + if (!pure || !shouldInjectPolyfill(name)) return; + if (runtimeVersion && meta && meta.minRuntimeVersion && !(0, _helpers.hasMinVersion)(meta && meta.minRuntimeVersion, runtimeVersion)) { + return; + } + + // Unfortunately core-js and @babel/runtime-corejs2 don't have the same + // directory structure, so we need to special case this. + if (useBabelRuntime && pure === "symbol/index") pure = "symbol"; + return utils.injectDefaultImport(`${coreJSBase}/${pure}${ext}`, hint); + } + return { + name: "corejs2", + runtimeName: noRuntimeName ? null : BABEL_RUNTIME, + polyfills, + entryGlobal(meta, utils, path) { + if (meta.kind === "import" && meta.source === "core-js") { + debug(null); + inject(Object.keys(polyfills), utils); + if (entryInjectRegenerator) { + utils.injectGlobalImport("regenerator-runtime/runtime.js"); + } + path.remove(); + } + }, + usageGlobal(meta, utils) { + const resolved = resolve(meta); + if (!resolved) return; + let deps = resolved.desc.global; + if (resolved.kind !== "global" && "object" in meta && meta.object && meta.placement === "prototype") { + const low = meta.object.toLowerCase(); + deps = deps.filter(m => m.includes(low)); + } + inject(deps, utils); + }, + usagePure(meta, utils, path) { + if (meta.kind === "in") { + if (meta.key === "Symbol.iterator") { + path.replaceWith(t.callExpression(utils.injectDefaultImport(`${coreJSBase}/is-iterable${ext}`, "isIterable"), [path.node.right] // meta.kind === "in" narrows this + )); + } + return; + } + if (path.parentPath.isUnaryExpression({ + operator: "delete" + })) return; + if (meta.kind === "property") { + // We can't compile destructuring. + if (!path.isMemberExpression()) return; + if (!path.isReferenced()) return; + if (meta.key === "Symbol.iterator" && shouldInjectPolyfill("es6.symbol") && path.parentPath.isCallExpression({ + callee: path.node + }) && path.parentPath.node.arguments.length === 0) { + path.parentPath.replaceWith(t.callExpression(utils.injectDefaultImport(`${coreJSBase}/get-iterator${ext}`, "getIterator"), [path.node.object])); + path.skip(); + return; + } + } + const resolved = resolve(meta); + if (!resolved) return; + const id = maybeInjectPure(resolved.desc, resolved.name, utils); + if (id) path.replaceWith(id); + }, + visitor: method === "usage-global" && { + // yield* + YieldExpression(path) { + if (path.node.delegate) { + inject("web.dom.iterable", api.getUtils(path)); + } + }, + // for-of, [a, b] = c + "ForOfStatement|ArrayPattern"(path) { + _builtInDefinitions.CommonIterators.forEach(name => inject(name, api.getUtils(path))); + } + } + }; +}); \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-corejs2/package.json b/node_modules/babel-plugin-polyfill-corejs2/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ed06150af580507ef5c66a0028bcef4d6a2d25b6 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs2/package.json @@ -0,0 +1,43 @@ +{ + "name": "babel-plugin-polyfill-corejs2", + "version": "0.4.17", + "description": "A Babel plugin to inject imports to core-js@2 polyfills", + "repository": { + "type": "git", + "url": "https://github.com/babel/babel-polyfills.git", + "directory": "packages/babel-plugin-polyfill-corejs2" + }, + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "main": "lib/index.js", + "exports": { + ".": [ + { + "import": "./esm/index.mjs", + "default": "./lib/index.js" + }, + "./lib/index.js" + ], + "./package.json": "./package.json" + }, + "keywords": [ + "babel-plugin" + ], + "dependencies": { + "@babel/compat-data": "^7.28.6", + "@babel/helper-define-polyfill-provider": "^0.6.8", + "semver": "^6.3.1" + }, + "devDependencies": { + "@babel/core": "^7.28.6", + "@babel/helper-plugin-test-runner": "^7.27.1", + "@babel/plugin-transform-for-of": "^7.27.1", + "@babel/plugin-transform-modules-commonjs": "^7.28.6" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + }, + "gitHead": "86eff78e98adc17cdf0eb9ba4d94140eb7cb0da0" +} \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-corejs3/LICENSE b/node_modules/babel-plugin-polyfill-corejs3/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b74971fede812cae3d1b3d7db474db739fac2d53 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs3/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Nicolò Ribaudo and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/babel-plugin-polyfill-corejs3/README.md b/node_modules/babel-plugin-polyfill-corejs3/README.md new file mode 100644 index 0000000000000000000000000000000000000000..11f3e7c0232c9c1fc4b2981545ede7d80fcc8a9d --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs3/README.md @@ -0,0 +1,78 @@ +# babel-plugin-polyfill-corejs3 + +## Install + +Using npm: + +```sh +npm install --save-dev babel-plugin-polyfill-corejs3 +``` + +or using yarn: + +```sh +yarn add babel-plugin-polyfill-corejs3 --dev +``` + +## Usage + +Add this plugin to your Babel configuration: + +```json +{ + "plugins": [["polyfill-corejs3", { "method": "usage-global", "version": "3.48" }]] +} +``` + +This package supports the `usage-pure`, `usage-global`, and `entry-global` methods. +When `entry-global` is used, it replaces imports to `core-js`. + +## Options + +See [here](../../docs/usage.md#options) for a list of options supported by every polyfill provider. + +### `version` + +`string`, defaults to `"3.0"`. + +This option only has an effect when used alongside `"method": "usage-global"` or `"method": "usage-pure"`. It is recommended to specify the minor version you are using as `core-js@3.0` may not include polyfills for the latest features. If you are bundling an app, you can provide the version directly from your node modules: + +```js +{ + plugins: [ + ["polyfill-corejs3", { + "method": "usage-pure", + // use `core-js/package.json` if you are using `usage-global` + "version": require("core-js-pure/package.json").version + }] + ] +} +``` + +If you are a library author, specify a reasonably modern `core-js` version in your +`package.json` and provide the plugin the minimal supported version. + +```json +{ + "dependencies": { + "core-js": "^3.48.0" + } +} +``` +```js +{ + plugins: [ + ["polyfill-corejs3", { + "method": "usage-global", + // improvise if you have more complicated version spec, e.g. > 3.1.4 + "version": require("./package.json").dependencies["core-js"] + }] + ] +} +``` + +### `proposals` + +`boolean`, defaults to `false`. + +This option only has an effect when used alongside `"method": "usage-global"` or `"method": "usage-pure"`. When `proposals` are `true`, any ES proposal supported by core-js will be polyfilled as well. \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-corejs3/core-js-compat/README.md b/node_modules/babel-plugin-polyfill-corejs3/core-js-compat/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ba110c8500fdb7fde96b5fefd19bdef9be0c7f9f --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs3/core-js-compat/README.md @@ -0,0 +1,4 @@ +`core-js-compat` exposes some files as JSON, and they cannot be +imported by Node.js ESM files. +This folder proxies `core-js-compat` to ensure that every entry +is CJS and can be safely imported. \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-corejs3/core-js-compat/data.js b/node_modules/babel-plugin-polyfill-corejs3/core-js-compat/data.js new file mode 100644 index 0000000000000000000000000000000000000000..b525c34b54c3335abe9ee08718ec34a9922c4720 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs3/core-js-compat/data.js @@ -0,0 +1 @@ +module.exports = require("core-js-compat/data"); diff --git a/node_modules/babel-plugin-polyfill-corejs3/core-js-compat/entries.js b/node_modules/babel-plugin-polyfill-corejs3/core-js-compat/entries.js new file mode 100644 index 0000000000000000000000000000000000000000..1afc97e37e597ab329564280fccfbdb08395764c --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs3/core-js-compat/entries.js @@ -0,0 +1 @@ +module.exports = require("core-js-compat/entries"); diff --git a/node_modules/babel-plugin-polyfill-corejs3/core-js-compat/get-modules-list-for-target-version.js b/node_modules/babel-plugin-polyfill-corejs3/core-js-compat/get-modules-list-for-target-version.js new file mode 100644 index 0000000000000000000000000000000000000000..35d1fb3457feb9444da9dc91570f2d2ff3712395 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs3/core-js-compat/get-modules-list-for-target-version.js @@ -0,0 +1 @@ +module.exports = require("core-js-compat/get-modules-list-for-target-version"); diff --git a/node_modules/babel-plugin-polyfill-corejs3/esm/index.mjs b/node_modules/babel-plugin-polyfill-corejs3/esm/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..847a763eda4f87be6437d0a6a73073c0266313c8 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs3/esm/index.mjs @@ -0,0 +1,855 @@ +import corejs3Polyfills from '../core-js-compat/data.js'; +import getModulesListForTargetVersion from '../core-js-compat/get-modules-list-for-target-version.js'; +import * as _babel from '@babel/core'; +import corejsEntries from '../core-js-compat/entries.js'; +import defineProvider from '@babel/helper-define-polyfill-provider'; + +// This file is automatically generated by scripts/build-corejs3-shipped-proposals.mjs + +var corejs3ShippedProposalsList = new Set(["esnext.array.group", "esnext.array.group-to-map", "esnext.iterator.zip", "esnext.iterator.zip-keyed", "esnext.symbol.metadata"]); + +const polyfillsOrder = {}; +Object.keys(corejs3Polyfills).forEach((name, index) => { + polyfillsOrder[name] = index; +}); +const define = (pure, global, name = global[0], exclude) => { + return { + name, + pure, + global: global.sort((a, b) => polyfillsOrder[a] - polyfillsOrder[b]), + exclude + }; +}; +const typed = (...modules) => define(null, [...modules, ...TypedArrayDependencies]); +const ArrayNatureIterators = ["es.array.iterator", "web.dom-collections.iterator"]; +const CommonIterators = ["es.string.iterator", ...ArrayNatureIterators]; +const ArrayNatureIteratorsWithTag = ["es.object.to-string", ...ArrayNatureIterators]; +const CommonIteratorsWithTag = ["es.object.to-string", ...CommonIterators]; +const ErrorDependencies = ["es.error.cause", "es.error.to-string"]; +const SuppressedErrorDependencies = ["es.suppressed-error.constructor", ...ErrorDependencies]; +const ArrayBufferDependencies = ["es.array-buffer.constructor", "es.array-buffer.slice", "es.data-view", "es.array-buffer.detached", "es.array-buffer.transfer", "es.array-buffer.transfer-to-fixed-length", "es.object.to-string"]; +const TypedArrayDependencies = ["es.typed-array.at", "es.typed-array.copy-within", "es.typed-array.every", "es.typed-array.fill", "es.typed-array.filter", "es.typed-array.find", "es.typed-array.find-index", "es.typed-array.find-last", "es.typed-array.find-last-index", "es.typed-array.for-each", "es.typed-array.includes", "es.typed-array.index-of", "es.typed-array.iterator", "es.typed-array.join", "es.typed-array.last-index-of", "es.typed-array.map", "es.typed-array.reduce", "es.typed-array.reduce-right", "es.typed-array.reverse", "es.typed-array.set", "es.typed-array.slice", "es.typed-array.some", "es.typed-array.sort", "es.typed-array.subarray", "es.typed-array.to-locale-string", "es.typed-array.to-reversed", "es.typed-array.to-sorted", "es.typed-array.to-string", "es.typed-array.with", "es.object.to-string", "es.array.iterator", "esnext.typed-array.filter-reject", "esnext.typed-array.group-by", "esnext.typed-array.to-spliced", "esnext.typed-array.unique-by", ...ArrayBufferDependencies]; +const PromiseDependencies = ["es.promise", "es.object.to-string"]; +const PromiseDependenciesWithIterators = [...PromiseDependencies, ...CommonIterators]; +const SymbolDependencies = ["es.symbol", "es.symbol.description", "es.object.to-string"]; +const MapDependencies = ["es.map", "es.map.get-or-insert", "es.map.get-or-insert-computed", "esnext.map.delete-all", "esnext.map.emplace", "esnext.map.every", "esnext.map.filter", "esnext.map.find", "esnext.map.find-key", "esnext.map.includes", "esnext.map.key-of", "esnext.map.map-keys", "esnext.map.map-values", "esnext.map.merge", "esnext.map.reduce", "esnext.map.some", "esnext.map.update", ...CommonIteratorsWithTag]; +const SetDependencies = ["es.set", "es.set.difference.v2", "es.set.intersection.v2", "es.set.is-disjoint-from.v2", "es.set.is-subset-of.v2", "es.set.is-superset-of.v2", "es.set.symmetric-difference.v2", "es.set.union.v2", "esnext.set.add-all", "esnext.set.delete-all", "esnext.set.difference", "esnext.set.every", "esnext.set.filter", "esnext.set.find", "esnext.set.intersection", "esnext.set.is-disjoint-from", "esnext.set.is-subset-of", "esnext.set.is-superset-of", "esnext.set.join", "esnext.set.map", "esnext.set.reduce", "esnext.set.some", "esnext.set.symmetric-difference", "esnext.set.union", ...CommonIteratorsWithTag]; +const WeakMapDependencies = ["es.weak-map", "es.weak-map.get-or-insert", "es.weak-map.get-or-insert-computed", "esnext.weak-map.delete-all", "esnext.weak-map.emplace", ...CommonIteratorsWithTag]; +const WeakSetDependencies = ["es.weak-set", "esnext.weak-set.add-all", "esnext.weak-set.delete-all", ...CommonIteratorsWithTag]; +const DOMExceptionDependencies = ["web.dom-exception.constructor", "web.dom-exception.stack", "web.dom-exception.to-string-tag", "es.error.to-string"]; +const URLSearchParamsDependencies = ["web.url-search-params", "web.url-search-params.delete", "web.url-search-params.has", "web.url-search-params.size", ...CommonIteratorsWithTag]; +const AsyncIteratorDependencies = ["esnext.async-iterator.constructor", ...PromiseDependencies]; +const AsyncIteratorProblemMethods = ["esnext.async-iterator.every", "esnext.async-iterator.filter", "esnext.async-iterator.find", "esnext.async-iterator.flat-map", "esnext.async-iterator.for-each", "esnext.async-iterator.map", "esnext.async-iterator.reduce", "esnext.async-iterator.some"]; +const IteratorDependencies = ["es.iterator.constructor", "es.object.to-string"]; +const DecoratorMetadataDependencies = ["esnext.symbol.metadata", "esnext.function.metadata"]; +const TypedArrayStaticMethods = base => ({ + from: define(null, ["es.typed-array.from", base, ...TypedArrayDependencies]), + fromAsync: define(null, ["esnext.typed-array.from-async", base, ...PromiseDependenciesWithIterators, ...TypedArrayDependencies]), + of: define(null, ["es.typed-array.of", base, ...TypedArrayDependencies]) +}); +const DataViewDependencies = ["es.data-view", ...ArrayBufferDependencies]; +const BuiltIns = { + AsyncDisposableStack: define("async-disposable-stack/index", ["es.async-disposable-stack.constructor", "es.object.to-string", "es.async-iterator.async-dispose", "es.iterator.dispose", ...PromiseDependencies, ...SuppressedErrorDependencies]), + AsyncIterator: define("async-iterator/index", AsyncIteratorDependencies), + AggregateError: define("aggregate-error", ["es.aggregate-error", ...ErrorDependencies, ...CommonIteratorsWithTag, "es.aggregate-error.cause"]), + ArrayBuffer: define(null, ArrayBufferDependencies), + DataView: define(null, DataViewDependencies), + Date: define(null, ["es.date.to-string"]), + DOMException: define("dom-exception/index", DOMExceptionDependencies), + DisposableStack: define("disposable-stack/index", ["es.disposable-stack.constructor", "es.object.to-string", "es.iterator.dispose", ...SuppressedErrorDependencies]), + Error: define(null, ErrorDependencies), + EvalError: define(null, ErrorDependencies), + Float32Array: typed("es.typed-array.float32-array"), + Float64Array: typed("es.typed-array.float64-array"), + Int8Array: typed("es.typed-array.int8-array"), + Int16Array: typed("es.typed-array.int16-array"), + Int32Array: typed("es.typed-array.int32-array"), + Iterator: define("iterator/index", IteratorDependencies), + Uint8Array: typed("es.typed-array.uint8-array", "es.uint8-array.set-from-base64", "es.uint8-array.set-from-hex", "es.uint8-array.to-base64", "es.uint8-array.to-hex"), + Uint8ClampedArray: typed("es.typed-array.uint8-clamped-array"), + Uint16Array: typed("es.typed-array.uint16-array"), + Uint32Array: typed("es.typed-array.uint32-array"), + Map: define("map/index", MapDependencies), + Number: define(null, ["es.number.constructor"]), + Observable: define("observable/index", ["esnext.observable", "esnext.symbol.observable", "es.object.to-string", ...CommonIteratorsWithTag]), + Promise: define("promise/index", PromiseDependencies), + RangeError: define(null, ErrorDependencies), + ReferenceError: define(null, ErrorDependencies), + Reflect: define(null, ["es.reflect.to-string-tag", "es.object.to-string"]), + RegExp: define(null, ["es.regexp.constructor", "es.regexp.dot-all", "es.regexp.exec", "es.regexp.sticky", "es.regexp.to-string"]), + Set: define("set/index", SetDependencies), + SuppressedError: define("suppressed-error", SuppressedErrorDependencies), + Symbol: define("symbol/index", SymbolDependencies), + SyntaxError: define(null, ErrorDependencies), + TypeError: define(null, ErrorDependencies), + URIError: define(null, ErrorDependencies), + URL: define("url/index", ["web.url", "web.url.to-json", ...URLSearchParamsDependencies]), + URLSearchParams: define("url-search-params/index", URLSearchParamsDependencies), + WeakMap: define("weak-map/index", WeakMapDependencies), + WeakSet: define("weak-set/index", WeakSetDependencies), + atob: define("atob", ["web.atob", ...DOMExceptionDependencies]), + btoa: define("btoa", ["web.btoa", ...DOMExceptionDependencies]), + clearImmediate: define("clear-immediate", ["web.immediate"]), + compositeKey: define("composite-key", ["esnext.composite-key"]), + compositeSymbol: define("composite-symbol", ["esnext.composite-symbol"]), + escape: define("escape", ["es.escape"]), + fetch: define(null, PromiseDependencies), + globalThis: define("global-this", ["es.global-this"]), + parseFloat: define("parse-float", ["es.parse-float"]), + parseInt: define("parse-int", ["es.parse-int"]), + queueMicrotask: define("queue-microtask", ["web.queue-microtask"]), + self: define("self", ["web.self"]), + setImmediate: define("set-immediate", ["web.immediate"]), + setInterval: define("set-interval", ["web.timers"]), + setTimeout: define("set-timeout", ["web.timers"]), + structuredClone: define("structured-clone", ["web.structured-clone", ...DOMExceptionDependencies, "es.array.iterator", "es.object.keys", "es.object.to-string", "es.map", "es.set"]), + unescape: define("unescape", ["es.unescape"]) +}; +const StaticProperties = { + AsyncIterator: { + from: define("async-iterator/from", ["esnext.async-iterator.from", ...AsyncIteratorDependencies, ...AsyncIteratorProblemMethods, ...CommonIterators]) + }, + Array: { + from: define("array/from", ["es.array.from", "es.string.iterator"]), + fromAsync: define("array/from-async", ["es.array.from-async", ...PromiseDependenciesWithIterators]), + isArray: define("array/is-array", ["es.array.is-array"]), + isTemplateObject: define("array/is-template-object", ["esnext.array.is-template-object"]), + of: define("array/of", ["es.array.of"]) + }, + ArrayBuffer: { + isView: define(null, ["es.array-buffer.is-view"]) + }, + BigInt: { + range: define("bigint/range", ["esnext.bigint.range", "es.object.to-string"]) + }, + Date: { + now: define("date/now", ["es.date.now"]) + }, + Error: { + isError: define("error/is-error", ["es.error.is-error", "es.object.create"]) + }, + Function: { + isCallable: define("function/is-callable", ["esnext.function.is-callable"]), + isConstructor: define("function/is-constructor", ["esnext.function.is-constructor"]) + }, + Iterator: { + concat: define("iterator/concat", ["es.iterator.concat", ...IteratorDependencies, ...CommonIterators]), + from: define("iterator/from", ["es.iterator.from", ...IteratorDependencies, ...CommonIterators]), + range: define("iterator/range", ["esnext.iterator.range", ...IteratorDependencies]), + zip: define("iterator/zip", ["esnext.iterator.zip", ...IteratorDependencies, ...CommonIterators]), + zipKeyed: define("iterator/zip-keyed", ["esnext.iterator.zip-keyed", "es.object.create", "es.reflect.own-keys", ...IteratorDependencies, ...CommonIterators]) + }, + JSON: { + isRawJSON: define("json/is-raw-json", ["es.json.is-raw-json"]), + parse: define("json/parse", ["es.json.parse", "es.object.keys"]), + rawJSON: define("json/raw-json", ["es.json.raw-json", "es.object.create", "es.object.freeze"]), + stringify: define("json/stringify", ["es.json.stringify", "es.date.to-json"]) + }, + Math: { + DEG_PER_RAD: define("math/deg-per-rad", ["esnext.math.deg-per-rad"]), + RAD_PER_DEG: define("math/rad-per-deg", ["esnext.math.rad-per-deg"]), + acosh: define("math/acosh", ["es.math.acosh"]), + asinh: define("math/asinh", ["es.math.asinh"]), + atanh: define("math/atanh", ["es.math.atanh"]), + cbrt: define("math/cbrt", ["es.math.cbrt"]), + clamp: define("math/clamp", ["esnext.math.clamp"]), + clz32: define("math/clz32", ["es.math.clz32"]), + cosh: define("math/cosh", ["es.math.cosh"]), + degrees: define("math/degrees", ["esnext.math.degrees"]), + expm1: define("math/expm1", ["es.math.expm1"]), + fround: define("math/fround", ["es.math.fround"]), + f16round: define("math/f16round", ["es.math.f16round"]), + fscale: define("math/fscale", ["esnext.math.fscale"]), + hypot: define("math/hypot", ["es.math.hypot"]), + iaddh: define("math/iaddh", ["esnext.math.iaddh"]), + imul: define("math/imul", ["es.math.imul"]), + imulh: define("math/imulh", ["esnext.math.imulh"]), + isubh: define("math/isubh", ["esnext.math.isubh"]), + log10: define("math/log10", ["es.math.log10"]), + log1p: define("math/log1p", ["es.math.log1p"]), + log2: define("math/log2", ["es.math.log2"]), + radians: define("math/radians", ["esnext.math.radians"]), + scale: define("math/scale", ["esnext.math.scale"]), + seededPRNG: define("math/seeded-prng", ["esnext.math.seeded-prng"]), + sign: define("math/sign", ["es.math.sign"]), + signbit: define("math/signbit", ["esnext.math.signbit"]), + sinh: define("math/sinh", ["es.math.sinh"]), + sumPrecise: define("math/sum-precise", ["es.math.sum-precise", "es.array.iterator"]), + tanh: define("math/tanh", ["es.math.tanh"]), + trunc: define("math/trunc", ["es.math.trunc"]), + umulh: define("math/umulh", ["esnext.math.umulh"]) + }, + Map: { + from: define("map/from", ["esnext.map.from", ...MapDependencies]), + groupBy: define("map/group-by", ["es.map.group-by", ...MapDependencies]), + keyBy: define("map/key-by", ["esnext.map.key-by", ...MapDependencies]), + of: define("map/of", ["esnext.map.of", ...MapDependencies]) + }, + Number: { + EPSILON: define("number/epsilon", ["es.number.epsilon"]), + MAX_SAFE_INTEGER: define("number/max-safe-integer", ["es.number.max-safe-integer"]), + MIN_SAFE_INTEGER: define("number/min-safe-integer", ["es.number.min-safe-integer"]), + fromString: define("number/from-string", ["esnext.number.from-string"]), + isFinite: define("number/is-finite", ["es.number.is-finite"]), + isInteger: define("number/is-integer", ["es.number.is-integer"]), + isNaN: define("number/is-nan", ["es.number.is-nan"]), + isSafeInteger: define("number/is-safe-integer", ["es.number.is-safe-integer"]), + parseFloat: define("number/parse-float", ["es.number.parse-float"]), + parseInt: define("number/parse-int", ["es.number.parse-int"]), + range: define("number/range", ["esnext.number.range", "es.object.to-string"]) + }, + Object: { + assign: define("object/assign", ["es.object.assign"]), + create: define("object/create", ["es.object.create"]), + defineProperties: define("object/define-properties", ["es.object.define-properties"]), + defineProperty: define("object/define-property", ["es.object.define-property"]), + entries: define("object/entries", ["es.object.entries"]), + freeze: define("object/freeze", ["es.object.freeze"]), + fromEntries: define("object/from-entries", ["es.object.from-entries", "es.array.iterator"]), + getOwnPropertyDescriptor: define("object/get-own-property-descriptor", ["es.object.get-own-property-descriptor"]), + getOwnPropertyDescriptors: define("object/get-own-property-descriptors", ["es.object.get-own-property-descriptors"]), + getOwnPropertyNames: define("object/get-own-property-names", ["es.object.get-own-property-names"]), + getOwnPropertySymbols: define("object/get-own-property-symbols", ["es.symbol"]), + getPrototypeOf: define("object/get-prototype-of", ["es.object.get-prototype-of"]), + groupBy: define("object/group-by", ["es.object.group-by", "es.object.create"]), + hasOwn: define("object/has-own", ["es.object.has-own"]), + is: define("object/is", ["es.object.is"]), + isExtensible: define("object/is-extensible", ["es.object.is-extensible"]), + isFrozen: define("object/is-frozen", ["es.object.is-frozen"]), + isSealed: define("object/is-sealed", ["es.object.is-sealed"]), + keys: define("object/keys", ["es.object.keys"]), + preventExtensions: define("object/prevent-extensions", ["es.object.prevent-extensions"]), + seal: define("object/seal", ["es.object.seal"]), + setPrototypeOf: define("object/set-prototype-of", ["es.object.set-prototype-of"]), + values: define("object/values", ["es.object.values"]) + }, + Promise: { + all: define(null, PromiseDependenciesWithIterators), + allSettled: define("promise/all-settled", ["es.promise.all-settled", ...PromiseDependenciesWithIterators]), + any: define("promise/any", ["es.promise.any", "es.aggregate-error", ...PromiseDependenciesWithIterators]), + race: define(null, PromiseDependenciesWithIterators), + try: define("promise/try", ["es.promise.try", ...PromiseDependencies]), + withResolvers: define("promise/with-resolvers", ["es.promise.with-resolvers", ...PromiseDependencies]) + }, + Reflect: { + apply: define("reflect/apply", ["es.reflect.apply"]), + construct: define("reflect/construct", ["es.reflect.construct"]), + defineMetadata: define("reflect/define-metadata", ["esnext.reflect.define-metadata"]), + defineProperty: define("reflect/define-property", ["es.reflect.define-property"]), + deleteMetadata: define("reflect/delete-metadata", ["esnext.reflect.delete-metadata"]), + deleteProperty: define("reflect/delete-property", ["es.reflect.delete-property"]), + get: define("reflect/get", ["es.reflect.get"]), + getMetadata: define("reflect/get-metadata", ["esnext.reflect.get-metadata"]), + getMetadataKeys: define("reflect/get-metadata-keys", ["esnext.reflect.get-metadata-keys"]), + getOwnMetadata: define("reflect/get-own-metadata", ["esnext.reflect.get-own-metadata"]), + getOwnMetadataKeys: define("reflect/get-own-metadata-keys", ["esnext.reflect.get-own-metadata-keys"]), + getOwnPropertyDescriptor: define("reflect/get-own-property-descriptor", ["es.reflect.get-own-property-descriptor"]), + getPrototypeOf: define("reflect/get-prototype-of", ["es.reflect.get-prototype-of"]), + has: define("reflect/has", ["es.reflect.has"]), + hasMetadata: define("reflect/has-metadata", ["esnext.reflect.has-metadata"]), + hasOwnMetadata: define("reflect/has-own-metadata", ["esnext.reflect.has-own-metadata"]), + isExtensible: define("reflect/is-extensible", ["es.reflect.is-extensible"]), + metadata: define("reflect/metadata", ["esnext.reflect.metadata"]), + ownKeys: define("reflect/own-keys", ["es.reflect.own-keys"]), + preventExtensions: define("reflect/prevent-extensions", ["es.reflect.prevent-extensions"]), + set: define("reflect/set", ["es.reflect.set"]), + setPrototypeOf: define("reflect/set-prototype-of", ["es.reflect.set-prototype-of"]) + }, + RegExp: { + escape: define("regexp/escape", ["es.regexp.escape"]) + }, + Set: { + from: define("set/from", ["esnext.set.from", ...SetDependencies]), + of: define("set/of", ["esnext.set.of", ...SetDependencies]) + }, + String: { + cooked: define("string/cooked", ["esnext.string.cooked"]), + dedent: define("string/dedent", ["esnext.string.dedent", "es.string.from-code-point", "es.weak-map"]), + fromCodePoint: define("string/from-code-point", ["es.string.from-code-point"]), + raw: define("string/raw", ["es.string.raw"]) + }, + Symbol: { + asyncDispose: define("symbol/async-dispose", ["es.symbol.async-dispose", "es.async-iterator.async-dispose"]), + asyncIterator: define("symbol/async-iterator", ["es.symbol.async-iterator"]), + customMatcher: define("symbol/custom-matcher", ["esnext.symbol.custom-matcher"]), + dispose: define("symbol/dispose", ["es.symbol.dispose", "es.iterator.dispose"]), + for: define("symbol/for", [], "es.symbol"), + hasInstance: define("symbol/has-instance", ["es.symbol.has-instance", "es.function.has-instance"]), + isConcatSpreadable: define("symbol/is-concat-spreadable", ["es.symbol.is-concat-spreadable", "es.array.concat"]), + isRegistered: define("symbol/is-registered", ["esnext.symbol.is-registered", "es.symbol"]), + isRegisteredSymbol: define("symbol/is-registered-symbol", ["esnext.symbol.is-registered-symbol", "es.symbol"]), + isWellKnown: define("symbol/is-well-known", ["esnext.symbol.is-well-known", "es.symbol"]), + isWellKnownSymbol: define("symbol/is-well-known-symbol", ["esnext.symbol.is-well-known-symbol", "es.symbol"]), + iterator: define("symbol/iterator", ["es.symbol.iterator", ...CommonIteratorsWithTag]), + keyFor: define("symbol/key-for", [], "es.symbol"), + match: define("symbol/match", ["es.symbol.match", "es.string.match"]), + matcher: define("symbol/matcher", ["esnext.symbol.matcher"]), + matchAll: define("symbol/match-all", ["es.symbol.match-all", "es.string.match-all"]), + metadata: define("symbol/metadata", DecoratorMetadataDependencies), + metadataKey: define("symbol/metadata-key", ["esnext.symbol.metadata-key"]), + observable: define("symbol/observable", ["esnext.symbol.observable"]), + patternMatch: define("symbol/pattern-match", ["esnext.symbol.pattern-match"]), + replace: define("symbol/replace", ["es.symbol.replace", "es.string.replace"]), + search: define("symbol/search", ["es.symbol.search", "es.string.search"]), + species: define("symbol/species", ["es.symbol.species", "es.array.species"]), + split: define("symbol/split", ["es.symbol.split", "es.string.split"]), + toPrimitive: define("symbol/to-primitive", ["es.symbol.to-primitive", "es.date.to-primitive"]), + toStringTag: define("symbol/to-string-tag", ["es.symbol.to-string-tag", "es.object.to-string", "es.math.to-string-tag", "es.json.to-string-tag"]), + unscopables: define("symbol/unscopables", ["es.symbol.unscopables"]) + }, + URL: { + canParse: define("url/can-parse", ["web.url.can-parse", "web.url"]), + parse: define("url/parse", ["web.url.parse", "web.url"]) + }, + WeakMap: { + from: define("weak-map/from", ["esnext.weak-map.from", ...WeakMapDependencies]), + of: define("weak-map/of", ["esnext.weak-map.of", ...WeakMapDependencies]) + }, + WeakSet: { + from: define("weak-set/from", ["esnext.weak-set.from", ...WeakSetDependencies]), + of: define("weak-set/of", ["esnext.weak-set.of", ...WeakSetDependencies]) + }, + Int8Array: TypedArrayStaticMethods("es.typed-array.int8-array"), + Uint8Array: { + fromBase64: define(null, ["es.uint8-array.from-base64", ...TypedArrayDependencies]), + fromHex: define(null, ["es.uint8-array.from-hex", ...TypedArrayDependencies]), + ...TypedArrayStaticMethods("es.typed-array.uint8-array") + }, + Uint8ClampedArray: TypedArrayStaticMethods("es.typed-array.uint8-clamped-array"), + Int16Array: TypedArrayStaticMethods("es.typed-array.int16-array"), + Uint16Array: TypedArrayStaticMethods("es.typed-array.uint16-array"), + Int32Array: TypedArrayStaticMethods("es.typed-array.int32-array"), + Uint32Array: TypedArrayStaticMethods("es.typed-array.uint32-array"), + Float32Array: TypedArrayStaticMethods("es.typed-array.float32-array"), + Float64Array: TypedArrayStaticMethods("es.typed-array.float64-array"), + WebAssembly: { + CompileError: define(null, ErrorDependencies), + LinkError: define(null, ErrorDependencies), + RuntimeError: define(null, ErrorDependencies) + } +}; +["AggregateError", "EvalError", "RangeError", "ReferenceError", "SuppressedError", "SyntaxError", "TypeError", "URIError"].forEach(ERROR_SUBCLASS => { + StaticProperties[ERROR_SUBCLASS] = StaticProperties.Error; +}); +const InstanceProperties = { + asIndexedPairs: define(null, ["esnext.async-iterator.as-indexed-pairs", ...AsyncIteratorDependencies, "esnext.iterator.as-indexed-pairs", ...IteratorDependencies]), + at: define("instance/at", [ + // TODO: We should introduce overloaded instance methods definition + // Before that is implemented, the `esnext.string.at` must be the first + // In pure mode, the provider resolves the descriptor as a "pure" `esnext.string.at` + // and treats the compat-data of `esnext.string.at` as the compat-data of + // pure import `instance/at`. The first polyfill here should have the lowest corejs + // supported versions. + "esnext.string.at", "es.string.at-alternative", "es.array.at"]), + anchor: define(null, ["es.string.anchor"]), + big: define(null, ["es.string.big"]), + bind: define("instance/bind", ["es.function.bind"]), + blink: define(null, ["es.string.blink"]), + bold: define(null, ["es.string.bold"]), + chunks: define(null, ["esnext.iterator.chunks", ...IteratorDependencies]), + clamp: define("instance/clamp", ["esnext.number.clamp"]), + codePointAt: define("instance/code-point-at", ["es.string.code-point-at"]), + codePoints: define("instance/code-points", ["esnext.string.code-points"]), + concat: define("instance/concat", ["es.array.concat"], undefined, ["String"]), + copyWithin: define("instance/copy-within", ["es.array.copy-within"]), + demethodize: define("instance/demethodize", ["esnext.function.demethodize"]), + description: define(null, ["es.symbol", "es.symbol.description"]), + dotAll: define(null, ["es.regexp.dot-all"]), + drop: define(null, ["es.iterator.drop", ...IteratorDependencies, "esnext.async-iterator.drop", ...AsyncIteratorDependencies]), + endsWith: define("instance/ends-with", ["es.string.ends-with"]), + entries: define("instance/entries", ArrayNatureIteratorsWithTag), + every: define("instance/every", ["es.array.every", "es.iterator.every", ...IteratorDependencies + // TODO: add async iterator dependencies when we support sub-dependencies + // esnext.async-iterator.every depends on es.promise + // but we don't want to pull es.promise when esnext.async-iterator is disabled + // + // "esnext.async-iterator.every", + // ...AsyncIteratorDependencies + ]), + exec: define(null, ["es.regexp.exec"]), + fill: define("instance/fill", ["es.array.fill"]), + filter: define("instance/filter", ["es.array.filter", "es.iterator.filter", ...IteratorDependencies + // "esnext.async-iterator.filter", + ]), + filterReject: define("instance/filter-reject", ["esnext.array.filter-reject"]), + finally: define(null, ["es.promise.finally", ...PromiseDependencies]), + find: define("instance/find", ["es.array.find", "es.iterator.find", ...IteratorDependencies + // "esnext.async-iterator.find", + ]), + findIndex: define("instance/find-index", ["es.array.find-index"]), + findLast: define("instance/find-last", ["es.array.find-last"]), + findLastIndex: define("instance/find-last-index", ["es.array.find-last-index"]), + fixed: define(null, ["es.string.fixed"]), + flags: define("instance/flags", ["es.regexp.flags"]), + flatMap: define("instance/flat-map", ["es.array.flat-map", "es.array.unscopables.flat-map", "es.iterator.flat-map", ...IteratorDependencies + // "esnext.async-iterator.flat-map", + ]), + flat: define("instance/flat", ["es.array.flat", "es.array.unscopables.flat"]), + getFloat16: define(null, ["es.data-view.get-float16", ...DataViewDependencies]), + getUint8Clamped: define(null, ["esnext.data-view.get-uint8-clamped", ...DataViewDependencies]), + getYear: define(null, ["es.date.get-year"]), + group: define("instance/group", ["esnext.array.group"]), + groupBy: define("instance/group-by", ["esnext.array.group-by"]), + groupByToMap: define("instance/group-by-to-map", ["esnext.array.group-by-to-map", "es.map", "es.object.to-string"]), + groupToMap: define("instance/group-to-map", ["esnext.array.group-to-map", "es.map", "es.object.to-string"]), + fontcolor: define(null, ["es.string.fontcolor"]), + fontsize: define(null, ["es.string.fontsize"]), + forEach: define("instance/for-each", ["es.array.for-each", "es.iterator.for-each", ...IteratorDependencies, + // "esnext.async-iterator.for-each", + "web.dom-collections.for-each"]), + includes: define("instance/includes", ["es.array.includes", "es.string.includes"]), + indexed: define(null, ["esnext.async-iterator.indexed", ...AsyncIteratorDependencies, "esnext.iterator.indexed", ...IteratorDependencies]), + indexOf: define("instance/index-of", ["es.array.index-of"]), + isWellFormed: define("instance/is-well-formed", ["es.string.is-well-formed"]), + italics: define(null, ["es.string.italics"]), + join: define(null, ["es.array.join"]), + keys: define("instance/keys", ArrayNatureIteratorsWithTag), + lastIndex: define(null, ["esnext.array.last-index"]), + lastIndexOf: define("instance/last-index-of", ["es.array.last-index-of"]), + lastItem: define(null, ["esnext.array.last-item"]), + link: define(null, ["es.string.link"]), + map: define("instance/map", ["es.array.map", "es.iterator.map", ...IteratorDependencies + // "esnext.async-iterator.map", + ]), + match: define(null, ["es.string.match", "es.regexp.exec"]), + matchAll: define("instance/match-all", ["es.string.match-all", "es.regexp.exec"]), + name: define(null, ["es.function.name"]), + padEnd: define("instance/pad-end", ["es.string.pad-end"]), + padStart: define("instance/pad-start", ["es.string.pad-start"]), + push: define("instance/push", ["es.array.push"]), + reduce: define("instance/reduce", ["es.array.reduce", "es.iterator.reduce", ...IteratorDependencies + // "esnext.async-iterator.reduce", + ]), + reduceRight: define("instance/reduce-right", ["es.array.reduce-right"]), + repeat: define("instance/repeat", ["es.string.repeat"]), + replace: define(null, ["es.string.replace", "es.regexp.exec"]), + replaceAll: define("instance/replace-all", ["es.string.replace-all", "es.string.replace", "es.regexp.exec"]), + reverse: define("instance/reverse", ["es.array.reverse"]), + search: define(null, ["es.string.search", "es.regexp.exec"]), + setFloat16: define(null, ["es.data-view.set-float16", ...DataViewDependencies]), + setUint8Clamped: define(null, ["esnext.data-view.set-uint8-clamped", ...DataViewDependencies]), + setYear: define(null, ["es.date.set-year"]), + slice: define("instance/slice", ["es.array.slice"]), + sliding: define(null, ["esnext.iterator.sliding", ...IteratorDependencies]), + small: define(null, ["es.string.small"]), + some: define("instance/some", ["es.array.some", "es.iterator.some", ...IteratorDependencies + // "esnext.async-iterator.some", + ]), + sort: define("instance/sort", ["es.array.sort"]), + splice: define("instance/splice", ["es.array.splice"]), + split: define(null, ["es.string.split", "es.regexp.exec"]), + startsWith: define("instance/starts-with", ["es.string.starts-with"]), + sticky: define(null, ["es.regexp.sticky"]), + strike: define(null, ["es.string.strike"]), + sub: define(null, ["es.string.sub"]), + substr: define(null, ["es.string.substr"]), + sup: define(null, ["es.string.sup"]), + take: define(null, ["es.iterator.take", ...IteratorDependencies, "esnext.async-iterator.take", ...AsyncIteratorDependencies]), + test: define(null, ["es.regexp.test", "es.regexp.exec"]), + toArray: define(null, ["es.iterator.to-array", ...IteratorDependencies, "esnext.async-iterator.to-array", ...AsyncIteratorDependencies]), + toAsync: define(null, ["esnext.iterator.to-async", ...IteratorDependencies, ...AsyncIteratorDependencies, ...AsyncIteratorProblemMethods]), + toExponential: define(null, ["es.number.to-exponential"]), + toFixed: define(null, ["es.number.to-fixed"]), + toGMTString: define(null, ["es.date.to-gmt-string"]), + toISOString: define(null, ["es.date.to-iso-string"]), + toJSON: define(null, ["es.date.to-json"]), + toPrecision: define(null, ["es.number.to-precision"]), + toReversed: define("instance/to-reversed", ["es.array.to-reversed"]), + toSorted: define("instance/to-sorted", ["es.array.to-sorted", "es.array.sort"]), + toSpliced: define("instance/to-spliced", ["es.array.to-spliced"]), + toString: define(null, ["es.object.to-string", "es.error.to-string", "es.date.to-string", "es.regexp.to-string"]), + toWellFormed: define("instance/to-well-formed", ["es.string.to-well-formed"]), + trim: define("instance/trim", ["es.string.trim"]), + trimEnd: define("instance/trim-end", ["es.string.trim-end"]), + trimLeft: define("instance/trim-left", ["es.string.trim-start"]), + trimRight: define("instance/trim-right", ["es.string.trim-end"]), + trimStart: define("instance/trim-start", ["es.string.trim-start"]), + uniqueBy: define("instance/unique-by", ["esnext.array.unique-by", "es.map"]), + unshift: define("instance/unshift", ["es.array.unshift"]), + unThis: define("instance/un-this", ["esnext.function.un-this"]), + values: define("instance/values", ArrayNatureIteratorsWithTag), + windows: define(null, ["esnext.iterator.windows", ...IteratorDependencies]), + with: define("instance/with", ["es.array.with"]), + __defineGetter__: define(null, ["es.object.define-getter"]), + __defineSetter__: define(null, ["es.object.define-setter"]), + __lookupGetter__: define(null, ["es.object.lookup-getter"]), + __lookupSetter__: define(null, ["es.object.lookup-setter"]), + ["__proto__"]: define(null, ["es.object.proto"]) +}; + +// This file contains the list of paths supported by @babel/runtime-corejs3. +// It must _not_ be edited, as all new features should go through direct +// injection of core-js-pure imports. + +const stable = new Set(["array", "array/from", "array/is-array", "array/of", "clear-immediate", "date/now", "instance/bind", "instance/code-point-at", "instance/concat", "instance/copy-within", "instance/ends-with", "instance/entries", "instance/every", "instance/fill", "instance/filter", "instance/find", "instance/find-index", "instance/flags", "instance/flat", "instance/flat-map", "instance/for-each", "instance/includes", "instance/index-of", "instance/keys", "instance/last-index-of", "instance/map", "instance/pad-end", "instance/pad-start", "instance/reduce", "instance/reduce-right", "instance/repeat", "instance/reverse", "instance/slice", "instance/some", "instance/sort", "instance/splice", "instance/starts-with", "instance/trim", "instance/trim-end", "instance/trim-left", "instance/trim-right", "instance/trim-start", "instance/values", "json/stringify", "map", "math/acosh", "math/asinh", "math/atanh", "math/cbrt", "math/clz32", "math/cosh", "math/expm1", "math/fround", "math/hypot", "math/imul", "math/log10", "math/log1p", "math/log2", "math/sign", "math/sinh", "math/tanh", "math/trunc", "number/epsilon", "number/is-finite", "number/is-integer", "number/is-nan", "number/is-safe-integer", "number/max-safe-integer", "number/min-safe-integer", "number/parse-float", "number/parse-int", "object/assign", "object/create", "object/define-properties", "object/define-property", "object/entries", "object/freeze", "object/from-entries", "object/get-own-property-descriptor", "object/get-own-property-descriptors", "object/get-own-property-names", "object/get-own-property-symbols", "object/get-prototype-of", "object/is", "object/is-extensible", "object/is-frozen", "object/is-sealed", "object/keys", "object/prevent-extensions", "object/seal", "object/set-prototype-of", "object/values", "parse-float", "parse-int", "promise", "queue-microtask", "reflect/apply", "reflect/construct", "reflect/define-property", "reflect/delete-property", "reflect/get", "reflect/get-own-property-descriptor", "reflect/get-prototype-of", "reflect/has", "reflect/is-extensible", "reflect/own-keys", "reflect/prevent-extensions", "reflect/set", "reflect/set-prototype-of", "set", "set-immediate", "set-interval", "set-timeout", "string/from-code-point", "string/raw", "symbol", "symbol/async-iterator", "symbol/for", "symbol/has-instance", "symbol/is-concat-spreadable", "symbol/iterator", "symbol/key-for", "symbol/match", "symbol/replace", "symbol/search", "symbol/species", "symbol/split", "symbol/to-primitive", "symbol/to-string-tag", "symbol/unscopables", "url", "url-search-params", "weak-map", "weak-set"]); +const proposals = new Set([...stable, "aggregate-error", "composite-key", "composite-symbol", "global-this", "instance/at", "instance/code-points", "instance/match-all", "instance/replace-all", "math/clamp", "math/degrees", "math/deg-per-rad", "math/fscale", "math/iaddh", "math/imulh", "math/isubh", "math/rad-per-deg", "math/radians", "math/scale", "math/seeded-prng", "math/signbit", "math/umulh", "number/from-string", "observable", "reflect/define-metadata", "reflect/delete-metadata", "reflect/get-metadata", "reflect/get-metadata-keys", "reflect/get-own-metadata", "reflect/get-own-metadata-keys", "reflect/has-metadata", "reflect/has-own-metadata", "reflect/metadata", "symbol/dispose", "symbol/observable", "symbol/pattern-match"]); + +const { + types: t$2 +} = _babel.default || _babel; +function canSkipPolyfill(desc, path) { + const { + node, + parent + } = path; + switch (desc.name) { + case "es.string.split": + { + if (!t$2.isCallExpression(parent, { + callee: node + })) return false; + if (parent.arguments.length < 1) return true; + const splitter = parent.arguments[0]; + return t$2.isStringLiteral(splitter) || t$2.isTemplateLiteral(splitter); + } + } +} + +const { + types: t$1 +} = _babel.default || _babel; +const BABEL_RUNTIME = "@babel/runtime-corejs3"; +function callMethod(path, id, optionalCall, wrapCallee) { + const [context1, context2] = maybeMemoizeContext(path.node, path.scope); + let callee = t$1.callExpression(id, [context1]); + if (wrapCallee) callee = wrapCallee(callee); + const call = t$1.identifier("call"); + path.replaceWith(optionalCall ? t$1.optionalMemberExpression(callee, call, false, true) : t$1.memberExpression(callee, call)); + path.parentPath.unshiftContainer("arguments", context2); +} +function maybeMemoizeContext(node, scope) { + const { + object + } = node; + let context1, context2; + if (t$1.isIdentifier(object)) { + context2 = object; + context1 = t$1.cloneNode(object); + } else { + context2 = scope.generateDeclaredUidIdentifier("context"); + context1 = t$1.assignmentExpression("=", t$1.cloneNode(context2), object); + } + return [context1, context2]; +} +function extractOptionalCheck(scope, node) { + let optionalNode = node; + while (!optionalNode.optional && t$1.isOptionalMemberExpression(optionalNode.object)) { + optionalNode = optionalNode.object; + } + optionalNode.optional = false; + const ctx = scope.generateDeclaredUidIdentifier("context"); + const assign = t$1.assignmentExpression("=", ctx, optionalNode.object); + optionalNode.object = t$1.cloneNode(ctx); + return ifNotNullish => t$1.conditionalExpression(t$1.binaryExpression("==", assign, t$1.nullLiteral()), t$1.unaryExpression("void", t$1.numericLiteral(0)), ifNotNullish); +} +function isCoreJSSource(source) { + if (typeof source === "string") { + source = source.replace(/\\/g, "/").replace(/(\/(index)?)?(\.js)?$/i, "").toLowerCase(); + } + return Object.prototype.hasOwnProperty.call(corejsEntries, source) && corejsEntries[source]; +} +function coreJSModule(name) { + return `core-js/modules/${name}.js`; +} +function coreJSPureHelper(name, useBabelRuntime, ext) { + return useBabelRuntime ? `${BABEL_RUNTIME}/core-js/${name}${ext}` : `core-js-pure/features/${name}.js`; +} + +const { + types: t, + template: template +} = _babel.default || _babel; +const presetEnvCompat = "#__secret_key__@babel/preset-env__compatibility"; +const runtimeCompat = "#__secret_key__@babel/runtime__compatibility"; +const uniqueObjects = ["array", "string", "iterator", "async-iterator", "dom-collections"].map(v => new RegExp(`[a-z]*\\.${v}\\..*`)); +const esnextFallback = (name, cb) => { + if (cb(name)) return true; + if (!name.startsWith("es.")) return false; + const fallback = `esnext.${name.slice(3)}`; + if (!corejs3Polyfills[fallback]) return false; + return cb(fallback); +}; +var index = defineProvider(function ({ + getUtils, + method, + shouldInjectPolyfill, + createMetaResolver, + debug, + babel +}, { + version = 3, + proposals: proposals$1, + shippedProposals, + [presetEnvCompat]: { + noRuntimeName = false + } = {}, + [runtimeCompat]: { + useBabelRuntime = false, + ext = ".js" + } = {} +}) { + const isWebpack = babel.caller(caller => (caller == null ? void 0 : caller.name) === "babel-loader"); + const resolve = createMetaResolver({ + global: BuiltIns, + static: StaticProperties, + instance: InstanceProperties + }); + const available = new Set(getModulesListForTargetVersion(version)); + function getCoreJSPureBase(useProposalBase) { + return useBabelRuntime ? useProposalBase ? `${BABEL_RUNTIME}/core-js` : `${BABEL_RUNTIME}/core-js-stable` : useProposalBase ? "core-js-pure/features" : "core-js-pure/stable"; + } + function maybeInjectGlobalImpl(name, utils) { + if (shouldInjectPolyfill(name)) { + debug(name); + utils.injectGlobalImport(coreJSModule(name), name); + return true; + } + return false; + } + function maybeInjectGlobal(names, utils, fallback = true) { + for (const name of names) { + if (fallback) { + esnextFallback(name, name => maybeInjectGlobalImpl(name, utils)); + } else { + maybeInjectGlobalImpl(name, utils); + } + } + } + function maybeInjectPure(desc, hint, utils, object) { + if (desc.pure && !(object && desc.exclude && desc.exclude.includes(object)) && esnextFallback(desc.name, shouldInjectPolyfill)) { + const { + name + } = desc; + let useProposalBase = false; + if (proposals$1 || shippedProposals && name.startsWith("esnext.")) { + useProposalBase = true; + } else if (name.startsWith("es.") && !available.has(name)) { + useProposalBase = true; + } + if (useBabelRuntime && !(useProposalBase ? proposals : stable).has(desc.pure)) { + return; + } + const coreJSPureBase = getCoreJSPureBase(useProposalBase); + return utils.injectDefaultImport(`${coreJSPureBase}/${desc.pure}${ext}`, hint); + } + } + function isFeatureStable(name) { + if (name.startsWith("esnext.")) { + const esName = `es.${name.slice(7)}`; + // If its imaginative esName is not in latest compat data, it means + // the proposal is not stage 4 + return esName in corejs3Polyfills; + } + return true; + } + return { + name: "corejs3", + runtimeName: noRuntimeName ? null : BABEL_RUNTIME, + polyfills: corejs3Polyfills, + filterPolyfills(name) { + if (!available.has(name)) return false; + if (proposals$1 || method === "entry-global") return true; + if (shippedProposals && corejs3ShippedProposalsList.has(name)) { + return true; + } + return isFeatureStable(name); + }, + entryGlobal(meta, utils, path) { + if (meta.kind !== "import") return; + const modules = isCoreJSSource(meta.source); + if (!modules) return; + if (modules.length === 1 && meta.source === coreJSModule(modules[0]) && shouldInjectPolyfill(modules[0])) { + // Avoid infinite loop: do not replace imports with a new copy of + // themselves. + debug(null); + return; + } + const modulesSet = new Set(modules); + const filteredModules = modules.filter(module => { + if (!module.startsWith("esnext.")) return true; + const stable = module.replace("esnext.", "es."); + if (modulesSet.has(stable) && shouldInjectPolyfill(stable)) { + return false; + } + return true; + }); + maybeInjectGlobal(filteredModules, utils, false); + path.remove(); + }, + usageGlobal(meta, utils, path) { + const resolved = resolve(meta); + if (!resolved) return; + if (canSkipPolyfill(resolved.desc, path)) return; + let deps = resolved.desc.global; + if (resolved.kind !== "global" && "object" in meta && meta.object && meta.placement === "prototype") { + const low = meta.object.toLowerCase(); + deps = deps.filter(m => uniqueObjects.some(v => v.test(m)) ? m.includes(low) : true); + } + maybeInjectGlobal(deps, utils); + return true; + }, + usagePure(meta, utils, path) { + if (meta.kind === "in") { + if (meta.key === "Symbol.iterator") { + path.replaceWith(t.callExpression(utils.injectDefaultImport(coreJSPureHelper("is-iterable", useBabelRuntime, ext), "isIterable"), [path.node.right] // meta.kind === "in" narrows this + )); + } + return; + } + if (path.parentPath.isUnaryExpression({ + operator: "delete" + })) return; + if (meta.kind === "property") { + // We can't compile destructuring and updateExpression. + if (!path.isMemberExpression() && !path.isOptionalMemberExpression()) { + return; + } + if (!path.isReferenced()) return; + if (path.parentPath.isUpdateExpression()) return; + if (t.isSuper(path.node.object)) { + return; + } + if (meta.key === "Symbol.iterator") { + if (!shouldInjectPolyfill("es.symbol.iterator")) return; + const { + parent, + node + } = path; + if (t.isCallExpression(parent, { + callee: node + })) { + if (parent.arguments.length === 0) { + path.parentPath.replaceWith(t.callExpression(utils.injectDefaultImport(coreJSPureHelper("get-iterator", useBabelRuntime, ext), "getIterator"), [node.object])); + path.skip(); + } else { + callMethod(path, utils.injectDefaultImport(coreJSPureHelper("get-iterator-method", useBabelRuntime, ext), "getIteratorMethod")); + } + } else { + path.replaceWith(t.callExpression(utils.injectDefaultImport(coreJSPureHelper("get-iterator-method", useBabelRuntime, ext), "getIteratorMethod"), [path.node.object])); + } + return; + } + } + let resolved = resolve(meta); + if (!resolved) return; + if (canSkipPolyfill(resolved.desc, path)) return; + if (useBabelRuntime && resolved.desc.pure && resolved.desc.pure.slice(-6) === "/index") { + // Remove /index, since it doesn't exist in @babel/runtime-corejs3s + resolved = { + ...resolved, + desc: { + ...resolved.desc, + pure: resolved.desc.pure.slice(0, -6) + } + }; + } + if (resolved.kind === "global") { + const id = maybeInjectPure(resolved.desc, resolved.name, utils); + if (id) path.replaceWith(id); + } else if (resolved.kind === "static") { + const id = maybeInjectPure(resolved.desc, resolved.name, utils, + // @ts-expect-error + meta.object); + if (id) { + path.replaceWith(id); + let { + parentPath + } = path; + if (parentPath.isOptionalMemberExpression() || parentPath.isOptionalCallExpression()) { + do { + const parentAsNotOptional = parentPath; + parentAsNotOptional.type = parentAsNotOptional.node.type = parentPath.type === "OptionalMemberExpression" ? "MemberExpression" : "CallExpression"; + delete parentAsNotOptional.node.optional; + ({ + parentPath + } = parentPath); + } while ((parentPath.isOptionalMemberExpression() || parentPath.isOptionalCallExpression()) && !parentPath.node.optional); + } + } + } else if (resolved.kind === "instance") { + const id = maybeInjectPure(resolved.desc, `${resolved.name}InstanceProperty`, utils, + // @ts-expect-error + meta.object); + if (!id) return; + const { + node, + parent + } = path; + if (t.isOptionalCallExpression(parent) && parent.callee === node) { + const wasOptional = parent.optional; + parent.optional = !wasOptional; + if (!wasOptional) { + const check = extractOptionalCheck(path.scope, node); + const [thisArg, thisArg2] = maybeMemoizeContext(node, path.scope); + path.replaceWith(check(template.expression.ast` + Function.call.bind(${id}(${thisArg}), ${thisArg2}) + `)); + } else if (t.isOptionalMemberExpression(node)) { + const check = extractOptionalCheck(path.scope, node); + callMethod(path, id, true, check); + } else { + callMethod(path, id, true); + } + } else if (t.isCallExpression(parent) && parent.callee === node) { + callMethod(path, id, false); + } else if (t.isOptionalMemberExpression(node)) { + const check = extractOptionalCheck(path.scope, node); + path.replaceWith(check(t.callExpression(id, [node.object]))); + if (t.isOptionalMemberExpression(parent)) parent.optional = true; + } else { + path.replaceWith(t.callExpression(id, [node.object])); + } + } + }, + visitor: method === "usage-global" && { + // import("foo") + CallExpression(path) { + if (path.get("callee").isImport()) { + const utils = getUtils(path); + if (isWebpack) { + // Webpack uses Promise.all to handle dynamic import. + maybeInjectGlobal(PromiseDependenciesWithIterators, utils); + } else { + maybeInjectGlobal(PromiseDependencies, utils); + } + } + }, + // (async function () { }).finally(...) + Function(path) { + if (path.node.async) { + maybeInjectGlobal(PromiseDependencies, getUtils(path)); + } + }, + // for-of, [a, b] = c + "ForOfStatement|ArrayPattern"(path) { + maybeInjectGlobal(CommonIterators, getUtils(path)); + }, + // [...spread] + SpreadElement(path) { + if (!path.parentPath.isObjectExpression()) { + maybeInjectGlobal(CommonIterators, getUtils(path)); + } + }, + // yield* + YieldExpression(path) { + if (path.node.delegate) { + maybeInjectGlobal(CommonIterators, getUtils(path)); + } + }, + // Decorators metadata + Class(path) { + var _path$node$decorators; + const hasDecorators = ((_path$node$decorators = path.node.decorators) == null ? void 0 : _path$node$decorators.length) || path.node.body.body.some(el => { + var _decorators; + return (_decorators = el.decorators) == null ? void 0 : _decorators.length; + }); + if (hasDecorators) { + maybeInjectGlobal(DecoratorMetadataDependencies, getUtils(path)); + } + } + } + }; +}); + +export { index as default }; +//# sourceMappingURL=index.mjs.map diff --git a/node_modules/babel-plugin-polyfill-corejs3/esm/index.mjs.map b/node_modules/babel-plugin-polyfill-corejs3/esm/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..9112c1ead27d262d52b1e7cdc933cc3e2848dc5f --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs3/esm/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sources":["../src/shipped-proposals.ts","../src/built-in-definitions.ts","../src/babel-runtime-corejs3-paths.ts","../src/usage-filters.ts","../src/utils.ts","../src/index.ts"],"sourcesContent":["// This file is automatically generated by scripts/build-corejs3-shipped-proposals.mjs\n\nexport default new Set([\n \"esnext.array.group\",\n \"esnext.array.group-to-map\",\n \"esnext.iterator.zip\",\n \"esnext.iterator.zip-keyed\",\n \"esnext.symbol.metadata\",\n]);\n","import corejs3Polyfills from \"../core-js-compat/data.js\";\n\ntype ObjectMap = { [name: string]: V };\ntype ObjectMap2 = ObjectMap>;\n\nexport type CoreJSPolyfillDescriptor = {\n name: string;\n pure: string | null;\n global: string[];\n exclude: string[] | null;\n};\n\nconst polyfillsOrder = {};\nObject.keys(corejs3Polyfills).forEach((name, index) => {\n polyfillsOrder[name] = index;\n});\n\nconst define = (\n pure,\n global,\n name = global[0],\n exclude?,\n): CoreJSPolyfillDescriptor => {\n return {\n name,\n pure,\n global: global.sort((a, b) => polyfillsOrder[a] - polyfillsOrder[b]),\n exclude,\n };\n};\n\nconst typed = (...modules) =>\n define(null, [...modules, ...TypedArrayDependencies]);\n\nconst ArrayNatureIterators = [\n \"es.array.iterator\",\n \"web.dom-collections.iterator\",\n];\n\nexport const CommonIterators = [\"es.string.iterator\", ...ArrayNatureIterators];\n\nconst ArrayNatureIteratorsWithTag = [\n \"es.object.to-string\",\n ...ArrayNatureIterators,\n];\n\nconst CommonIteratorsWithTag = [\"es.object.to-string\", ...CommonIterators];\n\nconst ErrorDependencies = [\"es.error.cause\", \"es.error.to-string\"];\n\nconst SuppressedErrorDependencies = [\n \"es.suppressed-error.constructor\",\n ...ErrorDependencies,\n];\n\nconst ArrayBufferDependencies = [\n \"es.array-buffer.constructor\",\n \"es.array-buffer.slice\",\n \"es.data-view\",\n \"es.array-buffer.detached\",\n \"es.array-buffer.transfer\",\n \"es.array-buffer.transfer-to-fixed-length\",\n \"es.object.to-string\",\n];\n\nconst TypedArrayDependencies = [\n \"es.typed-array.at\",\n \"es.typed-array.copy-within\",\n \"es.typed-array.every\",\n \"es.typed-array.fill\",\n \"es.typed-array.filter\",\n \"es.typed-array.find\",\n \"es.typed-array.find-index\",\n \"es.typed-array.find-last\",\n \"es.typed-array.find-last-index\",\n \"es.typed-array.for-each\",\n \"es.typed-array.includes\",\n \"es.typed-array.index-of\",\n \"es.typed-array.iterator\",\n \"es.typed-array.join\",\n \"es.typed-array.last-index-of\",\n \"es.typed-array.map\",\n \"es.typed-array.reduce\",\n \"es.typed-array.reduce-right\",\n \"es.typed-array.reverse\",\n \"es.typed-array.set\",\n \"es.typed-array.slice\",\n \"es.typed-array.some\",\n \"es.typed-array.sort\",\n \"es.typed-array.subarray\",\n \"es.typed-array.to-locale-string\",\n \"es.typed-array.to-reversed\",\n \"es.typed-array.to-sorted\",\n \"es.typed-array.to-string\",\n \"es.typed-array.with\",\n \"es.object.to-string\",\n \"es.array.iterator\",\n \"esnext.typed-array.filter-reject\",\n \"esnext.typed-array.group-by\",\n \"esnext.typed-array.to-spliced\",\n \"esnext.typed-array.unique-by\",\n ...ArrayBufferDependencies,\n];\n\nexport const PromiseDependencies = [\"es.promise\", \"es.object.to-string\"];\n\nexport const PromiseDependenciesWithIterators = [\n ...PromiseDependencies,\n ...CommonIterators,\n];\n\nconst SymbolDependencies = [\n \"es.symbol\",\n \"es.symbol.description\",\n \"es.object.to-string\",\n];\n\nconst MapDependencies = [\n \"es.map\",\n \"es.map.get-or-insert\",\n \"es.map.get-or-insert-computed\",\n \"esnext.map.delete-all\",\n \"esnext.map.emplace\",\n \"esnext.map.every\",\n \"esnext.map.filter\",\n \"esnext.map.find\",\n \"esnext.map.find-key\",\n \"esnext.map.includes\",\n \"esnext.map.key-of\",\n \"esnext.map.map-keys\",\n \"esnext.map.map-values\",\n \"esnext.map.merge\",\n \"esnext.map.reduce\",\n \"esnext.map.some\",\n \"esnext.map.update\",\n ...CommonIteratorsWithTag,\n];\n\nconst SetDependencies = [\n \"es.set\",\n \"es.set.difference.v2\",\n \"es.set.intersection.v2\",\n \"es.set.is-disjoint-from.v2\",\n \"es.set.is-subset-of.v2\",\n \"es.set.is-superset-of.v2\",\n \"es.set.symmetric-difference.v2\",\n \"es.set.union.v2\",\n \"esnext.set.add-all\",\n \"esnext.set.delete-all\",\n \"esnext.set.difference\",\n \"esnext.set.every\",\n \"esnext.set.filter\",\n \"esnext.set.find\",\n \"esnext.set.intersection\",\n \"esnext.set.is-disjoint-from\",\n \"esnext.set.is-subset-of\",\n \"esnext.set.is-superset-of\",\n \"esnext.set.join\",\n \"esnext.set.map\",\n \"esnext.set.reduce\",\n \"esnext.set.some\",\n \"esnext.set.symmetric-difference\",\n \"esnext.set.union\",\n ...CommonIteratorsWithTag,\n];\n\nconst WeakMapDependencies = [\n \"es.weak-map\",\n \"es.weak-map.get-or-insert\",\n \"es.weak-map.get-or-insert-computed\",\n \"esnext.weak-map.delete-all\",\n \"esnext.weak-map.emplace\",\n ...CommonIteratorsWithTag,\n];\n\nconst WeakSetDependencies = [\n \"es.weak-set\",\n \"esnext.weak-set.add-all\",\n \"esnext.weak-set.delete-all\",\n ...CommonIteratorsWithTag,\n];\n\nconst DOMExceptionDependencies = [\n \"web.dom-exception.constructor\",\n \"web.dom-exception.stack\",\n \"web.dom-exception.to-string-tag\",\n \"es.error.to-string\",\n];\n\nconst URLSearchParamsDependencies = [\n \"web.url-search-params\",\n \"web.url-search-params.delete\",\n \"web.url-search-params.has\",\n \"web.url-search-params.size\",\n ...CommonIteratorsWithTag,\n];\n\nconst AsyncIteratorDependencies = [\n \"esnext.async-iterator.constructor\",\n ...PromiseDependencies,\n];\n\nconst AsyncIteratorProblemMethods = [\n \"esnext.async-iterator.every\",\n \"esnext.async-iterator.filter\",\n \"esnext.async-iterator.find\",\n \"esnext.async-iterator.flat-map\",\n \"esnext.async-iterator.for-each\",\n \"esnext.async-iterator.map\",\n \"esnext.async-iterator.reduce\",\n \"esnext.async-iterator.some\",\n];\n\nconst IteratorDependencies = [\"es.iterator.constructor\", \"es.object.to-string\"];\n\nexport const DecoratorMetadataDependencies = [\n \"esnext.symbol.metadata\",\n \"esnext.function.metadata\",\n];\n\nconst TypedArrayStaticMethods = (base: string) => ({\n from: define(null, [\"es.typed-array.from\", base, ...TypedArrayDependencies]),\n fromAsync: define(null, [\n \"esnext.typed-array.from-async\",\n base,\n ...PromiseDependenciesWithIterators,\n ...TypedArrayDependencies,\n ]),\n of: define(null, [\"es.typed-array.of\", base, ...TypedArrayDependencies]),\n});\n\nconst DataViewDependencies = [\"es.data-view\", ...ArrayBufferDependencies];\n\nexport const BuiltIns: ObjectMap = {\n AsyncDisposableStack: define(\"async-disposable-stack/index\", [\n \"es.async-disposable-stack.constructor\",\n \"es.object.to-string\",\n \"es.async-iterator.async-dispose\",\n \"es.iterator.dispose\",\n ...PromiseDependencies,\n ...SuppressedErrorDependencies,\n ]),\n AsyncIterator: define(\"async-iterator/index\", AsyncIteratorDependencies),\n AggregateError: define(\"aggregate-error\", [\n \"es.aggregate-error\",\n ...ErrorDependencies,\n ...CommonIteratorsWithTag,\n \"es.aggregate-error.cause\",\n ]),\n ArrayBuffer: define(null, ArrayBufferDependencies),\n DataView: define(null, DataViewDependencies),\n Date: define(null, [\"es.date.to-string\"]),\n DOMException: define(\"dom-exception/index\", DOMExceptionDependencies),\n DisposableStack: define(\"disposable-stack/index\", [\n \"es.disposable-stack.constructor\",\n \"es.object.to-string\",\n \"es.iterator.dispose\",\n ...SuppressedErrorDependencies,\n ]),\n Error: define(null, ErrorDependencies),\n EvalError: define(null, ErrorDependencies),\n Float32Array: typed(\"es.typed-array.float32-array\"),\n Float64Array: typed(\"es.typed-array.float64-array\"),\n Int8Array: typed(\"es.typed-array.int8-array\"),\n Int16Array: typed(\"es.typed-array.int16-array\"),\n Int32Array: typed(\"es.typed-array.int32-array\"),\n Iterator: define(\"iterator/index\", IteratorDependencies),\n Uint8Array: typed(\n \"es.typed-array.uint8-array\",\n \"es.uint8-array.set-from-base64\",\n \"es.uint8-array.set-from-hex\",\n \"es.uint8-array.to-base64\",\n \"es.uint8-array.to-hex\",\n ),\n Uint8ClampedArray: typed(\"es.typed-array.uint8-clamped-array\"),\n Uint16Array: typed(\"es.typed-array.uint16-array\"),\n Uint32Array: typed(\"es.typed-array.uint32-array\"),\n Map: define(\"map/index\", MapDependencies),\n Number: define(null, [\"es.number.constructor\"]),\n Observable: define(\"observable/index\", [\n \"esnext.observable\",\n \"esnext.symbol.observable\",\n \"es.object.to-string\",\n ...CommonIteratorsWithTag,\n ]),\n Promise: define(\"promise/index\", PromiseDependencies),\n RangeError: define(null, ErrorDependencies),\n ReferenceError: define(null, ErrorDependencies),\n Reflect: define(null, [\"es.reflect.to-string-tag\", \"es.object.to-string\"]),\n RegExp: define(null, [\n \"es.regexp.constructor\",\n \"es.regexp.dot-all\",\n \"es.regexp.exec\",\n \"es.regexp.sticky\",\n \"es.regexp.to-string\",\n ]),\n Set: define(\"set/index\", SetDependencies),\n SuppressedError: define(\"suppressed-error\", SuppressedErrorDependencies),\n Symbol: define(\"symbol/index\", SymbolDependencies),\n SyntaxError: define(null, ErrorDependencies),\n TypeError: define(null, ErrorDependencies),\n URIError: define(null, ErrorDependencies),\n URL: define(\"url/index\", [\n \"web.url\",\n \"web.url.to-json\",\n ...URLSearchParamsDependencies,\n ]),\n URLSearchParams: define(\n \"url-search-params/index\",\n URLSearchParamsDependencies,\n ),\n WeakMap: define(\"weak-map/index\", WeakMapDependencies),\n WeakSet: define(\"weak-set/index\", WeakSetDependencies),\n\n atob: define(\"atob\", [\"web.atob\", ...DOMExceptionDependencies]),\n btoa: define(\"btoa\", [\"web.btoa\", ...DOMExceptionDependencies]),\n clearImmediate: define(\"clear-immediate\", [\"web.immediate\"]),\n compositeKey: define(\"composite-key\", [\"esnext.composite-key\"]),\n compositeSymbol: define(\"composite-symbol\", [\"esnext.composite-symbol\"]),\n escape: define(\"escape\", [\"es.escape\"]),\n fetch: define(null, PromiseDependencies),\n globalThis: define(\"global-this\", [\"es.global-this\"]),\n parseFloat: define(\"parse-float\", [\"es.parse-float\"]),\n parseInt: define(\"parse-int\", [\"es.parse-int\"]),\n queueMicrotask: define(\"queue-microtask\", [\"web.queue-microtask\"]),\n self: define(\"self\", [\"web.self\"]),\n setImmediate: define(\"set-immediate\", [\"web.immediate\"]),\n setInterval: define(\"set-interval\", [\"web.timers\"]),\n setTimeout: define(\"set-timeout\", [\"web.timers\"]),\n structuredClone: define(\"structured-clone\", [\n \"web.structured-clone\",\n ...DOMExceptionDependencies,\n \"es.array.iterator\",\n \"es.object.keys\",\n \"es.object.to-string\",\n \"es.map\",\n \"es.set\",\n ]),\n unescape: define(\"unescape\", [\"es.unescape\"]),\n};\n\nexport const StaticProperties: ObjectMap2 = {\n AsyncIterator: {\n from: define(\"async-iterator/from\", [\n \"esnext.async-iterator.from\",\n ...AsyncIteratorDependencies,\n ...AsyncIteratorProblemMethods,\n ...CommonIterators,\n ]),\n },\n Array: {\n from: define(\"array/from\", [\"es.array.from\", \"es.string.iterator\"]),\n fromAsync: define(\"array/from-async\", [\n \"es.array.from-async\",\n ...PromiseDependenciesWithIterators,\n ]),\n isArray: define(\"array/is-array\", [\"es.array.is-array\"]),\n isTemplateObject: define(\"array/is-template-object\", [\n \"esnext.array.is-template-object\",\n ]),\n of: define(\"array/of\", [\"es.array.of\"]),\n },\n\n ArrayBuffer: {\n isView: define(null, [\"es.array-buffer.is-view\"]),\n },\n\n BigInt: {\n range: define(\"bigint/range\", [\n \"esnext.bigint.range\",\n \"es.object.to-string\",\n ]),\n },\n\n Date: {\n now: define(\"date/now\", [\"es.date.now\"]),\n },\n\n Error: {\n isError: define(\"error/is-error\", [\n \"es.error.is-error\",\n \"es.object.create\",\n ]),\n },\n\n Function: {\n isCallable: define(\"function/is-callable\", [\"esnext.function.is-callable\"]),\n isConstructor: define(\"function/is-constructor\", [\n \"esnext.function.is-constructor\",\n ]),\n },\n\n Iterator: {\n concat: define(\"iterator/concat\", [\n \"es.iterator.concat\",\n ...IteratorDependencies,\n ...CommonIterators,\n ]),\n from: define(\"iterator/from\", [\n \"es.iterator.from\",\n ...IteratorDependencies,\n ...CommonIterators,\n ]),\n range: define(\"iterator/range\", [\n \"esnext.iterator.range\",\n ...IteratorDependencies,\n ]),\n zip: define(\"iterator/zip\", [\n \"esnext.iterator.zip\",\n ...IteratorDependencies,\n ...CommonIterators,\n ]),\n zipKeyed: define(\"iterator/zip-keyed\", [\n \"esnext.iterator.zip-keyed\",\n \"es.object.create\",\n \"es.reflect.own-keys\",\n ...IteratorDependencies,\n ...CommonIterators,\n ]),\n },\n\n JSON: {\n isRawJSON: define(\"json/is-raw-json\", [\"es.json.is-raw-json\"]),\n parse: define(\"json/parse\", [\"es.json.parse\", \"es.object.keys\"]),\n rawJSON: define(\"json/raw-json\", [\n \"es.json.raw-json\",\n \"es.object.create\",\n \"es.object.freeze\",\n ]),\n stringify: define(\"json/stringify\", [\n \"es.json.stringify\",\n \"es.date.to-json\",\n ]),\n },\n\n Math: {\n DEG_PER_RAD: define(\"math/deg-per-rad\", [\"esnext.math.deg-per-rad\"]),\n RAD_PER_DEG: define(\"math/rad-per-deg\", [\"esnext.math.rad-per-deg\"]),\n acosh: define(\"math/acosh\", [\"es.math.acosh\"]),\n asinh: define(\"math/asinh\", [\"es.math.asinh\"]),\n atanh: define(\"math/atanh\", [\"es.math.atanh\"]),\n cbrt: define(\"math/cbrt\", [\"es.math.cbrt\"]),\n clamp: define(\"math/clamp\", [\"esnext.math.clamp\"]),\n clz32: define(\"math/clz32\", [\"es.math.clz32\"]),\n cosh: define(\"math/cosh\", [\"es.math.cosh\"]),\n degrees: define(\"math/degrees\", [\"esnext.math.degrees\"]),\n expm1: define(\"math/expm1\", [\"es.math.expm1\"]),\n fround: define(\"math/fround\", [\"es.math.fround\"]),\n f16round: define(\"math/f16round\", [\"es.math.f16round\"]),\n fscale: define(\"math/fscale\", [\"esnext.math.fscale\"]),\n hypot: define(\"math/hypot\", [\"es.math.hypot\"]),\n iaddh: define(\"math/iaddh\", [\"esnext.math.iaddh\"]),\n imul: define(\"math/imul\", [\"es.math.imul\"]),\n imulh: define(\"math/imulh\", [\"esnext.math.imulh\"]),\n isubh: define(\"math/isubh\", [\"esnext.math.isubh\"]),\n log10: define(\"math/log10\", [\"es.math.log10\"]),\n log1p: define(\"math/log1p\", [\"es.math.log1p\"]),\n log2: define(\"math/log2\", [\"es.math.log2\"]),\n radians: define(\"math/radians\", [\"esnext.math.radians\"]),\n scale: define(\"math/scale\", [\"esnext.math.scale\"]),\n seededPRNG: define(\"math/seeded-prng\", [\"esnext.math.seeded-prng\"]),\n sign: define(\"math/sign\", [\"es.math.sign\"]),\n signbit: define(\"math/signbit\", [\"esnext.math.signbit\"]),\n sinh: define(\"math/sinh\", [\"es.math.sinh\"]),\n sumPrecise: define(\"math/sum-precise\", [\n \"es.math.sum-precise\",\n \"es.array.iterator\",\n ]),\n tanh: define(\"math/tanh\", [\"es.math.tanh\"]),\n trunc: define(\"math/trunc\", [\"es.math.trunc\"]),\n umulh: define(\"math/umulh\", [\"esnext.math.umulh\"]),\n },\n\n Map: {\n from: define(\"map/from\", [\"esnext.map.from\", ...MapDependencies]),\n groupBy: define(\"map/group-by\", [\"es.map.group-by\", ...MapDependencies]),\n keyBy: define(\"map/key-by\", [\"esnext.map.key-by\", ...MapDependencies]),\n of: define(\"map/of\", [\"esnext.map.of\", ...MapDependencies]),\n },\n\n Number: {\n EPSILON: define(\"number/epsilon\", [\"es.number.epsilon\"]),\n MAX_SAFE_INTEGER: define(\"number/max-safe-integer\", [\n \"es.number.max-safe-integer\",\n ]),\n MIN_SAFE_INTEGER: define(\"number/min-safe-integer\", [\n \"es.number.min-safe-integer\",\n ]),\n fromString: define(\"number/from-string\", [\"esnext.number.from-string\"]),\n isFinite: define(\"number/is-finite\", [\"es.number.is-finite\"]),\n isInteger: define(\"number/is-integer\", [\"es.number.is-integer\"]),\n isNaN: define(\"number/is-nan\", [\"es.number.is-nan\"]),\n isSafeInteger: define(\"number/is-safe-integer\", [\n \"es.number.is-safe-integer\",\n ]),\n parseFloat: define(\"number/parse-float\", [\"es.number.parse-float\"]),\n parseInt: define(\"number/parse-int\", [\"es.number.parse-int\"]),\n range: define(\"number/range\", [\n \"esnext.number.range\",\n \"es.object.to-string\",\n ]),\n },\n\n Object: {\n assign: define(\"object/assign\", [\"es.object.assign\"]),\n create: define(\"object/create\", [\"es.object.create\"]),\n defineProperties: define(\"object/define-properties\", [\n \"es.object.define-properties\",\n ]),\n defineProperty: define(\"object/define-property\", [\n \"es.object.define-property\",\n ]),\n entries: define(\"object/entries\", [\"es.object.entries\"]),\n freeze: define(\"object/freeze\", [\"es.object.freeze\"]),\n fromEntries: define(\"object/from-entries\", [\n \"es.object.from-entries\",\n \"es.array.iterator\",\n ]),\n getOwnPropertyDescriptor: define(\"object/get-own-property-descriptor\", [\n \"es.object.get-own-property-descriptor\",\n ]),\n getOwnPropertyDescriptors: define(\"object/get-own-property-descriptors\", [\n \"es.object.get-own-property-descriptors\",\n ]),\n getOwnPropertyNames: define(\"object/get-own-property-names\", [\n \"es.object.get-own-property-names\",\n ]),\n getOwnPropertySymbols: define(\"object/get-own-property-symbols\", [\n \"es.symbol\",\n ]),\n getPrototypeOf: define(\"object/get-prototype-of\", [\n \"es.object.get-prototype-of\",\n ]),\n groupBy: define(\"object/group-by\", [\n \"es.object.group-by\",\n \"es.object.create\",\n ]),\n hasOwn: define(\"object/has-own\", [\"es.object.has-own\"]),\n is: define(\"object/is\", [\"es.object.is\"]),\n isExtensible: define(\"object/is-extensible\", [\"es.object.is-extensible\"]),\n isFrozen: define(\"object/is-frozen\", [\"es.object.is-frozen\"]),\n isSealed: define(\"object/is-sealed\", [\"es.object.is-sealed\"]),\n keys: define(\"object/keys\", [\"es.object.keys\"]),\n preventExtensions: define(\"object/prevent-extensions\", [\n \"es.object.prevent-extensions\",\n ]),\n seal: define(\"object/seal\", [\"es.object.seal\"]),\n setPrototypeOf: define(\"object/set-prototype-of\", [\n \"es.object.set-prototype-of\",\n ]),\n values: define(\"object/values\", [\"es.object.values\"]),\n },\n\n Promise: {\n all: define(null, PromiseDependenciesWithIterators),\n allSettled: define(\"promise/all-settled\", [\n \"es.promise.all-settled\",\n ...PromiseDependenciesWithIterators,\n ]),\n any: define(\"promise/any\", [\n \"es.promise.any\",\n \"es.aggregate-error\",\n ...PromiseDependenciesWithIterators,\n ]),\n race: define(null, PromiseDependenciesWithIterators),\n try: define(\"promise/try\", [\"es.promise.try\", ...PromiseDependencies]),\n withResolvers: define(\"promise/with-resolvers\", [\n \"es.promise.with-resolvers\",\n ...PromiseDependencies,\n ]),\n },\n\n Reflect: {\n apply: define(\"reflect/apply\", [\"es.reflect.apply\"]),\n construct: define(\"reflect/construct\", [\"es.reflect.construct\"]),\n defineMetadata: define(\"reflect/define-metadata\", [\n \"esnext.reflect.define-metadata\",\n ]),\n defineProperty: define(\"reflect/define-property\", [\n \"es.reflect.define-property\",\n ]),\n deleteMetadata: define(\"reflect/delete-metadata\", [\n \"esnext.reflect.delete-metadata\",\n ]),\n deleteProperty: define(\"reflect/delete-property\", [\n \"es.reflect.delete-property\",\n ]),\n get: define(\"reflect/get\", [\"es.reflect.get\"]),\n getMetadata: define(\"reflect/get-metadata\", [\n \"esnext.reflect.get-metadata\",\n ]),\n getMetadataKeys: define(\"reflect/get-metadata-keys\", [\n \"esnext.reflect.get-metadata-keys\",\n ]),\n getOwnMetadata: define(\"reflect/get-own-metadata\", [\n \"esnext.reflect.get-own-metadata\",\n ]),\n getOwnMetadataKeys: define(\"reflect/get-own-metadata-keys\", [\n \"esnext.reflect.get-own-metadata-keys\",\n ]),\n getOwnPropertyDescriptor: define(\"reflect/get-own-property-descriptor\", [\n \"es.reflect.get-own-property-descriptor\",\n ]),\n getPrototypeOf: define(\"reflect/get-prototype-of\", [\n \"es.reflect.get-prototype-of\",\n ]),\n has: define(\"reflect/has\", [\"es.reflect.has\"]),\n hasMetadata: define(\"reflect/has-metadata\", [\n \"esnext.reflect.has-metadata\",\n ]),\n hasOwnMetadata: define(\"reflect/has-own-metadata\", [\n \"esnext.reflect.has-own-metadata\",\n ]),\n isExtensible: define(\"reflect/is-extensible\", [\"es.reflect.is-extensible\"]),\n metadata: define(\"reflect/metadata\", [\"esnext.reflect.metadata\"]),\n ownKeys: define(\"reflect/own-keys\", [\"es.reflect.own-keys\"]),\n preventExtensions: define(\"reflect/prevent-extensions\", [\n \"es.reflect.prevent-extensions\",\n ]),\n set: define(\"reflect/set\", [\"es.reflect.set\"]),\n setPrototypeOf: define(\"reflect/set-prototype-of\", [\n \"es.reflect.set-prototype-of\",\n ]),\n },\n\n RegExp: {\n escape: define(\"regexp/escape\", [\"es.regexp.escape\"]),\n },\n\n Set: {\n from: define(\"set/from\", [\"esnext.set.from\", ...SetDependencies]),\n of: define(\"set/of\", [\"esnext.set.of\", ...SetDependencies]),\n },\n\n String: {\n cooked: define(\"string/cooked\", [\"esnext.string.cooked\"]),\n dedent: define(\"string/dedent\", [\n \"esnext.string.dedent\",\n \"es.string.from-code-point\",\n \"es.weak-map\",\n ]),\n fromCodePoint: define(\"string/from-code-point\", [\n \"es.string.from-code-point\",\n ]),\n raw: define(\"string/raw\", [\"es.string.raw\"]),\n },\n\n Symbol: {\n asyncDispose: define(\"symbol/async-dispose\", [\n \"es.symbol.async-dispose\",\n \"es.async-iterator.async-dispose\",\n ]),\n asyncIterator: define(\"symbol/async-iterator\", [\n \"es.symbol.async-iterator\",\n ]),\n customMatcher: define(\"symbol/custom-matcher\", [\n \"esnext.symbol.custom-matcher\",\n ]),\n dispose: define(\"symbol/dispose\", [\n \"es.symbol.dispose\",\n \"es.iterator.dispose\",\n ]),\n for: define(\"symbol/for\", [], \"es.symbol\"),\n hasInstance: define(\"symbol/has-instance\", [\n \"es.symbol.has-instance\",\n \"es.function.has-instance\",\n ]),\n isConcatSpreadable: define(\"symbol/is-concat-spreadable\", [\n \"es.symbol.is-concat-spreadable\",\n \"es.array.concat\",\n ]),\n isRegistered: define(\"symbol/is-registered\", [\n \"esnext.symbol.is-registered\",\n \"es.symbol\",\n ]),\n isRegisteredSymbol: define(\"symbol/is-registered-symbol\", [\n \"esnext.symbol.is-registered-symbol\",\n \"es.symbol\",\n ]),\n isWellKnown: define(\"symbol/is-well-known\", [\n \"esnext.symbol.is-well-known\",\n \"es.symbol\",\n ]),\n isWellKnownSymbol: define(\"symbol/is-well-known-symbol\", [\n \"esnext.symbol.is-well-known-symbol\",\n \"es.symbol\",\n ]),\n iterator: define(\"symbol/iterator\", [\n \"es.symbol.iterator\",\n ...CommonIteratorsWithTag,\n ]),\n keyFor: define(\"symbol/key-for\", [], \"es.symbol\"),\n match: define(\"symbol/match\", [\"es.symbol.match\", \"es.string.match\"]),\n matcher: define(\"symbol/matcher\", [\"esnext.symbol.matcher\"]),\n matchAll: define(\"symbol/match-all\", [\n \"es.symbol.match-all\",\n \"es.string.match-all\",\n ]),\n metadata: define(\"symbol/metadata\", DecoratorMetadataDependencies),\n metadataKey: define(\"symbol/metadata-key\", [\"esnext.symbol.metadata-key\"]),\n observable: define(\"symbol/observable\", [\"esnext.symbol.observable\"]),\n patternMatch: define(\"symbol/pattern-match\", [\n \"esnext.symbol.pattern-match\",\n ]),\n replace: define(\"symbol/replace\", [\n \"es.symbol.replace\",\n \"es.string.replace\",\n ]),\n search: define(\"symbol/search\", [\"es.symbol.search\", \"es.string.search\"]),\n species: define(\"symbol/species\", [\n \"es.symbol.species\",\n \"es.array.species\",\n ]),\n split: define(\"symbol/split\", [\"es.symbol.split\", \"es.string.split\"]),\n toPrimitive: define(\"symbol/to-primitive\", [\n \"es.symbol.to-primitive\",\n \"es.date.to-primitive\",\n ]),\n toStringTag: define(\"symbol/to-string-tag\", [\n \"es.symbol.to-string-tag\",\n \"es.object.to-string\",\n \"es.math.to-string-tag\",\n \"es.json.to-string-tag\",\n ]),\n unscopables: define(\"symbol/unscopables\", [\"es.symbol.unscopables\"]),\n },\n\n URL: {\n canParse: define(\"url/can-parse\", [\"web.url.can-parse\", \"web.url\"]),\n parse: define(\"url/parse\", [\"web.url.parse\", \"web.url\"]),\n },\n\n WeakMap: {\n from: define(\"weak-map/from\", [\n \"esnext.weak-map.from\",\n ...WeakMapDependencies,\n ]),\n of: define(\"weak-map/of\", [\"esnext.weak-map.of\", ...WeakMapDependencies]),\n },\n\n WeakSet: {\n from: define(\"weak-set/from\", [\n \"esnext.weak-set.from\",\n ...WeakSetDependencies,\n ]),\n of: define(\"weak-set/of\", [\"esnext.weak-set.of\", ...WeakSetDependencies]),\n },\n\n Int8Array: TypedArrayStaticMethods(\"es.typed-array.int8-array\"),\n Uint8Array: {\n fromBase64: define(null, [\n \"es.uint8-array.from-base64\",\n ...TypedArrayDependencies,\n ]),\n fromHex: define(null, [\n \"es.uint8-array.from-hex\",\n ...TypedArrayDependencies,\n ]),\n ...TypedArrayStaticMethods(\"es.typed-array.uint8-array\"),\n },\n Uint8ClampedArray: TypedArrayStaticMethods(\n \"es.typed-array.uint8-clamped-array\",\n ),\n Int16Array: TypedArrayStaticMethods(\"es.typed-array.int16-array\"),\n Uint16Array: TypedArrayStaticMethods(\"es.typed-array.uint16-array\"),\n Int32Array: TypedArrayStaticMethods(\"es.typed-array.int32-array\"),\n Uint32Array: TypedArrayStaticMethods(\"es.typed-array.uint32-array\"),\n Float32Array: TypedArrayStaticMethods(\"es.typed-array.float32-array\"),\n Float64Array: TypedArrayStaticMethods(\"es.typed-array.float64-array\"),\n\n WebAssembly: {\n CompileError: define(null, ErrorDependencies),\n LinkError: define(null, ErrorDependencies),\n RuntimeError: define(null, ErrorDependencies),\n },\n};\n\n[\n \"AggregateError\",\n \"EvalError\",\n \"RangeError\",\n \"ReferenceError\",\n \"SuppressedError\",\n \"SyntaxError\",\n \"TypeError\",\n \"URIError\",\n].forEach(ERROR_SUBCLASS => {\n StaticProperties[ERROR_SUBCLASS] = StaticProperties.Error;\n});\n\nexport const InstanceProperties = {\n asIndexedPairs: define(null, [\n \"esnext.async-iterator.as-indexed-pairs\",\n ...AsyncIteratorDependencies,\n \"esnext.iterator.as-indexed-pairs\",\n ...IteratorDependencies,\n ]),\n at: define(\"instance/at\", [\n // TODO: We should introduce overloaded instance methods definition\n // Before that is implemented, the `esnext.string.at` must be the first\n // In pure mode, the provider resolves the descriptor as a \"pure\" `esnext.string.at`\n // and treats the compat-data of `esnext.string.at` as the compat-data of\n // pure import `instance/at`. The first polyfill here should have the lowest corejs\n // supported versions.\n \"esnext.string.at\",\n \"es.string.at-alternative\",\n \"es.array.at\",\n ]),\n anchor: define(null, [\"es.string.anchor\"]),\n big: define(null, [\"es.string.big\"]),\n bind: define(\"instance/bind\", [\"es.function.bind\"]),\n blink: define(null, [\"es.string.blink\"]),\n bold: define(null, [\"es.string.bold\"]),\n chunks: define(null, [\"esnext.iterator.chunks\", ...IteratorDependencies]),\n clamp: define(\"instance/clamp\", [\"esnext.number.clamp\"]),\n codePointAt: define(\"instance/code-point-at\", [\"es.string.code-point-at\"]),\n codePoints: define(\"instance/code-points\", [\"esnext.string.code-points\"]),\n concat: define(\"instance/concat\", [\"es.array.concat\"], undefined, [\"String\"]),\n copyWithin: define(\"instance/copy-within\", [\"es.array.copy-within\"]),\n demethodize: define(\"instance/demethodize\", [\"esnext.function.demethodize\"]),\n description: define(null, [\"es.symbol\", \"es.symbol.description\"]),\n dotAll: define(null, [\"es.regexp.dot-all\"]),\n drop: define(null, [\n \"es.iterator.drop\",\n ...IteratorDependencies,\n \"esnext.async-iterator.drop\",\n ...AsyncIteratorDependencies,\n ]),\n endsWith: define(\"instance/ends-with\", [\"es.string.ends-with\"]),\n entries: define(\"instance/entries\", ArrayNatureIteratorsWithTag),\n every: define(\"instance/every\", [\n \"es.array.every\",\n \"es.iterator.every\",\n ...IteratorDependencies,\n // TODO: add async iterator dependencies when we support sub-dependencies\n // esnext.async-iterator.every depends on es.promise\n // but we don't want to pull es.promise when esnext.async-iterator is disabled\n //\n // \"esnext.async-iterator.every\",\n // ...AsyncIteratorDependencies\n ]),\n exec: define(null, [\"es.regexp.exec\"]),\n fill: define(\"instance/fill\", [\"es.array.fill\"]),\n filter: define(\"instance/filter\", [\n \"es.array.filter\",\n \"es.iterator.filter\",\n ...IteratorDependencies,\n // \"esnext.async-iterator.filter\",\n ]),\n filterReject: define(\"instance/filter-reject\", [\n \"esnext.array.filter-reject\",\n ]),\n finally: define(null, [\"es.promise.finally\", ...PromiseDependencies]),\n find: define(\"instance/find\", [\n \"es.array.find\",\n \"es.iterator.find\",\n ...IteratorDependencies,\n // \"esnext.async-iterator.find\",\n ]),\n findIndex: define(\"instance/find-index\", [\"es.array.find-index\"]),\n findLast: define(\"instance/find-last\", [\"es.array.find-last\"]),\n findLastIndex: define(\"instance/find-last-index\", [\n \"es.array.find-last-index\",\n ]),\n fixed: define(null, [\"es.string.fixed\"]),\n flags: define(\"instance/flags\", [\"es.regexp.flags\"]),\n flatMap: define(\"instance/flat-map\", [\n \"es.array.flat-map\",\n \"es.array.unscopables.flat-map\",\n \"es.iterator.flat-map\",\n ...IteratorDependencies,\n // \"esnext.async-iterator.flat-map\",\n ]),\n flat: define(\"instance/flat\", [\"es.array.flat\", \"es.array.unscopables.flat\"]),\n getFloat16: define(null, [\n \"es.data-view.get-float16\",\n ...DataViewDependencies,\n ]),\n getUint8Clamped: define(null, [\n \"esnext.data-view.get-uint8-clamped\",\n ...DataViewDependencies,\n ]),\n getYear: define(null, [\"es.date.get-year\"]),\n group: define(\"instance/group\", [\"esnext.array.group\"]),\n groupBy: define(\"instance/group-by\", [\"esnext.array.group-by\"]),\n groupByToMap: define(\"instance/group-by-to-map\", [\n \"esnext.array.group-by-to-map\",\n \"es.map\",\n \"es.object.to-string\",\n ]),\n groupToMap: define(\"instance/group-to-map\", [\n \"esnext.array.group-to-map\",\n \"es.map\",\n \"es.object.to-string\",\n ]),\n fontcolor: define(null, [\"es.string.fontcolor\"]),\n fontsize: define(null, [\"es.string.fontsize\"]),\n forEach: define(\"instance/for-each\", [\n \"es.array.for-each\",\n \"es.iterator.for-each\",\n ...IteratorDependencies,\n // \"esnext.async-iterator.for-each\",\n \"web.dom-collections.for-each\",\n ]),\n includes: define(\"instance/includes\", [\n \"es.array.includes\",\n \"es.string.includes\",\n ]),\n indexed: define(null, [\n \"esnext.async-iterator.indexed\",\n ...AsyncIteratorDependencies,\n \"esnext.iterator.indexed\",\n ...IteratorDependencies,\n ]),\n indexOf: define(\"instance/index-of\", [\"es.array.index-of\"]),\n isWellFormed: define(\"instance/is-well-formed\", [\"es.string.is-well-formed\"]),\n italics: define(null, [\"es.string.italics\"]),\n join: define(null, [\"es.array.join\"]),\n keys: define(\"instance/keys\", ArrayNatureIteratorsWithTag),\n lastIndex: define(null, [\"esnext.array.last-index\"]),\n lastIndexOf: define(\"instance/last-index-of\", [\"es.array.last-index-of\"]),\n lastItem: define(null, [\"esnext.array.last-item\"]),\n link: define(null, [\"es.string.link\"]),\n map: define(\"instance/map\", [\n \"es.array.map\",\n \"es.iterator.map\",\n ...IteratorDependencies,\n // \"esnext.async-iterator.map\",\n ]),\n match: define(null, [\"es.string.match\", \"es.regexp.exec\"]),\n matchAll: define(\"instance/match-all\", [\n \"es.string.match-all\",\n \"es.regexp.exec\",\n ]),\n name: define(null, [\"es.function.name\"]),\n padEnd: define(\"instance/pad-end\", [\"es.string.pad-end\"]),\n padStart: define(\"instance/pad-start\", [\"es.string.pad-start\"]),\n push: define(\"instance/push\", [\"es.array.push\"]),\n reduce: define(\"instance/reduce\", [\n \"es.array.reduce\",\n \"es.iterator.reduce\",\n ...IteratorDependencies,\n // \"esnext.async-iterator.reduce\",\n ]),\n reduceRight: define(\"instance/reduce-right\", [\"es.array.reduce-right\"]),\n repeat: define(\"instance/repeat\", [\"es.string.repeat\"]),\n replace: define(null, [\"es.string.replace\", \"es.regexp.exec\"]),\n replaceAll: define(\"instance/replace-all\", [\n \"es.string.replace-all\",\n \"es.string.replace\",\n \"es.regexp.exec\",\n ]),\n reverse: define(\"instance/reverse\", [\"es.array.reverse\"]),\n search: define(null, [\"es.string.search\", \"es.regexp.exec\"]),\n setFloat16: define(null, [\n \"es.data-view.set-float16\",\n ...DataViewDependencies,\n ]),\n setUint8Clamped: define(null, [\n \"esnext.data-view.set-uint8-clamped\",\n ...DataViewDependencies,\n ]),\n setYear: define(null, [\"es.date.set-year\"]),\n slice: define(\"instance/slice\", [\"es.array.slice\"]),\n sliding: define(null, [\"esnext.iterator.sliding\", ...IteratorDependencies]),\n small: define(null, [\"es.string.small\"]),\n some: define(\"instance/some\", [\n \"es.array.some\",\n \"es.iterator.some\",\n ...IteratorDependencies,\n // \"esnext.async-iterator.some\",\n ]),\n sort: define(\"instance/sort\", [\"es.array.sort\"]),\n splice: define(\"instance/splice\", [\"es.array.splice\"]),\n split: define(null, [\"es.string.split\", \"es.regexp.exec\"]),\n startsWith: define(\"instance/starts-with\", [\"es.string.starts-with\"]),\n sticky: define(null, [\"es.regexp.sticky\"]),\n strike: define(null, [\"es.string.strike\"]),\n sub: define(null, [\"es.string.sub\"]),\n substr: define(null, [\"es.string.substr\"]),\n sup: define(null, [\"es.string.sup\"]),\n take: define(null, [\n \"es.iterator.take\",\n ...IteratorDependencies,\n \"esnext.async-iterator.take\",\n ...AsyncIteratorDependencies,\n ]),\n test: define(null, [\"es.regexp.test\", \"es.regexp.exec\"]),\n toArray: define(null, [\n \"es.iterator.to-array\",\n ...IteratorDependencies,\n \"esnext.async-iterator.to-array\",\n ...AsyncIteratorDependencies,\n ]),\n toAsync: define(null, [\n \"esnext.iterator.to-async\",\n ...IteratorDependencies,\n ...AsyncIteratorDependencies,\n ...AsyncIteratorProblemMethods,\n ]),\n toExponential: define(null, [\"es.number.to-exponential\"]),\n toFixed: define(null, [\"es.number.to-fixed\"]),\n toGMTString: define(null, [\"es.date.to-gmt-string\"]),\n toISOString: define(null, [\"es.date.to-iso-string\"]),\n toJSON: define(null, [\"es.date.to-json\"]),\n toPrecision: define(null, [\"es.number.to-precision\"]),\n toReversed: define(\"instance/to-reversed\", [\"es.array.to-reversed\"]),\n toSorted: define(\"instance/to-sorted\", [\n \"es.array.to-sorted\",\n \"es.array.sort\",\n ]),\n toSpliced: define(\"instance/to-spliced\", [\"es.array.to-spliced\"]),\n toString: define(null, [\n \"es.object.to-string\",\n \"es.error.to-string\",\n \"es.date.to-string\",\n \"es.regexp.to-string\",\n ]),\n toWellFormed: define(\"instance/to-well-formed\", [\"es.string.to-well-formed\"]),\n trim: define(\"instance/trim\", [\"es.string.trim\"]),\n trimEnd: define(\"instance/trim-end\", [\"es.string.trim-end\"]),\n trimLeft: define(\"instance/trim-left\", [\"es.string.trim-start\"]),\n trimRight: define(\"instance/trim-right\", [\"es.string.trim-end\"]),\n trimStart: define(\"instance/trim-start\", [\"es.string.trim-start\"]),\n uniqueBy: define(\"instance/unique-by\", [\"esnext.array.unique-by\", \"es.map\"]),\n unshift: define(\"instance/unshift\", [\"es.array.unshift\"]),\n unThis: define(\"instance/un-this\", [\"esnext.function.un-this\"]),\n values: define(\"instance/values\", ArrayNatureIteratorsWithTag),\n windows: define(null, [\"esnext.iterator.windows\", ...IteratorDependencies]),\n with: define(\"instance/with\", [\"es.array.with\"]),\n __defineGetter__: define(null, [\"es.object.define-getter\"]),\n __defineSetter__: define(null, [\"es.object.define-setter\"]),\n __lookupGetter__: define(null, [\"es.object.lookup-getter\"]),\n __lookupSetter__: define(null, [\"es.object.lookup-setter\"]),\n [\"__proto__\"]: define(null, [\"es.object.proto\"]),\n};\n","// This file contains the list of paths supported by @babel/runtime-corejs3.\n// It must _not_ be edited, as all new features should go through direct\n// injection of core-js-pure imports.\n\nexport const stable = new Set([\n \"array\",\n \"array/from\",\n \"array/is-array\",\n \"array/of\",\n \"clear-immediate\",\n \"date/now\",\n \"instance/bind\",\n \"instance/code-point-at\",\n \"instance/concat\",\n \"instance/copy-within\",\n \"instance/ends-with\",\n \"instance/entries\",\n \"instance/every\",\n \"instance/fill\",\n \"instance/filter\",\n \"instance/find\",\n \"instance/find-index\",\n \"instance/flags\",\n \"instance/flat\",\n \"instance/flat-map\",\n \"instance/for-each\",\n \"instance/includes\",\n \"instance/index-of\",\n \"instance/keys\",\n \"instance/last-index-of\",\n \"instance/map\",\n \"instance/pad-end\",\n \"instance/pad-start\",\n \"instance/reduce\",\n \"instance/reduce-right\",\n \"instance/repeat\",\n \"instance/reverse\",\n \"instance/slice\",\n \"instance/some\",\n \"instance/sort\",\n \"instance/splice\",\n \"instance/starts-with\",\n \"instance/trim\",\n \"instance/trim-end\",\n \"instance/trim-left\",\n \"instance/trim-right\",\n \"instance/trim-start\",\n \"instance/values\",\n \"json/stringify\",\n \"map\",\n \"math/acosh\",\n \"math/asinh\",\n \"math/atanh\",\n \"math/cbrt\",\n \"math/clz32\",\n \"math/cosh\",\n \"math/expm1\",\n \"math/fround\",\n \"math/hypot\",\n \"math/imul\",\n \"math/log10\",\n \"math/log1p\",\n \"math/log2\",\n \"math/sign\",\n \"math/sinh\",\n \"math/tanh\",\n \"math/trunc\",\n \"number/epsilon\",\n \"number/is-finite\",\n \"number/is-integer\",\n \"number/is-nan\",\n \"number/is-safe-integer\",\n \"number/max-safe-integer\",\n \"number/min-safe-integer\",\n \"number/parse-float\",\n \"number/parse-int\",\n \"object/assign\",\n \"object/create\",\n \"object/define-properties\",\n \"object/define-property\",\n \"object/entries\",\n \"object/freeze\",\n \"object/from-entries\",\n \"object/get-own-property-descriptor\",\n \"object/get-own-property-descriptors\",\n \"object/get-own-property-names\",\n \"object/get-own-property-symbols\",\n \"object/get-prototype-of\",\n \"object/is\",\n \"object/is-extensible\",\n \"object/is-frozen\",\n \"object/is-sealed\",\n \"object/keys\",\n \"object/prevent-extensions\",\n \"object/seal\",\n \"object/set-prototype-of\",\n \"object/values\",\n \"parse-float\",\n \"parse-int\",\n \"promise\",\n \"queue-microtask\",\n \"reflect/apply\",\n \"reflect/construct\",\n \"reflect/define-property\",\n \"reflect/delete-property\",\n \"reflect/get\",\n \"reflect/get-own-property-descriptor\",\n \"reflect/get-prototype-of\",\n \"reflect/has\",\n \"reflect/is-extensible\",\n \"reflect/own-keys\",\n \"reflect/prevent-extensions\",\n \"reflect/set\",\n \"reflect/set-prototype-of\",\n \"set\",\n \"set-immediate\",\n \"set-interval\",\n \"set-timeout\",\n \"string/from-code-point\",\n \"string/raw\",\n \"symbol\",\n \"symbol/async-iterator\",\n \"symbol/for\",\n \"symbol/has-instance\",\n \"symbol/is-concat-spreadable\",\n \"symbol/iterator\",\n \"symbol/key-for\",\n \"symbol/match\",\n \"symbol/replace\",\n \"symbol/search\",\n \"symbol/species\",\n \"symbol/split\",\n \"symbol/to-primitive\",\n \"symbol/to-string-tag\",\n \"symbol/unscopables\",\n \"url\",\n \"url-search-params\",\n \"weak-map\",\n \"weak-set\",\n]);\n\nexport const proposals = new Set([\n ...stable,\n \"aggregate-error\",\n \"composite-key\",\n \"composite-symbol\",\n \"global-this\",\n \"instance/at\",\n \"instance/code-points\",\n \"instance/match-all\",\n \"instance/replace-all\",\n \"math/clamp\",\n \"math/degrees\",\n \"math/deg-per-rad\",\n \"math/fscale\",\n \"math/iaddh\",\n \"math/imulh\",\n \"math/isubh\",\n \"math/rad-per-deg\",\n \"math/radians\",\n \"math/scale\",\n \"math/seeded-prng\",\n \"math/signbit\",\n \"math/umulh\",\n \"number/from-string\",\n \"observable\",\n \"reflect/define-metadata\",\n \"reflect/delete-metadata\",\n \"reflect/get-metadata\",\n \"reflect/get-metadata-keys\",\n \"reflect/get-own-metadata\",\n \"reflect/get-own-metadata-keys\",\n \"reflect/has-metadata\",\n \"reflect/has-own-metadata\",\n \"reflect/metadata\",\n \"symbol/dispose\",\n \"symbol/observable\",\n \"symbol/pattern-match\",\n]);\n","import type { CoreJSPolyfillDescriptor } from \"./built-in-definitions\";\nimport { types as t, type NodePath } from \"@babel/core\";\n\nexport default function canSkipPolyfill(\n desc: CoreJSPolyfillDescriptor,\n path: NodePath,\n) {\n const { node, parent } = path;\n switch (desc.name) {\n case \"es.string.split\": {\n if (!t.isCallExpression(parent, { callee: node })) return false;\n if (parent.arguments.length < 1) return true;\n const splitter = parent.arguments[0];\n return t.isStringLiteral(splitter) || t.isTemplateLiteral(splitter);\n }\n }\n}\n","import { types as t, type NodePath } from \"@babel/core\";\nimport corejsEntries from \"../core-js-compat/entries.js\";\n\nexport const BABEL_RUNTIME = \"@babel/runtime-corejs3\";\n\nexport function callMethod(\n path: any,\n id: t.Identifier,\n optionalCall?: boolean,\n wrapCallee?: (callee: t.Expression) => t.Expression,\n) {\n const [context1, context2] = maybeMemoizeContext(path.node, path.scope);\n\n let callee: t.Expression = t.callExpression(id, [context1]);\n if (wrapCallee) callee = wrapCallee(callee);\n\n const call = t.identifier(\"call\");\n\n path.replaceWith(\n optionalCall\n ? t.optionalMemberExpression(callee, call, false, true)\n : t.memberExpression(callee, call),\n );\n\n path.parentPath.unshiftContainer(\"arguments\", context2);\n}\n\nexport function maybeMemoizeContext(\n node: t.MemberExpression | t.OptionalMemberExpression,\n scope: NodePath[\"scope\"],\n) {\n const { object } = node;\n\n let context1, context2;\n if (t.isIdentifier(object)) {\n context2 = object;\n context1 = t.cloneNode(object);\n } else {\n context2 = scope.generateDeclaredUidIdentifier(\"context\");\n context1 = t.assignmentExpression(\"=\", t.cloneNode(context2), object);\n }\n\n return [context1, context2];\n}\n\nexport function extractOptionalCheck(\n scope: NodePath[\"scope\"],\n node: t.OptionalMemberExpression,\n) {\n let optionalNode = node;\n while (\n !optionalNode.optional &&\n t.isOptionalMemberExpression(optionalNode.object)\n ) {\n optionalNode = optionalNode.object;\n }\n optionalNode.optional = false;\n\n const ctx = scope.generateDeclaredUidIdentifier(\"context\");\n const assign = t.assignmentExpression(\"=\", ctx, optionalNode.object);\n optionalNode.object = t.cloneNode(ctx);\n\n return ifNotNullish =>\n t.conditionalExpression(\n t.binaryExpression(\"==\", assign, t.nullLiteral()),\n t.unaryExpression(\"void\", t.numericLiteral(0)),\n ifNotNullish,\n );\n}\n\nexport function isCoreJSSource(source: string) {\n if (typeof source === \"string\") {\n source = source\n .replace(/\\\\/g, \"/\")\n .replace(/(\\/(index)?)?(\\.js)?$/i, \"\")\n .toLowerCase();\n }\n\n return (\n Object.prototype.hasOwnProperty.call(corejsEntries, source) &&\n corejsEntries[source]\n );\n}\n\nexport function coreJSModule(name: string) {\n return `core-js/modules/${name}.js`;\n}\n\nexport function coreJSPureHelper(\n name: string,\n useBabelRuntime: boolean,\n ext: string,\n) {\n return useBabelRuntime\n ? `${BABEL_RUNTIME}/core-js/${name}${ext}`\n : `core-js-pure/features/${name}.js`;\n}\n","import corejs3Polyfills from \"../core-js-compat/data.js\";\nimport corejs3ShippedProposalsList from \"./shipped-proposals\";\nimport getModulesListForTargetVersion from \"../core-js-compat/get-modules-list-for-target-version.js\";\nimport {\n BuiltIns,\n CommonIterators,\n PromiseDependencies,\n PromiseDependenciesWithIterators,\n StaticProperties,\n InstanceProperties,\n DecoratorMetadataDependencies,\n type CoreJSPolyfillDescriptor,\n} from \"./built-in-definitions\";\nimport * as BabelRuntimePaths from \"./babel-runtime-corejs3-paths\";\nimport canSkipPolyfill from \"./usage-filters\";\n\nimport type { NodePath } from \"@babel/traverse\";\nimport { types as t, template } from \"@babel/core\";\nimport {\n callMethod,\n coreJSModule,\n isCoreJSSource,\n coreJSPureHelper,\n BABEL_RUNTIME,\n extractOptionalCheck,\n maybeMemoizeContext,\n} from \"./utils\";\n\nimport defineProvider from \"@babel/helper-define-polyfill-provider\";\n\nconst presetEnvCompat = \"#__secret_key__@babel/preset-env__compatibility\";\nconst runtimeCompat = \"#__secret_key__@babel/runtime__compatibility\";\n\ntype Options = {\n version?: number | string;\n proposals?: boolean;\n shippedProposals?: boolean;\n [presetEnvCompat]?: { noRuntimeName: boolean };\n [runtimeCompat]: {\n useBabelRuntime: boolean;\n ext: string;\n };\n};\n\nconst uniqueObjects = [\n \"array\",\n \"string\",\n\n \"iterator\",\n \"async-iterator\",\n \"dom-collections\",\n].map(v => new RegExp(`[a-z]*\\\\.${v}\\\\..*`));\n\nconst esnextFallback = (\n name: string,\n cb: (name: string) => boolean,\n): boolean => {\n if (cb(name)) return true;\n if (!name.startsWith(\"es.\")) return false;\n const fallback = `esnext.${name.slice(3)}`;\n if (!corejs3Polyfills[fallback]) return false;\n return cb(fallback);\n};\n\nexport default defineProvider(function (\n { getUtils, method, shouldInjectPolyfill, createMetaResolver, debug, babel },\n {\n version = 3,\n proposals,\n shippedProposals,\n [presetEnvCompat]: { noRuntimeName = false } = {},\n [runtimeCompat]: { useBabelRuntime = false, ext = \".js\" } = {},\n },\n) {\n const isWebpack = babel.caller(caller => caller?.name === \"babel-loader\");\n\n const resolve = createMetaResolver({\n global: BuiltIns,\n static: StaticProperties,\n instance: InstanceProperties,\n });\n\n const available = new Set(getModulesListForTargetVersion(version));\n\n function getCoreJSPureBase(useProposalBase) {\n return useBabelRuntime\n ? useProposalBase\n ? `${BABEL_RUNTIME}/core-js`\n : `${BABEL_RUNTIME}/core-js-stable`\n : useProposalBase\n ? \"core-js-pure/features\"\n : \"core-js-pure/stable\";\n }\n\n function maybeInjectGlobalImpl(name: string, utils) {\n if (shouldInjectPolyfill(name)) {\n debug(name);\n utils.injectGlobalImport(coreJSModule(name), name);\n return true;\n }\n return false;\n }\n\n function maybeInjectGlobal(names: string[], utils, fallback = true) {\n for (const name of names) {\n if (fallback) {\n esnextFallback(name, name => maybeInjectGlobalImpl(name, utils));\n } else {\n maybeInjectGlobalImpl(name, utils);\n }\n }\n }\n\n function maybeInjectPure(\n desc: CoreJSPolyfillDescriptor,\n hint: string,\n utils: ReturnType,\n object?: string,\n ) {\n if (\n desc.pure &&\n !(object && desc.exclude && desc.exclude.includes(object)) &&\n esnextFallback(desc.name, shouldInjectPolyfill)\n ) {\n const { name } = desc;\n let useProposalBase = false;\n if (proposals || (shippedProposals && name.startsWith(\"esnext.\"))) {\n useProposalBase = true;\n } else if (name.startsWith(\"es.\") && !available.has(name)) {\n useProposalBase = true;\n }\n if (\n useBabelRuntime &&\n !(\n useProposalBase\n ? BabelRuntimePaths.proposals\n : BabelRuntimePaths.stable\n ).has(desc.pure)\n ) {\n return;\n }\n const coreJSPureBase = getCoreJSPureBase(useProposalBase);\n return utils.injectDefaultImport(\n `${coreJSPureBase}/${desc.pure}${ext}`,\n hint,\n );\n }\n }\n\n function isFeatureStable(name) {\n if (name.startsWith(\"esnext.\")) {\n const esName = `es.${name.slice(7)}`;\n // If its imaginative esName is not in latest compat data, it means\n // the proposal is not stage 4\n return esName in corejs3Polyfills;\n }\n return true;\n }\n\n return {\n name: \"corejs3\",\n\n runtimeName: noRuntimeName ? null : BABEL_RUNTIME,\n\n polyfills: corejs3Polyfills,\n\n filterPolyfills(name) {\n if (!available.has(name)) return false;\n if (proposals || method === \"entry-global\") return true;\n if (shippedProposals && corejs3ShippedProposalsList.has(name)) {\n return true;\n }\n return isFeatureStable(name);\n },\n\n entryGlobal(meta, utils, path) {\n if (meta.kind !== \"import\") return;\n\n const modules = isCoreJSSource(meta.source);\n if (!modules) return;\n\n if (\n modules.length === 1 &&\n meta.source === coreJSModule(modules[0]) &&\n shouldInjectPolyfill(modules[0])\n ) {\n // Avoid infinite loop: do not replace imports with a new copy of\n // themselves.\n debug(null);\n return;\n }\n\n const modulesSet = new Set(modules);\n const filteredModules = modules.filter(module => {\n if (!module.startsWith(\"esnext.\")) return true;\n const stable = module.replace(\"esnext.\", \"es.\");\n if (modulesSet.has(stable) && shouldInjectPolyfill(stable)) {\n return false;\n }\n return true;\n });\n\n maybeInjectGlobal(filteredModules, utils, false);\n path.remove();\n },\n\n usageGlobal(meta, utils, path) {\n const resolved = resolve(meta);\n if (!resolved) return;\n\n if (canSkipPolyfill(resolved.desc, path)) return;\n\n let deps = resolved.desc.global;\n\n if (\n resolved.kind !== \"global\" &&\n \"object\" in meta &&\n meta.object &&\n meta.placement === \"prototype\"\n ) {\n const low = meta.object.toLowerCase();\n deps = deps.filter(m =>\n uniqueObjects.some(v => v.test(m)) ? m.includes(low) : true,\n );\n }\n\n maybeInjectGlobal(deps, utils);\n\n return true;\n },\n\n usagePure(meta, utils, path) {\n if (meta.kind === \"in\") {\n if (meta.key === \"Symbol.iterator\") {\n path.replaceWith(\n t.callExpression(\n utils.injectDefaultImport(\n coreJSPureHelper(\"is-iterable\", useBabelRuntime, ext),\n \"isIterable\",\n ),\n [(path.node as t.BinaryExpression).right], // meta.kind === \"in\" narrows this\n ),\n );\n }\n return;\n }\n\n if (path.parentPath.isUnaryExpression({ operator: \"delete\" })) return;\n\n if (meta.kind === \"property\") {\n // We can't compile destructuring and updateExpression.\n if (!path.isMemberExpression() && !path.isOptionalMemberExpression()) {\n return;\n }\n if (!path.isReferenced()) return;\n if (path.parentPath.isUpdateExpression()) return;\n if (t.isSuper(path.node.object)) {\n return;\n }\n\n if (meta.key === \"Symbol.iterator\") {\n if (!shouldInjectPolyfill(\"es.symbol.iterator\")) return;\n\n const { parent, node } = path;\n if (t.isCallExpression(parent, { callee: node })) {\n if (parent.arguments.length === 0) {\n path.parentPath.replaceWith(\n t.callExpression(\n utils.injectDefaultImport(\n coreJSPureHelper(\"get-iterator\", useBabelRuntime, ext),\n \"getIterator\",\n ),\n [node.object],\n ),\n );\n path.skip();\n } else {\n callMethod(\n path,\n utils.injectDefaultImport(\n coreJSPureHelper(\"get-iterator-method\", useBabelRuntime, ext),\n \"getIteratorMethod\",\n ),\n );\n }\n } else {\n path.replaceWith(\n t.callExpression(\n utils.injectDefaultImport(\n coreJSPureHelper(\"get-iterator-method\", useBabelRuntime, ext),\n \"getIteratorMethod\",\n ),\n [path.node.object],\n ),\n );\n }\n\n return;\n }\n }\n\n let resolved = resolve(meta);\n if (!resolved) return;\n\n if (canSkipPolyfill(resolved.desc, path)) return;\n\n if (\n useBabelRuntime &&\n resolved.desc.pure &&\n resolved.desc.pure.slice(-6) === \"/index\"\n ) {\n // Remove /index, since it doesn't exist in @babel/runtime-corejs3s\n resolved = {\n ...resolved,\n desc: {\n ...resolved.desc,\n pure: resolved.desc.pure.slice(0, -6),\n },\n };\n }\n\n if (resolved.kind === \"global\") {\n const id = maybeInjectPure(resolved.desc, resolved.name, utils);\n if (id) path.replaceWith(id);\n } else if (resolved.kind === \"static\") {\n const id = maybeInjectPure(\n resolved.desc,\n resolved.name,\n utils,\n // @ts-expect-error\n meta.object,\n );\n if (id) {\n path.replaceWith(id);\n let { parentPath } = path;\n if (\n parentPath.isOptionalMemberExpression() ||\n parentPath.isOptionalCallExpression()\n ) {\n do {\n const parentAsNotOptional = parentPath as NodePath as NodePath<\n t.MemberExpression | t.CallExpression\n >;\n parentAsNotOptional.type = parentAsNotOptional.node.type =\n parentPath.type === \"OptionalMemberExpression\"\n ? \"MemberExpression\"\n : \"CallExpression\";\n delete parentAsNotOptional.node.optional;\n\n ({ parentPath } = parentPath);\n } while (\n (parentPath.isOptionalMemberExpression() ||\n parentPath.isOptionalCallExpression()) &&\n !parentPath.node.optional\n );\n }\n }\n } else if (resolved.kind === \"instance\") {\n const id = maybeInjectPure(\n resolved.desc,\n `${resolved.name}InstanceProperty`,\n utils,\n // @ts-expect-error\n meta.object,\n );\n if (!id) return;\n\n const { node, parent } = path as NodePath<\n t.MemberExpression | t.OptionalMemberExpression\n >;\n\n if (t.isOptionalCallExpression(parent) && parent.callee === node) {\n const wasOptional = parent.optional;\n parent.optional = !wasOptional;\n\n if (!wasOptional) {\n const check = extractOptionalCheck(\n path.scope,\n node as t.OptionalMemberExpression,\n );\n const [thisArg, thisArg2] = maybeMemoizeContext(node, path.scope);\n\n path.replaceWith(\n check(\n template.expression.ast`\n Function.call.bind(${id}(${thisArg}), ${thisArg2})\n `,\n ),\n );\n } else if (t.isOptionalMemberExpression(node)) {\n const check = extractOptionalCheck(path.scope, node);\n callMethod(path, id, true, check);\n } else {\n callMethod(path, id, true);\n }\n } else if (t.isCallExpression(parent) && parent.callee === node) {\n callMethod(path, id, false);\n } else if (t.isOptionalMemberExpression(node)) {\n const check = extractOptionalCheck(path.scope, node);\n path.replaceWith(check(t.callExpression(id, [node.object])));\n if (t.isOptionalMemberExpression(parent)) parent.optional = true;\n } else {\n path.replaceWith(t.callExpression(id, [node.object]));\n }\n }\n },\n\n visitor: method === \"usage-global\" && {\n // import(\"foo\")\n CallExpression(path: NodePath) {\n if (path.get(\"callee\").isImport()) {\n const utils = getUtils(path);\n\n if (isWebpack) {\n // Webpack uses Promise.all to handle dynamic import.\n maybeInjectGlobal(PromiseDependenciesWithIterators, utils);\n } else {\n maybeInjectGlobal(PromiseDependencies, utils);\n }\n }\n },\n\n // (async function () { }).finally(...)\n Function(path: NodePath) {\n if (path.node.async) {\n maybeInjectGlobal(PromiseDependencies, getUtils(path));\n }\n },\n\n // for-of, [a, b] = c\n \"ForOfStatement|ArrayPattern\"(\n path: NodePath,\n ) {\n maybeInjectGlobal(CommonIterators, getUtils(path));\n },\n\n // [...spread]\n SpreadElement(path: NodePath) {\n if (!path.parentPath.isObjectExpression()) {\n maybeInjectGlobal(CommonIterators, getUtils(path));\n }\n },\n\n // yield*\n YieldExpression(path: NodePath) {\n if (path.node.delegate) {\n maybeInjectGlobal(CommonIterators, getUtils(path));\n }\n },\n\n // Decorators metadata\n Class(path: NodePath) {\n const hasDecorators =\n path.node.decorators?.length ||\n path.node.body.body.some(\n el => (el as t.ClassMethod).decorators?.length,\n );\n if (hasDecorators) {\n maybeInjectGlobal(DecoratorMetadataDependencies, getUtils(path));\n }\n },\n },\n };\n});\n"],"names":["Set","polyfillsOrder","Object","keys","corejs3Polyfills","forEach","name","index","define","pure","global","exclude","sort","a","b","typed","modules","TypedArrayDependencies","ArrayNatureIterators","CommonIterators","ArrayNatureIteratorsWithTag","CommonIteratorsWithTag","ErrorDependencies","SuppressedErrorDependencies","ArrayBufferDependencies","PromiseDependencies","PromiseDependenciesWithIterators","SymbolDependencies","MapDependencies","SetDependencies","WeakMapDependencies","WeakSetDependencies","DOMExceptionDependencies","URLSearchParamsDependencies","AsyncIteratorDependencies","AsyncIteratorProblemMethods","IteratorDependencies","DecoratorMetadataDependencies","TypedArrayStaticMethods","base","from","fromAsync","of","DataViewDependencies","BuiltIns","AsyncDisposableStack","AsyncIterator","AggregateError","ArrayBuffer","DataView","Date","DOMException","DisposableStack","Error","EvalError","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Iterator","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","Map","Number","Observable","Promise","RangeError","ReferenceError","Reflect","RegExp","SuppressedError","Symbol","SyntaxError","TypeError","URIError","URL","URLSearchParams","WeakMap","WeakSet","atob","btoa","clearImmediate","compositeKey","compositeSymbol","escape","fetch","globalThis","parseFloat","parseInt","queueMicrotask","self","setImmediate","setInterval","setTimeout","structuredClone","unescape","StaticProperties","Array","isArray","isTemplateObject","isView","BigInt","range","now","isError","Function","isCallable","isConstructor","concat","zip","zipKeyed","JSON","isRawJSON","parse","rawJSON","stringify","Math","DEG_PER_RAD","RAD_PER_DEG","acosh","asinh","atanh","cbrt","clamp","clz32","cosh","degrees","expm1","fround","f16round","fscale","hypot","iaddh","imul","imulh","isubh","log10","log1p","log2","radians","scale","seededPRNG","sign","signbit","sinh","sumPrecise","tanh","trunc","umulh","groupBy","keyBy","EPSILON","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","fromString","isFinite","isInteger","isNaN","isSafeInteger","assign","create","defineProperties","defineProperty","entries","freeze","fromEntries","getOwnPropertyDescriptor","getOwnPropertyDescriptors","getOwnPropertyNames","getOwnPropertySymbols","getPrototypeOf","hasOwn","is","isExtensible","isFrozen","isSealed","preventExtensions","seal","setPrototypeOf","values","all","allSettled","any","race","try","withResolvers","apply","construct","defineMetadata","deleteMetadata","deleteProperty","get","getMetadata","getMetadataKeys","getOwnMetadata","getOwnMetadataKeys","has","hasMetadata","hasOwnMetadata","metadata","ownKeys","set","String","cooked","dedent","fromCodePoint","raw","asyncDispose","asyncIterator","customMatcher","dispose","for","hasInstance","isConcatSpreadable","isRegistered","isRegisteredSymbol","isWellKnown","isWellKnownSymbol","iterator","keyFor","match","matcher","matchAll","metadataKey","observable","patternMatch","replace","search","species","split","toPrimitive","toStringTag","unscopables","canParse","fromBase64","fromHex","WebAssembly","CompileError","LinkError","RuntimeError","ERROR_SUBCLASS","InstanceProperties","asIndexedPairs","at","anchor","big","bind","blink","bold","chunks","codePointAt","codePoints","undefined","copyWithin","demethodize","description","dotAll","drop","endsWith","every","exec","fill","filter","filterReject","finally","find","findIndex","findLast","findLastIndex","fixed","flags","flatMap","flat","getFloat16","getUint8Clamped","getYear","group","groupByToMap","groupToMap","fontcolor","fontsize","includes","indexed","indexOf","isWellFormed","italics","join","lastIndex","lastIndexOf","lastItem","link","map","padEnd","padStart","push","reduce","reduceRight","repeat","replaceAll","reverse","setFloat16","setUint8Clamped","setYear","slice","sliding","small","some","splice","startsWith","sticky","strike","sub","substr","sup","take","test","toArray","toAsync","toExponential","toFixed","toGMTString","toISOString","toJSON","toPrecision","toReversed","toSorted","toSpliced","toString","toWellFormed","trim","trimEnd","trimLeft","trimRight","trimStart","uniqueBy","unshift","unThis","windows","with","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","stable","proposals","types","t","_babel","default","canSkipPolyfill","desc","path","node","parent","isCallExpression","callee","arguments","length","splitter","isStringLiteral","isTemplateLiteral","BABEL_RUNTIME","callMethod","id","optionalCall","wrapCallee","context1","context2","maybeMemoizeContext","scope","callExpression","call","identifier","replaceWith","optionalMemberExpression","memberExpression","parentPath","unshiftContainer","object","isIdentifier","cloneNode","generateDeclaredUidIdentifier","assignmentExpression","extractOptionalCheck","optionalNode","optional","isOptionalMemberExpression","ctx","ifNotNullish","conditionalExpression","binaryExpression","nullLiteral","unaryExpression","numericLiteral","isCoreJSSource","source","toLowerCase","prototype","hasOwnProperty","corejsEntries","coreJSModule","coreJSPureHelper","useBabelRuntime","ext","template","presetEnvCompat","runtimeCompat","uniqueObjects","v","esnextFallback","cb","fallback","defineProvider","getUtils","method","shouldInjectPolyfill","createMetaResolver","debug","babel","version","shippedProposals","noRuntimeName","isWebpack","caller","resolve","static","instance","available","getModulesListForTargetVersion","getCoreJSPureBase","useProposalBase","maybeInjectGlobalImpl","utils","injectGlobalImport","maybeInjectGlobal","names","maybeInjectPure","hint","BabelRuntimePaths","coreJSPureBase","injectDefaultImport","isFeatureStable","esName","runtimeName","polyfills","filterPolyfills","corejs3ShippedProposalsList","entryGlobal","meta","kind","modulesSet","filteredModules","module","remove","usageGlobal","resolved","deps","placement","low","m","usagePure","key","right","isUnaryExpression","operator","isMemberExpression","isReferenced","isUpdateExpression","isSuper","skip","isOptionalCallExpression","parentAsNotOptional","type","wasOptional","check","thisArg","thisArg2","expression","ast","visitor","CallExpression","isImport","async","ForOfStatement|ArrayPattern","SpreadElement","isObjectExpression","YieldExpression","delegate","Class","_path$node$decorators","hasDecorators","decorators","body","el","_decorators"],"mappings":";;;;;;AAAA;;AAEA,kCAAe,IAAIA,GAAG,CAAS,CAC7B,oBAAoB,EACpB,2BAA2B,EAC3B,qBAAqB,EACrB,2BAA2B,EAC3B,wBAAwB,CACzB,CAAC;;ACIF,MAAMC,cAAc,GAAG,EAAE,CAAA;AACzBC,MAAM,CAACC,IAAI,CAACC,gBAAgB,CAAC,CAACC,OAAO,CAAC,CAACC,IAAI,EAAEC,KAAK,KAAK;AACrDN,EAAAA,cAAc,CAACK,IAAI,CAAC,GAAGC,KAAK,CAAA;AAC9B,CAAC,CAAC,CAAA;AAEF,MAAMC,MAAM,GAAGA,CACbC,IAAI,EACJC,MAAM,EACNJ,IAAI,GAAGI,MAAM,CAAC,CAAC,CAAC,EAChBC,OAAQ,KACqB;EAC7B,OAAO;IACLL,IAAI;IACJG,IAAI;AACJC,IAAAA,MAAM,EAAEA,MAAM,CAACE,IAAI,CAAC,CAACC,CAAC,EAAEC,CAAC,KAAKb,cAAc,CAACY,CAAC,CAAC,GAAGZ,cAAc,CAACa,CAAC,CAAC,CAAC;AACpEH,IAAAA,OAAAA;GACD,CAAA;AACH,CAAC,CAAA;AAED,MAAMI,KAAK,GAAGA,CAAC,GAAGC,OAAO,KACvBR,MAAM,CAAC,IAAI,EAAE,CAAC,GAAGQ,OAAO,EAAE,GAAGC,sBAAsB,CAAC,CAAC,CAAA;AAEvD,MAAMC,oBAAoB,GAAG,CAC3B,mBAAmB,EACnB,8BAA8B,CAC/B,CAAA;AAEM,MAAMC,eAAe,GAAG,CAAC,oBAAoB,EAAE,GAAGD,oBAAoB,CAAC,CAAA;AAE9E,MAAME,2BAA2B,GAAG,CAClC,qBAAqB,EACrB,GAAGF,oBAAoB,CACxB,CAAA;AAED,MAAMG,sBAAsB,GAAG,CAAC,qBAAqB,EAAE,GAAGF,eAAe,CAAC,CAAA;AAE1E,MAAMG,iBAAiB,GAAG,CAAC,gBAAgB,EAAE,oBAAoB,CAAC,CAAA;AAElE,MAAMC,2BAA2B,GAAG,CAClC,iCAAiC,EACjC,GAAGD,iBAAiB,CACrB,CAAA;AAED,MAAME,uBAAuB,GAAG,CAC9B,6BAA6B,EAC7B,uBAAuB,EACvB,cAAc,EACd,0BAA0B,EAC1B,0BAA0B,EAC1B,0CAA0C,EAC1C,qBAAqB,CACtB,CAAA;AAED,MAAMP,sBAAsB,GAAG,CAC7B,mBAAmB,EACnB,4BAA4B,EAC5B,sBAAsB,EACtB,qBAAqB,EACrB,uBAAuB,EACvB,qBAAqB,EACrB,2BAA2B,EAC3B,0BAA0B,EAC1B,gCAAgC,EAChC,yBAAyB,EACzB,yBAAyB,EACzB,yBAAyB,EACzB,yBAAyB,EACzB,qBAAqB,EACrB,8BAA8B,EAC9B,oBAAoB,EACpB,uBAAuB,EACvB,6BAA6B,EAC7B,wBAAwB,EACxB,oBAAoB,EACpB,sBAAsB,EACtB,qBAAqB,EACrB,qBAAqB,EACrB,yBAAyB,EACzB,iCAAiC,EACjC,4BAA4B,EAC5B,0BAA0B,EAC1B,0BAA0B,EAC1B,qBAAqB,EACrB,qBAAqB,EACrB,mBAAmB,EACnB,kCAAkC,EAClC,6BAA6B,EAC7B,+BAA+B,EAC/B,8BAA8B,EAC9B,GAAGO,uBAAuB,CAC3B,CAAA;AAEM,MAAMC,mBAAmB,GAAG,CAAC,YAAY,EAAE,qBAAqB,CAAC,CAAA;AAEjE,MAAMC,gCAAgC,GAAG,CAC9C,GAAGD,mBAAmB,EACtB,GAAGN,eAAe,CACnB,CAAA;AAED,MAAMQ,kBAAkB,GAAG,CACzB,WAAW,EACX,uBAAuB,EACvB,qBAAqB,CACtB,CAAA;AAED,MAAMC,eAAe,GAAG,CACtB,QAAQ,EACR,sBAAsB,EACtB,+BAA+B,EAC/B,uBAAuB,EACvB,oBAAoB,EACpB,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,EACjB,qBAAqB,EACrB,qBAAqB,EACrB,mBAAmB,EACnB,qBAAqB,EACrB,uBAAuB,EACvB,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,EACjB,mBAAmB,EACnB,GAAGP,sBAAsB,CAC1B,CAAA;AAED,MAAMQ,eAAe,GAAG,CACtB,QAAQ,EACR,sBAAsB,EACtB,wBAAwB,EACxB,4BAA4B,EAC5B,wBAAwB,EACxB,0BAA0B,EAC1B,gCAAgC,EAChC,iBAAiB,EACjB,oBAAoB,EACpB,uBAAuB,EACvB,uBAAuB,EACvB,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,EACjB,yBAAyB,EACzB,6BAA6B,EAC7B,yBAAyB,EACzB,2BAA2B,EAC3B,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACnB,iBAAiB,EACjB,iCAAiC,EACjC,kBAAkB,EAClB,GAAGR,sBAAsB,CAC1B,CAAA;AAED,MAAMS,mBAAmB,GAAG,CAC1B,aAAa,EACb,2BAA2B,EAC3B,oCAAoC,EACpC,4BAA4B,EAC5B,yBAAyB,EACzB,GAAGT,sBAAsB,CAC1B,CAAA;AAED,MAAMU,mBAAmB,GAAG,CAC1B,aAAa,EACb,yBAAyB,EACzB,4BAA4B,EAC5B,GAAGV,sBAAsB,CAC1B,CAAA;AAED,MAAMW,wBAAwB,GAAG,CAC/B,+BAA+B,EAC/B,yBAAyB,EACzB,iCAAiC,EACjC,oBAAoB,CACrB,CAAA;AAED,MAAMC,2BAA2B,GAAG,CAClC,uBAAuB,EACvB,8BAA8B,EAC9B,2BAA2B,EAC3B,4BAA4B,EAC5B,GAAGZ,sBAAsB,CAC1B,CAAA;AAED,MAAMa,yBAAyB,GAAG,CAChC,mCAAmC,EACnC,GAAGT,mBAAmB,CACvB,CAAA;AAED,MAAMU,2BAA2B,GAAG,CAClC,6BAA6B,EAC7B,8BAA8B,EAC9B,4BAA4B,EAC5B,gCAAgC,EAChC,gCAAgC,EAChC,2BAA2B,EAC3B,8BAA8B,EAC9B,4BAA4B,CAC7B,CAAA;AAED,MAAMC,oBAAoB,GAAG,CAAC,yBAAyB,EAAE,qBAAqB,CAAC,CAAA;AAExE,MAAMC,6BAA6B,GAAG,CAC3C,wBAAwB,EACxB,0BAA0B,CAC3B,CAAA;AAED,MAAMC,uBAAuB,GAAIC,IAAY,KAAM;AACjDC,EAAAA,IAAI,EAAEhC,MAAM,CAAC,IAAI,EAAE,CAAC,qBAAqB,EAAE+B,IAAI,EAAE,GAAGtB,sBAAsB,CAAC,CAAC;AAC5EwB,EAAAA,SAAS,EAAEjC,MAAM,CAAC,IAAI,EAAE,CACtB,+BAA+B,EAC/B+B,IAAI,EACJ,GAAGb,gCAAgC,EACnC,GAAGT,sBAAsB,CAC1B,CAAC;AACFyB,EAAAA,EAAE,EAAElC,MAAM,CAAC,IAAI,EAAE,CAAC,mBAAmB,EAAE+B,IAAI,EAAE,GAAGtB,sBAAsB,CAAC,CAAA;AACzE,CAAC,CAAC,CAAA;AAEF,MAAM0B,oBAAoB,GAAG,CAAC,cAAc,EAAE,GAAGnB,uBAAuB,CAAC,CAAA;AAElE,MAAMoB,QAA6C,GAAG;EAC3DC,oBAAoB,EAAErC,MAAM,CAAC,8BAA8B,EAAE,CAC3D,uCAAuC,EACvC,qBAAqB,EACrB,iCAAiC,EACjC,qBAAqB,EACrB,GAAGiB,mBAAmB,EACtB,GAAGF,2BAA2B,CAC/B,CAAC;AACFuB,EAAAA,aAAa,EAAEtC,MAAM,CAAC,sBAAsB,EAAE0B,yBAAyB,CAAC;AACxEa,EAAAA,cAAc,EAAEvC,MAAM,CAAC,iBAAiB,EAAE,CACxC,oBAAoB,EACpB,GAAGc,iBAAiB,EACpB,GAAGD,sBAAsB,EACzB,0BAA0B,CAC3B,CAAC;AACF2B,EAAAA,WAAW,EAAExC,MAAM,CAAC,IAAI,EAAEgB,uBAAuB,CAAC;AAClDyB,EAAAA,QAAQ,EAAEzC,MAAM,CAAC,IAAI,EAAEmC,oBAAoB,CAAC;EAC5CO,IAAI,EAAE1C,MAAM,CAAC,IAAI,EAAE,CAAC,mBAAmB,CAAC,CAAC;AACzC2C,EAAAA,YAAY,EAAE3C,MAAM,CAAC,qBAAqB,EAAEwB,wBAAwB,CAAC;AACrEoB,EAAAA,eAAe,EAAE5C,MAAM,CAAC,wBAAwB,EAAE,CAChD,iCAAiC,EACjC,qBAAqB,EACrB,qBAAqB,EACrB,GAAGe,2BAA2B,CAC/B,CAAC;AACF8B,EAAAA,KAAK,EAAE7C,MAAM,CAAC,IAAI,EAAEc,iBAAiB,CAAC;AACtCgC,EAAAA,SAAS,EAAE9C,MAAM,CAAC,IAAI,EAAEc,iBAAiB,CAAC;AAC1CiC,EAAAA,YAAY,EAAExC,KAAK,CAAC,8BAA8B,CAAC;AACnDyC,EAAAA,YAAY,EAAEzC,KAAK,CAAC,8BAA8B,CAAC;AACnD0C,EAAAA,SAAS,EAAE1C,KAAK,CAAC,2BAA2B,CAAC;AAC7C2C,EAAAA,UAAU,EAAE3C,KAAK,CAAC,4BAA4B,CAAC;AAC/C4C,EAAAA,UAAU,EAAE5C,KAAK,CAAC,4BAA4B,CAAC;AAC/C6C,EAAAA,QAAQ,EAAEpD,MAAM,CAAC,gBAAgB,EAAE4B,oBAAoB,CAAC;AACxDyB,EAAAA,UAAU,EAAE9C,KAAK,CACf,4BAA4B,EAC5B,gCAAgC,EAChC,6BAA6B,EAC7B,0BAA0B,EAC1B,uBACF,CAAC;AACD+C,EAAAA,iBAAiB,EAAE/C,KAAK,CAAC,oCAAoC,CAAC;AAC9DgD,EAAAA,WAAW,EAAEhD,KAAK,CAAC,6BAA6B,CAAC;AACjDiD,EAAAA,WAAW,EAAEjD,KAAK,CAAC,6BAA6B,CAAC;AACjDkD,EAAAA,GAAG,EAAEzD,MAAM,CAAC,WAAW,EAAEoB,eAAe,CAAC;EACzCsC,MAAM,EAAE1D,MAAM,CAAC,IAAI,EAAE,CAAC,uBAAuB,CAAC,CAAC;AAC/C2D,EAAAA,UAAU,EAAE3D,MAAM,CAAC,kBAAkB,EAAE,CACrC,mBAAmB,EACnB,0BAA0B,EAC1B,qBAAqB,EACrB,GAAGa,sBAAsB,CAC1B,CAAC;AACF+C,EAAAA,OAAO,EAAE5D,MAAM,CAAC,eAAe,EAAEiB,mBAAmB,CAAC;AACrD4C,EAAAA,UAAU,EAAE7D,MAAM,CAAC,IAAI,EAAEc,iBAAiB,CAAC;AAC3CgD,EAAAA,cAAc,EAAE9D,MAAM,CAAC,IAAI,EAAEc,iBAAiB,CAAC;EAC/CiD,OAAO,EAAE/D,MAAM,CAAC,IAAI,EAAE,CAAC,0BAA0B,EAAE,qBAAqB,CAAC,CAAC;AAC1EgE,EAAAA,MAAM,EAAEhE,MAAM,CAAC,IAAI,EAAE,CACnB,uBAAuB,EACvB,mBAAmB,EACnB,gBAAgB,EAChB,kBAAkB,EAClB,qBAAqB,CACtB,CAAC;AACFR,EAAAA,GAAG,EAAEQ,MAAM,CAAC,WAAW,EAAEqB,eAAe,CAAC;AACzC4C,EAAAA,eAAe,EAAEjE,MAAM,CAAC,kBAAkB,EAAEe,2BAA2B,CAAC;AACxEmD,EAAAA,MAAM,EAAElE,MAAM,CAAC,cAAc,EAAEmB,kBAAkB,CAAC;AAClDgD,EAAAA,WAAW,EAAEnE,MAAM,CAAC,IAAI,EAAEc,iBAAiB,CAAC;AAC5CsD,EAAAA,SAAS,EAAEpE,MAAM,CAAC,IAAI,EAAEc,iBAAiB,CAAC;AAC1CuD,EAAAA,QAAQ,EAAErE,MAAM,CAAC,IAAI,EAAEc,iBAAiB,CAAC;AACzCwD,EAAAA,GAAG,EAAEtE,MAAM,CAAC,WAAW,EAAE,CACvB,SAAS,EACT,iBAAiB,EACjB,GAAGyB,2BAA2B,CAC/B,CAAC;AACF8C,EAAAA,eAAe,EAAEvE,MAAM,CACrB,yBAAyB,EACzByB,2BACF,CAAC;AACD+C,EAAAA,OAAO,EAAExE,MAAM,CAAC,gBAAgB,EAAEsB,mBAAmB,CAAC;AACtDmD,EAAAA,OAAO,EAAEzE,MAAM,CAAC,gBAAgB,EAAEuB,mBAAmB,CAAC;EAEtDmD,IAAI,EAAE1E,MAAM,CAAC,MAAM,EAAE,CAAC,UAAU,EAAE,GAAGwB,wBAAwB,CAAC,CAAC;EAC/DmD,IAAI,EAAE3E,MAAM,CAAC,MAAM,EAAE,CAAC,UAAU,EAAE,GAAGwB,wBAAwB,CAAC,CAAC;EAC/DoD,cAAc,EAAE5E,MAAM,CAAC,iBAAiB,EAAE,CAAC,eAAe,CAAC,CAAC;EAC5D6E,YAAY,EAAE7E,MAAM,CAAC,eAAe,EAAE,CAAC,sBAAsB,CAAC,CAAC;EAC/D8E,eAAe,EAAE9E,MAAM,CAAC,kBAAkB,EAAE,CAAC,yBAAyB,CAAC,CAAC;EACxE+E,MAAM,EAAE/E,MAAM,CAAC,QAAQ,EAAE,CAAC,WAAW,CAAC,CAAC;AACvCgF,EAAAA,KAAK,EAAEhF,MAAM,CAAC,IAAI,EAAEiB,mBAAmB,CAAC;EACxCgE,UAAU,EAAEjF,MAAM,CAAC,aAAa,EAAE,CAAC,gBAAgB,CAAC,CAAC;EACrDkF,UAAU,EAAElF,MAAM,CAAC,aAAa,EAAE,CAAC,gBAAgB,CAAC,CAAC;EACrDmF,QAAQ,EAAEnF,MAAM,CAAC,WAAW,EAAE,CAAC,cAAc,CAAC,CAAC;EAC/CoF,cAAc,EAAEpF,MAAM,CAAC,iBAAiB,EAAE,CAAC,qBAAqB,CAAC,CAAC;EAClEqF,IAAI,EAAErF,MAAM,CAAC,MAAM,EAAE,CAAC,UAAU,CAAC,CAAC;EAClCsF,YAAY,EAAEtF,MAAM,CAAC,eAAe,EAAE,CAAC,eAAe,CAAC,CAAC;EACxDuF,WAAW,EAAEvF,MAAM,CAAC,cAAc,EAAE,CAAC,YAAY,CAAC,CAAC;EACnDwF,UAAU,EAAExF,MAAM,CAAC,aAAa,EAAE,CAAC,YAAY,CAAC,CAAC;EACjDyF,eAAe,EAAEzF,MAAM,CAAC,kBAAkB,EAAE,CAC1C,sBAAsB,EACtB,GAAGwB,wBAAwB,EAC3B,mBAAmB,EACnB,gBAAgB,EAChB,qBAAqB,EACrB,QAAQ,EACR,QAAQ,CACT,CAAC;AACFkE,EAAAA,QAAQ,EAAE1F,MAAM,CAAC,UAAU,EAAE,CAAC,aAAa,CAAC,CAAA;AAC9C,CAAC,CAAA;AAEM,MAAM2F,gBAAsD,GAAG;AACpErD,EAAAA,aAAa,EAAE;AACbN,IAAAA,IAAI,EAAEhC,MAAM,CAAC,qBAAqB,EAAE,CAClC,4BAA4B,EAC5B,GAAG0B,yBAAyB,EAC5B,GAAGC,2BAA2B,EAC9B,GAAGhB,eAAe,CACnB,CAAA;GACF;AACDiF,EAAAA,KAAK,EAAE;IACL5D,IAAI,EAAEhC,MAAM,CAAC,YAAY,EAAE,CAAC,eAAe,EAAE,oBAAoB,CAAC,CAAC;IACnEiC,SAAS,EAAEjC,MAAM,CAAC,kBAAkB,EAAE,CACpC,qBAAqB,EACrB,GAAGkB,gCAAgC,CACpC,CAAC;IACF2E,OAAO,EAAE7F,MAAM,CAAC,gBAAgB,EAAE,CAAC,mBAAmB,CAAC,CAAC;IACxD8F,gBAAgB,EAAE9F,MAAM,CAAC,0BAA0B,EAAE,CACnD,iCAAiC,CAClC,CAAC;AACFkC,IAAAA,EAAE,EAAElC,MAAM,CAAC,UAAU,EAAE,CAAC,aAAa,CAAC,CAAA;GACvC;AAEDwC,EAAAA,WAAW,EAAE;AACXuD,IAAAA,MAAM,EAAE/F,MAAM,CAAC,IAAI,EAAE,CAAC,yBAAyB,CAAC,CAAA;GACjD;AAEDgG,EAAAA,MAAM,EAAE;IACNC,KAAK,EAAEjG,MAAM,CAAC,cAAc,EAAE,CAC5B,qBAAqB,EACrB,qBAAqB,CACtB,CAAA;GACF;AAED0C,EAAAA,IAAI,EAAE;AACJwD,IAAAA,GAAG,EAAElG,MAAM,CAAC,UAAU,EAAE,CAAC,aAAa,CAAC,CAAA;GACxC;AAED6C,EAAAA,KAAK,EAAE;IACLsD,OAAO,EAAEnG,MAAM,CAAC,gBAAgB,EAAE,CAChC,mBAAmB,EACnB,kBAAkB,CACnB,CAAA;GACF;AAEDoG,EAAAA,QAAQ,EAAE;IACRC,UAAU,EAAErG,MAAM,CAAC,sBAAsB,EAAE,CAAC,6BAA6B,CAAC,CAAC;AAC3EsG,IAAAA,aAAa,EAAEtG,MAAM,CAAC,yBAAyB,EAAE,CAC/C,gCAAgC,CACjC,CAAA;GACF;AAEDoD,EAAAA,QAAQ,EAAE;AACRmD,IAAAA,MAAM,EAAEvG,MAAM,CAAC,iBAAiB,EAAE,CAChC,oBAAoB,EACpB,GAAG4B,oBAAoB,EACvB,GAAGjB,eAAe,CACnB,CAAC;AACFqB,IAAAA,IAAI,EAAEhC,MAAM,CAAC,eAAe,EAAE,CAC5B,kBAAkB,EAClB,GAAG4B,oBAAoB,EACvB,GAAGjB,eAAe,CACnB,CAAC;IACFsF,KAAK,EAAEjG,MAAM,CAAC,gBAAgB,EAAE,CAC9B,uBAAuB,EACvB,GAAG4B,oBAAoB,CACxB,CAAC;AACF4E,IAAAA,GAAG,EAAExG,MAAM,CAAC,cAAc,EAAE,CAC1B,qBAAqB,EACrB,GAAG4B,oBAAoB,EACvB,GAAGjB,eAAe,CACnB,CAAC;AACF8F,IAAAA,QAAQ,EAAEzG,MAAM,CAAC,oBAAoB,EAAE,CACrC,2BAA2B,EAC3B,kBAAkB,EAClB,qBAAqB,EACrB,GAAG4B,oBAAoB,EACvB,GAAGjB,eAAe,CACnB,CAAA;GACF;AAED+F,EAAAA,IAAI,EAAE;IACJC,SAAS,EAAE3G,MAAM,CAAC,kBAAkB,EAAE,CAAC,qBAAqB,CAAC,CAAC;IAC9D4G,KAAK,EAAE5G,MAAM,CAAC,YAAY,EAAE,CAAC,eAAe,EAAE,gBAAgB,CAAC,CAAC;AAChE6G,IAAAA,OAAO,EAAE7G,MAAM,CAAC,eAAe,EAAE,CAC/B,kBAAkB,EAClB,kBAAkB,EAClB,kBAAkB,CACnB,CAAC;IACF8G,SAAS,EAAE9G,MAAM,CAAC,gBAAgB,EAAE,CAClC,mBAAmB,EACnB,iBAAiB,CAClB,CAAA;GACF;AAED+G,EAAAA,IAAI,EAAE;IACJC,WAAW,EAAEhH,MAAM,CAAC,kBAAkB,EAAE,CAAC,yBAAyB,CAAC,CAAC;IACpEiH,WAAW,EAAEjH,MAAM,CAAC,kBAAkB,EAAE,CAAC,yBAAyB,CAAC,CAAC;IACpEkH,KAAK,EAAElH,MAAM,CAAC,YAAY,EAAE,CAAC,eAAe,CAAC,CAAC;IAC9CmH,KAAK,EAAEnH,MAAM,CAAC,YAAY,EAAE,CAAC,eAAe,CAAC,CAAC;IAC9CoH,KAAK,EAAEpH,MAAM,CAAC,YAAY,EAAE,CAAC,eAAe,CAAC,CAAC;IAC9CqH,IAAI,EAAErH,MAAM,CAAC,WAAW,EAAE,CAAC,cAAc,CAAC,CAAC;IAC3CsH,KAAK,EAAEtH,MAAM,CAAC,YAAY,EAAE,CAAC,mBAAmB,CAAC,CAAC;IAClDuH,KAAK,EAAEvH,MAAM,CAAC,YAAY,EAAE,CAAC,eAAe,CAAC,CAAC;IAC9CwH,IAAI,EAAExH,MAAM,CAAC,WAAW,EAAE,CAAC,cAAc,CAAC,CAAC;IAC3CyH,OAAO,EAAEzH,MAAM,CAAC,cAAc,EAAE,CAAC,qBAAqB,CAAC,CAAC;IACxD0H,KAAK,EAAE1H,MAAM,CAAC,YAAY,EAAE,CAAC,eAAe,CAAC,CAAC;IAC9C2H,MAAM,EAAE3H,MAAM,CAAC,aAAa,EAAE,CAAC,gBAAgB,CAAC,CAAC;IACjD4H,QAAQ,EAAE5H,MAAM,CAAC,eAAe,EAAE,CAAC,kBAAkB,CAAC,CAAC;IACvD6H,MAAM,EAAE7H,MAAM,CAAC,aAAa,EAAE,CAAC,oBAAoB,CAAC,CAAC;IACrD8H,KAAK,EAAE9H,MAAM,CAAC,YAAY,EAAE,CAAC,eAAe,CAAC,CAAC;IAC9C+H,KAAK,EAAE/H,MAAM,CAAC,YAAY,EAAE,CAAC,mBAAmB,CAAC,CAAC;IAClDgI,IAAI,EAAEhI,MAAM,CAAC,WAAW,EAAE,CAAC,cAAc,CAAC,CAAC;IAC3CiI,KAAK,EAAEjI,MAAM,CAAC,YAAY,EAAE,CAAC,mBAAmB,CAAC,CAAC;IAClDkI,KAAK,EAAElI,MAAM,CAAC,YAAY,EAAE,CAAC,mBAAmB,CAAC,CAAC;IAClDmI,KAAK,EAAEnI,MAAM,CAAC,YAAY,EAAE,CAAC,eAAe,CAAC,CAAC;IAC9CoI,KAAK,EAAEpI,MAAM,CAAC,YAAY,EAAE,CAAC,eAAe,CAAC,CAAC;IAC9CqI,IAAI,EAAErI,MAAM,CAAC,WAAW,EAAE,CAAC,cAAc,CAAC,CAAC;IAC3CsI,OAAO,EAAEtI,MAAM,CAAC,cAAc,EAAE,CAAC,qBAAqB,CAAC,CAAC;IACxDuI,KAAK,EAAEvI,MAAM,CAAC,YAAY,EAAE,CAAC,mBAAmB,CAAC,CAAC;IAClDwI,UAAU,EAAExI,MAAM,CAAC,kBAAkB,EAAE,CAAC,yBAAyB,CAAC,CAAC;IACnEyI,IAAI,EAAEzI,MAAM,CAAC,WAAW,EAAE,CAAC,cAAc,CAAC,CAAC;IAC3C0I,OAAO,EAAE1I,MAAM,CAAC,cAAc,EAAE,CAAC,qBAAqB,CAAC,CAAC;IACxD2I,IAAI,EAAE3I,MAAM,CAAC,WAAW,EAAE,CAAC,cAAc,CAAC,CAAC;IAC3C4I,UAAU,EAAE5I,MAAM,CAAC,kBAAkB,EAAE,CACrC,qBAAqB,EACrB,mBAAmB,CACpB,CAAC;IACF6I,IAAI,EAAE7I,MAAM,CAAC,WAAW,EAAE,CAAC,cAAc,CAAC,CAAC;IAC3C8I,KAAK,EAAE9I,MAAM,CAAC,YAAY,EAAE,CAAC,eAAe,CAAC,CAAC;AAC9C+I,IAAAA,KAAK,EAAE/I,MAAM,CAAC,YAAY,EAAE,CAAC,mBAAmB,CAAC,CAAA;GAClD;AAEDyD,EAAAA,GAAG,EAAE;IACHzB,IAAI,EAAEhC,MAAM,CAAC,UAAU,EAAE,CAAC,iBAAiB,EAAE,GAAGoB,eAAe,CAAC,CAAC;IACjE4H,OAAO,EAAEhJ,MAAM,CAAC,cAAc,EAAE,CAAC,iBAAiB,EAAE,GAAGoB,eAAe,CAAC,CAAC;IACxE6H,KAAK,EAAEjJ,MAAM,CAAC,YAAY,EAAE,CAAC,mBAAmB,EAAE,GAAGoB,eAAe,CAAC,CAAC;IACtEc,EAAE,EAAElC,MAAM,CAAC,QAAQ,EAAE,CAAC,eAAe,EAAE,GAAGoB,eAAe,CAAC,CAAA;GAC3D;AAEDsC,EAAAA,MAAM,EAAE;IACNwF,OAAO,EAAElJ,MAAM,CAAC,gBAAgB,EAAE,CAAC,mBAAmB,CAAC,CAAC;IACxDmJ,gBAAgB,EAAEnJ,MAAM,CAAC,yBAAyB,EAAE,CAClD,4BAA4B,CAC7B,CAAC;IACFoJ,gBAAgB,EAAEpJ,MAAM,CAAC,yBAAyB,EAAE,CAClD,4BAA4B,CAC7B,CAAC;IACFqJ,UAAU,EAAErJ,MAAM,CAAC,oBAAoB,EAAE,CAAC,2BAA2B,CAAC,CAAC;IACvEsJ,QAAQ,EAAEtJ,MAAM,CAAC,kBAAkB,EAAE,CAAC,qBAAqB,CAAC,CAAC;IAC7DuJ,SAAS,EAAEvJ,MAAM,CAAC,mBAAmB,EAAE,CAAC,sBAAsB,CAAC,CAAC;IAChEwJ,KAAK,EAAExJ,MAAM,CAAC,eAAe,EAAE,CAAC,kBAAkB,CAAC,CAAC;IACpDyJ,aAAa,EAAEzJ,MAAM,CAAC,wBAAwB,EAAE,CAC9C,2BAA2B,CAC5B,CAAC;IACFkF,UAAU,EAAElF,MAAM,CAAC,oBAAoB,EAAE,CAAC,uBAAuB,CAAC,CAAC;IACnEmF,QAAQ,EAAEnF,MAAM,CAAC,kBAAkB,EAAE,CAAC,qBAAqB,CAAC,CAAC;IAC7DiG,KAAK,EAAEjG,MAAM,CAAC,cAAc,EAAE,CAC5B,qBAAqB,EACrB,qBAAqB,CACtB,CAAA;GACF;AAEDN,EAAAA,MAAM,EAAE;IACNgK,MAAM,EAAE1J,MAAM,CAAC,eAAe,EAAE,CAAC,kBAAkB,CAAC,CAAC;IACrD2J,MAAM,EAAE3J,MAAM,CAAC,eAAe,EAAE,CAAC,kBAAkB,CAAC,CAAC;IACrD4J,gBAAgB,EAAE5J,MAAM,CAAC,0BAA0B,EAAE,CACnD,6BAA6B,CAC9B,CAAC;IACF6J,cAAc,EAAE7J,MAAM,CAAC,wBAAwB,EAAE,CAC/C,2BAA2B,CAC5B,CAAC;IACF8J,OAAO,EAAE9J,MAAM,CAAC,gBAAgB,EAAE,CAAC,mBAAmB,CAAC,CAAC;IACxD+J,MAAM,EAAE/J,MAAM,CAAC,eAAe,EAAE,CAAC,kBAAkB,CAAC,CAAC;IACrDgK,WAAW,EAAEhK,MAAM,CAAC,qBAAqB,EAAE,CACzC,wBAAwB,EACxB,mBAAmB,CACpB,CAAC;IACFiK,wBAAwB,EAAEjK,MAAM,CAAC,oCAAoC,EAAE,CACrE,uCAAuC,CACxC,CAAC;IACFkK,yBAAyB,EAAElK,MAAM,CAAC,qCAAqC,EAAE,CACvE,wCAAwC,CACzC,CAAC;IACFmK,mBAAmB,EAAEnK,MAAM,CAAC,+BAA+B,EAAE,CAC3D,kCAAkC,CACnC,CAAC;IACFoK,qBAAqB,EAAEpK,MAAM,CAAC,iCAAiC,EAAE,CAC/D,WAAW,CACZ,CAAC;IACFqK,cAAc,EAAErK,MAAM,CAAC,yBAAyB,EAAE,CAChD,4BAA4B,CAC7B,CAAC;IACFgJ,OAAO,EAAEhJ,MAAM,CAAC,iBAAiB,EAAE,CACjC,oBAAoB,EACpB,kBAAkB,CACnB,CAAC;IACFsK,MAAM,EAAEtK,MAAM,CAAC,gBAAgB,EAAE,CAAC,mBAAmB,CAAC,CAAC;IACvDuK,EAAE,EAAEvK,MAAM,CAAC,WAAW,EAAE,CAAC,cAAc,CAAC,CAAC;IACzCwK,YAAY,EAAExK,MAAM,CAAC,sBAAsB,EAAE,CAAC,yBAAyB,CAAC,CAAC;IACzEyK,QAAQ,EAAEzK,MAAM,CAAC,kBAAkB,EAAE,CAAC,qBAAqB,CAAC,CAAC;IAC7D0K,QAAQ,EAAE1K,MAAM,CAAC,kBAAkB,EAAE,CAAC,qBAAqB,CAAC,CAAC;IAC7DL,IAAI,EAAEK,MAAM,CAAC,aAAa,EAAE,CAAC,gBAAgB,CAAC,CAAC;IAC/C2K,iBAAiB,EAAE3K,MAAM,CAAC,2BAA2B,EAAE,CACrD,8BAA8B,CAC/B,CAAC;IACF4K,IAAI,EAAE5K,MAAM,CAAC,aAAa,EAAE,CAAC,gBAAgB,CAAC,CAAC;IAC/C6K,cAAc,EAAE7K,MAAM,CAAC,yBAAyB,EAAE,CAChD,4BAA4B,CAC7B,CAAC;AACF8K,IAAAA,MAAM,EAAE9K,MAAM,CAAC,eAAe,EAAE,CAAC,kBAAkB,CAAC,CAAA;GACrD;AAED4D,EAAAA,OAAO,EAAE;AACPmH,IAAAA,GAAG,EAAE/K,MAAM,CAAC,IAAI,EAAEkB,gCAAgC,CAAC;IACnD8J,UAAU,EAAEhL,MAAM,CAAC,qBAAqB,EAAE,CACxC,wBAAwB,EACxB,GAAGkB,gCAAgC,CACpC,CAAC;AACF+J,IAAAA,GAAG,EAAEjL,MAAM,CAAC,aAAa,EAAE,CACzB,gBAAgB,EAChB,oBAAoB,EACpB,GAAGkB,gCAAgC,CACpC,CAAC;AACFgK,IAAAA,IAAI,EAAElL,MAAM,CAAC,IAAI,EAAEkB,gCAAgC,CAAC;IACpDiK,GAAG,EAAEnL,MAAM,CAAC,aAAa,EAAE,CAAC,gBAAgB,EAAE,GAAGiB,mBAAmB,CAAC,CAAC;IACtEmK,aAAa,EAAEpL,MAAM,CAAC,wBAAwB,EAAE,CAC9C,2BAA2B,EAC3B,GAAGiB,mBAAmB,CACvB,CAAA;GACF;AAED8C,EAAAA,OAAO,EAAE;IACPsH,KAAK,EAAErL,MAAM,CAAC,eAAe,EAAE,CAAC,kBAAkB,CAAC,CAAC;IACpDsL,SAAS,EAAEtL,MAAM,CAAC,mBAAmB,EAAE,CAAC,sBAAsB,CAAC,CAAC;IAChEuL,cAAc,EAAEvL,MAAM,CAAC,yBAAyB,EAAE,CAChD,gCAAgC,CACjC,CAAC;IACF6J,cAAc,EAAE7J,MAAM,CAAC,yBAAyB,EAAE,CAChD,4BAA4B,CAC7B,CAAC;IACFwL,cAAc,EAAExL,MAAM,CAAC,yBAAyB,EAAE,CAChD,gCAAgC,CACjC,CAAC;IACFyL,cAAc,EAAEzL,MAAM,CAAC,yBAAyB,EAAE,CAChD,4BAA4B,CAC7B,CAAC;IACF0L,GAAG,EAAE1L,MAAM,CAAC,aAAa,EAAE,CAAC,gBAAgB,CAAC,CAAC;IAC9C2L,WAAW,EAAE3L,MAAM,CAAC,sBAAsB,EAAE,CAC1C,6BAA6B,CAC9B,CAAC;IACF4L,eAAe,EAAE5L,MAAM,CAAC,2BAA2B,EAAE,CACnD,kCAAkC,CACnC,CAAC;IACF6L,cAAc,EAAE7L,MAAM,CAAC,0BAA0B,EAAE,CACjD,iCAAiC,CAClC,CAAC;IACF8L,kBAAkB,EAAE9L,MAAM,CAAC,+BAA+B,EAAE,CAC1D,sCAAsC,CACvC,CAAC;IACFiK,wBAAwB,EAAEjK,MAAM,CAAC,qCAAqC,EAAE,CACtE,wCAAwC,CACzC,CAAC;IACFqK,cAAc,EAAErK,MAAM,CAAC,0BAA0B,EAAE,CACjD,6BAA6B,CAC9B,CAAC;IACF+L,GAAG,EAAE/L,MAAM,CAAC,aAAa,EAAE,CAAC,gBAAgB,CAAC,CAAC;IAC9CgM,WAAW,EAAEhM,MAAM,CAAC,sBAAsB,EAAE,CAC1C,6BAA6B,CAC9B,CAAC;IACFiM,cAAc,EAAEjM,MAAM,CAAC,0BAA0B,EAAE,CACjD,iCAAiC,CAClC,CAAC;IACFwK,YAAY,EAAExK,MAAM,CAAC,uBAAuB,EAAE,CAAC,0BAA0B,CAAC,CAAC;IAC3EkM,QAAQ,EAAElM,MAAM,CAAC,kBAAkB,EAAE,CAAC,yBAAyB,CAAC,CAAC;IACjEmM,OAAO,EAAEnM,MAAM,CAAC,kBAAkB,EAAE,CAAC,qBAAqB,CAAC,CAAC;IAC5D2K,iBAAiB,EAAE3K,MAAM,CAAC,4BAA4B,EAAE,CACtD,+BAA+B,CAChC,CAAC;IACFoM,GAAG,EAAEpM,MAAM,CAAC,aAAa,EAAE,CAAC,gBAAgB,CAAC,CAAC;AAC9C6K,IAAAA,cAAc,EAAE7K,MAAM,CAAC,0BAA0B,EAAE,CACjD,6BAA6B,CAC9B,CAAA;GACF;AAEDgE,EAAAA,MAAM,EAAE;AACNe,IAAAA,MAAM,EAAE/E,MAAM,CAAC,eAAe,EAAE,CAAC,kBAAkB,CAAC,CAAA;GACrD;AAEDR,EAAAA,GAAG,EAAE;IACHwC,IAAI,EAAEhC,MAAM,CAAC,UAAU,EAAE,CAAC,iBAAiB,EAAE,GAAGqB,eAAe,CAAC,CAAC;IACjEa,EAAE,EAAElC,MAAM,CAAC,QAAQ,EAAE,CAAC,eAAe,EAAE,GAAGqB,eAAe,CAAC,CAAA;GAC3D;AAEDgL,EAAAA,MAAM,EAAE;IACNC,MAAM,EAAEtM,MAAM,CAAC,eAAe,EAAE,CAAC,sBAAsB,CAAC,CAAC;AACzDuM,IAAAA,MAAM,EAAEvM,MAAM,CAAC,eAAe,EAAE,CAC9B,sBAAsB,EACtB,2BAA2B,EAC3B,aAAa,CACd,CAAC;IACFwM,aAAa,EAAExM,MAAM,CAAC,wBAAwB,EAAE,CAC9C,2BAA2B,CAC5B,CAAC;AACFyM,IAAAA,GAAG,EAAEzM,MAAM,CAAC,YAAY,EAAE,CAAC,eAAe,CAAC,CAAA;GAC5C;AAEDkE,EAAAA,MAAM,EAAE;IACNwI,YAAY,EAAE1M,MAAM,CAAC,sBAAsB,EAAE,CAC3C,yBAAyB,EACzB,iCAAiC,CAClC,CAAC;IACF2M,aAAa,EAAE3M,MAAM,CAAC,uBAAuB,EAAE,CAC7C,0BAA0B,CAC3B,CAAC;IACF4M,aAAa,EAAE5M,MAAM,CAAC,uBAAuB,EAAE,CAC7C,8BAA8B,CAC/B,CAAC;IACF6M,OAAO,EAAE7M,MAAM,CAAC,gBAAgB,EAAE,CAChC,mBAAmB,EACnB,qBAAqB,CACtB,CAAC;IACF8M,GAAG,EAAE9M,MAAM,CAAC,YAAY,EAAE,EAAE,EAAE,WAAW,CAAC;IAC1C+M,WAAW,EAAE/M,MAAM,CAAC,qBAAqB,EAAE,CACzC,wBAAwB,EACxB,0BAA0B,CAC3B,CAAC;IACFgN,kBAAkB,EAAEhN,MAAM,CAAC,6BAA6B,EAAE,CACxD,gCAAgC,EAChC,iBAAiB,CAClB,CAAC;IACFiN,YAAY,EAAEjN,MAAM,CAAC,sBAAsB,EAAE,CAC3C,6BAA6B,EAC7B,WAAW,CACZ,CAAC;IACFkN,kBAAkB,EAAElN,MAAM,CAAC,6BAA6B,EAAE,CACxD,oCAAoC,EACpC,WAAW,CACZ,CAAC;IACFmN,WAAW,EAAEnN,MAAM,CAAC,sBAAsB,EAAE,CAC1C,6BAA6B,EAC7B,WAAW,CACZ,CAAC;IACFoN,iBAAiB,EAAEpN,MAAM,CAAC,6BAA6B,EAAE,CACvD,oCAAoC,EACpC,WAAW,CACZ,CAAC;IACFqN,QAAQ,EAAErN,MAAM,CAAC,iBAAiB,EAAE,CAClC,oBAAoB,EACpB,GAAGa,sBAAsB,CAC1B,CAAC;IACFyM,MAAM,EAAEtN,MAAM,CAAC,gBAAgB,EAAE,EAAE,EAAE,WAAW,CAAC;IACjDuN,KAAK,EAAEvN,MAAM,CAAC,cAAc,EAAE,CAAC,iBAAiB,EAAE,iBAAiB,CAAC,CAAC;IACrEwN,OAAO,EAAExN,MAAM,CAAC,gBAAgB,EAAE,CAAC,uBAAuB,CAAC,CAAC;IAC5DyN,QAAQ,EAAEzN,MAAM,CAAC,kBAAkB,EAAE,CACnC,qBAAqB,EACrB,qBAAqB,CACtB,CAAC;AACFkM,IAAAA,QAAQ,EAAElM,MAAM,CAAC,iBAAiB,EAAE6B,6BAA6B,CAAC;IAClE6L,WAAW,EAAE1N,MAAM,CAAC,qBAAqB,EAAE,CAAC,4BAA4B,CAAC,CAAC;IAC1E2N,UAAU,EAAE3N,MAAM,CAAC,mBAAmB,EAAE,CAAC,0BAA0B,CAAC,CAAC;IACrE4N,YAAY,EAAE5N,MAAM,CAAC,sBAAsB,EAAE,CAC3C,6BAA6B,CAC9B,CAAC;IACF6N,OAAO,EAAE7N,MAAM,CAAC,gBAAgB,EAAE,CAChC,mBAAmB,EACnB,mBAAmB,CACpB,CAAC;IACF8N,MAAM,EAAE9N,MAAM,CAAC,eAAe,EAAE,CAAC,kBAAkB,EAAE,kBAAkB,CAAC,CAAC;IACzE+N,OAAO,EAAE/N,MAAM,CAAC,gBAAgB,EAAE,CAChC,mBAAmB,EACnB,kBAAkB,CACnB,CAAC;IACFgO,KAAK,EAAEhO,MAAM,CAAC,cAAc,EAAE,CAAC,iBAAiB,EAAE,iBAAiB,CAAC,CAAC;IACrEiO,WAAW,EAAEjO,MAAM,CAAC,qBAAqB,EAAE,CACzC,wBAAwB,EACxB,sBAAsB,CACvB,CAAC;AACFkO,IAAAA,WAAW,EAAElO,MAAM,CAAC,sBAAsB,EAAE,CAC1C,yBAAyB,EACzB,qBAAqB,EACrB,uBAAuB,EACvB,uBAAuB,CACxB,CAAC;AACFmO,IAAAA,WAAW,EAAEnO,MAAM,CAAC,oBAAoB,EAAE,CAAC,uBAAuB,CAAC,CAAA;GACpE;AAEDsE,EAAAA,GAAG,EAAE;IACH8J,QAAQ,EAAEpO,MAAM,CAAC,eAAe,EAAE,CAAC,mBAAmB,EAAE,SAAS,CAAC,CAAC;IACnE4G,KAAK,EAAE5G,MAAM,CAAC,WAAW,EAAE,CAAC,eAAe,EAAE,SAAS,CAAC,CAAA;GACxD;AAEDwE,EAAAA,OAAO,EAAE;IACPxC,IAAI,EAAEhC,MAAM,CAAC,eAAe,EAAE,CAC5B,sBAAsB,EACtB,GAAGsB,mBAAmB,CACvB,CAAC;IACFY,EAAE,EAAElC,MAAM,CAAC,aAAa,EAAE,CAAC,oBAAoB,EAAE,GAAGsB,mBAAmB,CAAC,CAAA;GACzE;AAEDmD,EAAAA,OAAO,EAAE;IACPzC,IAAI,EAAEhC,MAAM,CAAC,eAAe,EAAE,CAC5B,sBAAsB,EACtB,GAAGuB,mBAAmB,CACvB,CAAC;IACFW,EAAE,EAAElC,MAAM,CAAC,aAAa,EAAE,CAAC,oBAAoB,EAAE,GAAGuB,mBAAmB,CAAC,CAAA;GACzE;AAED0B,EAAAA,SAAS,EAAEnB,uBAAuB,CAAC,2BAA2B,CAAC;AAC/DuB,EAAAA,UAAU,EAAE;IACVgL,UAAU,EAAErO,MAAM,CAAC,IAAI,EAAE,CACvB,4BAA4B,EAC5B,GAAGS,sBAAsB,CAC1B,CAAC;IACF6N,OAAO,EAAEtO,MAAM,CAAC,IAAI,EAAE,CACpB,yBAAyB,EACzB,GAAGS,sBAAsB,CAC1B,CAAC;IACF,GAAGqB,uBAAuB,CAAC,4BAA4B,CAAA;GACxD;AACDwB,EAAAA,iBAAiB,EAAExB,uBAAuB,CACxC,oCACF,CAAC;AACDoB,EAAAA,UAAU,EAAEpB,uBAAuB,CAAC,4BAA4B,CAAC;AACjEyB,EAAAA,WAAW,EAAEzB,uBAAuB,CAAC,6BAA6B,CAAC;AACnEqB,EAAAA,UAAU,EAAErB,uBAAuB,CAAC,4BAA4B,CAAC;AACjE0B,EAAAA,WAAW,EAAE1B,uBAAuB,CAAC,6BAA6B,CAAC;AACnEiB,EAAAA,YAAY,EAAEjB,uBAAuB,CAAC,8BAA8B,CAAC;AACrEkB,EAAAA,YAAY,EAAElB,uBAAuB,CAAC,8BAA8B,CAAC;AAErEyM,EAAAA,WAAW,EAAE;AACXC,IAAAA,YAAY,EAAExO,MAAM,CAAC,IAAI,EAAEc,iBAAiB,CAAC;AAC7C2N,IAAAA,SAAS,EAAEzO,MAAM,CAAC,IAAI,EAAEc,iBAAiB,CAAC;AAC1C4N,IAAAA,YAAY,EAAE1O,MAAM,CAAC,IAAI,EAAEc,iBAAiB,CAAA;AAC9C,GAAA;AACF,CAAC,CAAA;AAED,CACE,gBAAgB,EAChB,WAAW,EACX,YAAY,EACZ,gBAAgB,EAChB,iBAAiB,EACjB,aAAa,EACb,WAAW,EACX,UAAU,CACX,CAACjB,OAAO,CAAC8O,cAAc,IAAI;AAC1BhJ,EAAAA,gBAAgB,CAACgJ,cAAc,CAAC,GAAGhJ,gBAAgB,CAAC9C,KAAK,CAAA;AAC3D,CAAC,CAAC,CAAA;AAEK,MAAM+L,kBAAkB,GAAG;AAChCC,EAAAA,cAAc,EAAE7O,MAAM,CAAC,IAAI,EAAE,CAC3B,wCAAwC,EACxC,GAAG0B,yBAAyB,EAC5B,kCAAkC,EAClC,GAAGE,oBAAoB,CACxB,CAAC;AACFkN,EAAAA,EAAE,EAAE9O,MAAM,CAAC,aAAa,EAAE;AACxB;AACA;AACA;AACA;AACA;AACA;AACA,EAAA,kBAAkB,EAClB,0BAA0B,EAC1B,aAAa,CACd,CAAC;EACF+O,MAAM,EAAE/O,MAAM,CAAC,IAAI,EAAE,CAAC,kBAAkB,CAAC,CAAC;EAC1CgP,GAAG,EAAEhP,MAAM,CAAC,IAAI,EAAE,CAAC,eAAe,CAAC,CAAC;EACpCiP,IAAI,EAAEjP,MAAM,CAAC,eAAe,EAAE,CAAC,kBAAkB,CAAC,CAAC;EACnDkP,KAAK,EAAElP,MAAM,CAAC,IAAI,EAAE,CAAC,iBAAiB,CAAC,CAAC;EACxCmP,IAAI,EAAEnP,MAAM,CAAC,IAAI,EAAE,CAAC,gBAAgB,CAAC,CAAC;EACtCoP,MAAM,EAAEpP,MAAM,CAAC,IAAI,EAAE,CAAC,wBAAwB,EAAE,GAAG4B,oBAAoB,CAAC,CAAC;EACzE0F,KAAK,EAAEtH,MAAM,CAAC,gBAAgB,EAAE,CAAC,qBAAqB,CAAC,CAAC;EACxDqP,WAAW,EAAErP,MAAM,CAAC,wBAAwB,EAAE,CAAC,yBAAyB,CAAC,CAAC;EAC1EsP,UAAU,EAAEtP,MAAM,CAAC,sBAAsB,EAAE,CAAC,2BAA2B,CAAC,CAAC;AACzEuG,EAAAA,MAAM,EAAEvG,MAAM,CAAC,iBAAiB,EAAE,CAAC,iBAAiB,CAAC,EAAEuP,SAAS,EAAE,CAAC,QAAQ,CAAC,CAAC;EAC7EC,UAAU,EAAExP,MAAM,CAAC,sBAAsB,EAAE,CAAC,sBAAsB,CAAC,CAAC;EACpEyP,WAAW,EAAEzP,MAAM,CAAC,sBAAsB,EAAE,CAAC,6BAA6B,CAAC,CAAC;EAC5E0P,WAAW,EAAE1P,MAAM,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,uBAAuB,CAAC,CAAC;EACjE2P,MAAM,EAAE3P,MAAM,CAAC,IAAI,EAAE,CAAC,mBAAmB,CAAC,CAAC;AAC3C4P,EAAAA,IAAI,EAAE5P,MAAM,CAAC,IAAI,EAAE,CACjB,kBAAkB,EAClB,GAAG4B,oBAAoB,EACvB,4BAA4B,EAC5B,GAAGF,yBAAyB,CAC7B,CAAC;EACFmO,QAAQ,EAAE7P,MAAM,CAAC,oBAAoB,EAAE,CAAC,qBAAqB,CAAC,CAAC;AAC/D8J,EAAAA,OAAO,EAAE9J,MAAM,CAAC,kBAAkB,EAAEY,2BAA2B,CAAC;EAChEkP,KAAK,EAAE9P,MAAM,CAAC,gBAAgB,EAAE,CAC9B,gBAAgB,EAChB,mBAAmB,EACnB,GAAG4B,oBAAAA;AACH;AACA;AACA;AACA;AACA;AACA;AAAA,GACD,CAAC;EACFmO,IAAI,EAAE/P,MAAM,CAAC,IAAI,EAAE,CAAC,gBAAgB,CAAC,CAAC;EACtCgQ,IAAI,EAAEhQ,MAAM,CAAC,eAAe,EAAE,CAAC,eAAe,CAAC,CAAC;EAChDiQ,MAAM,EAAEjQ,MAAM,CAAC,iBAAiB,EAAE,CAChC,iBAAiB,EACjB,oBAAoB,EACpB,GAAG4B,oBAAAA;AACH;AAAA,GACD,CAAC;EACFsO,YAAY,EAAElQ,MAAM,CAAC,wBAAwB,EAAE,CAC7C,4BAA4B,CAC7B,CAAC;EACFmQ,OAAO,EAAEnQ,MAAM,CAAC,IAAI,EAAE,CAAC,oBAAoB,EAAE,GAAGiB,mBAAmB,CAAC,CAAC;EACrEmP,IAAI,EAAEpQ,MAAM,CAAC,eAAe,EAAE,CAC5B,eAAe,EACf,kBAAkB,EAClB,GAAG4B,oBAAAA;AACH;AAAA,GACD,CAAC;EACFyO,SAAS,EAAErQ,MAAM,CAAC,qBAAqB,EAAE,CAAC,qBAAqB,CAAC,CAAC;EACjEsQ,QAAQ,EAAEtQ,MAAM,CAAC,oBAAoB,EAAE,CAAC,oBAAoB,CAAC,CAAC;EAC9DuQ,aAAa,EAAEvQ,MAAM,CAAC,0BAA0B,EAAE,CAChD,0BAA0B,CAC3B,CAAC;EACFwQ,KAAK,EAAExQ,MAAM,CAAC,IAAI,EAAE,CAAC,iBAAiB,CAAC,CAAC;EACxCyQ,KAAK,EAAEzQ,MAAM,CAAC,gBAAgB,EAAE,CAAC,iBAAiB,CAAC,CAAC;AACpD0Q,EAAAA,OAAO,EAAE1Q,MAAM,CAAC,mBAAmB,EAAE,CACnC,mBAAmB,EACnB,+BAA+B,EAC/B,sBAAsB,EACtB,GAAG4B,oBAAAA;AACH;AAAA,GACD,CAAC;EACF+O,IAAI,EAAE3Q,MAAM,CAAC,eAAe,EAAE,CAAC,eAAe,EAAE,2BAA2B,CAAC,CAAC;EAC7E4Q,UAAU,EAAE5Q,MAAM,CAAC,IAAI,EAAE,CACvB,0BAA0B,EAC1B,GAAGmC,oBAAoB,CACxB,CAAC;EACF0O,eAAe,EAAE7Q,MAAM,CAAC,IAAI,EAAE,CAC5B,oCAAoC,EACpC,GAAGmC,oBAAoB,CACxB,CAAC;EACF2O,OAAO,EAAE9Q,MAAM,CAAC,IAAI,EAAE,CAAC,kBAAkB,CAAC,CAAC;EAC3C+Q,KAAK,EAAE/Q,MAAM,CAAC,gBAAgB,EAAE,CAAC,oBAAoB,CAAC,CAAC;EACvDgJ,OAAO,EAAEhJ,MAAM,CAAC,mBAAmB,EAAE,CAAC,uBAAuB,CAAC,CAAC;AAC/DgR,EAAAA,YAAY,EAAEhR,MAAM,CAAC,0BAA0B,EAAE,CAC/C,8BAA8B,EAC9B,QAAQ,EACR,qBAAqB,CACtB,CAAC;AACFiR,EAAAA,UAAU,EAAEjR,MAAM,CAAC,uBAAuB,EAAE,CAC1C,2BAA2B,EAC3B,QAAQ,EACR,qBAAqB,CACtB,CAAC;EACFkR,SAAS,EAAElR,MAAM,CAAC,IAAI,EAAE,CAAC,qBAAqB,CAAC,CAAC;EAChDmR,QAAQ,EAAEnR,MAAM,CAAC,IAAI,EAAE,CAAC,oBAAoB,CAAC,CAAC;EAC9CH,OAAO,EAAEG,MAAM,CAAC,mBAAmB,EAAE,CACnC,mBAAmB,EACnB,sBAAsB,EACtB,GAAG4B,oBAAoB;AACvB;AACA,EAAA,8BAA8B,CAC/B,CAAC;EACFwP,QAAQ,EAAEpR,MAAM,CAAC,mBAAmB,EAAE,CACpC,mBAAmB,EACnB,oBAAoB,CACrB,CAAC;AACFqR,EAAAA,OAAO,EAAErR,MAAM,CAAC,IAAI,EAAE,CACpB,+BAA+B,EAC/B,GAAG0B,yBAAyB,EAC5B,yBAAyB,EACzB,GAAGE,oBAAoB,CACxB,CAAC;EACF0P,OAAO,EAAEtR,MAAM,CAAC,mBAAmB,EAAE,CAAC,mBAAmB,CAAC,CAAC;EAC3DuR,YAAY,EAAEvR,MAAM,CAAC,yBAAyB,EAAE,CAAC,0BAA0B,CAAC,CAAC;EAC7EwR,OAAO,EAAExR,MAAM,CAAC,IAAI,EAAE,CAAC,mBAAmB,CAAC,CAAC;EAC5CyR,IAAI,EAAEzR,MAAM,CAAC,IAAI,EAAE,CAAC,eAAe,CAAC,CAAC;AACrCL,EAAAA,IAAI,EAAEK,MAAM,CAAC,eAAe,EAAEY,2BAA2B,CAAC;EAC1D8Q,SAAS,EAAE1R,MAAM,CAAC,IAAI,EAAE,CAAC,yBAAyB,CAAC,CAAC;EACpD2R,WAAW,EAAE3R,MAAM,CAAC,wBAAwB,EAAE,CAAC,wBAAwB,CAAC,CAAC;EACzE4R,QAAQ,EAAE5R,MAAM,CAAC,IAAI,EAAE,CAAC,wBAAwB,CAAC,CAAC;EAClD6R,IAAI,EAAE7R,MAAM,CAAC,IAAI,EAAE,CAAC,gBAAgB,CAAC,CAAC;EACtC8R,GAAG,EAAE9R,MAAM,CAAC,cAAc,EAAE,CAC1B,cAAc,EACd,iBAAiB,EACjB,GAAG4B,oBAAAA;AACH;AAAA,GACD,CAAC;EACF2L,KAAK,EAAEvN,MAAM,CAAC,IAAI,EAAE,CAAC,iBAAiB,EAAE,gBAAgB,CAAC,CAAC;EAC1DyN,QAAQ,EAAEzN,MAAM,CAAC,oBAAoB,EAAE,CACrC,qBAAqB,EACrB,gBAAgB,CACjB,CAAC;EACFF,IAAI,EAAEE,MAAM,CAAC,IAAI,EAAE,CAAC,kBAAkB,CAAC,CAAC;EACxC+R,MAAM,EAAE/R,MAAM,CAAC,kBAAkB,EAAE,CAAC,mBAAmB,CAAC,CAAC;EACzDgS,QAAQ,EAAEhS,MAAM,CAAC,oBAAoB,EAAE,CAAC,qBAAqB,CAAC,CAAC;EAC/DiS,IAAI,EAAEjS,MAAM,CAAC,eAAe,EAAE,CAAC,eAAe,CAAC,CAAC;EAChDkS,MAAM,EAAElS,MAAM,CAAC,iBAAiB,EAAE,CAChC,iBAAiB,EACjB,oBAAoB,EACpB,GAAG4B,oBAAAA;AACH;AAAA,GACD,CAAC;EACFuQ,WAAW,EAAEnS,MAAM,CAAC,uBAAuB,EAAE,CAAC,uBAAuB,CAAC,CAAC;EACvEoS,MAAM,EAAEpS,MAAM,CAAC,iBAAiB,EAAE,CAAC,kBAAkB,CAAC,CAAC;EACvD6N,OAAO,EAAE7N,MAAM,CAAC,IAAI,EAAE,CAAC,mBAAmB,EAAE,gBAAgB,CAAC,CAAC;AAC9DqS,EAAAA,UAAU,EAAErS,MAAM,CAAC,sBAAsB,EAAE,CACzC,uBAAuB,EACvB,mBAAmB,EACnB,gBAAgB,CACjB,CAAC;EACFsS,OAAO,EAAEtS,MAAM,CAAC,kBAAkB,EAAE,CAAC,kBAAkB,CAAC,CAAC;EACzD8N,MAAM,EAAE9N,MAAM,CAAC,IAAI,EAAE,CAAC,kBAAkB,EAAE,gBAAgB,CAAC,CAAC;EAC5DuS,UAAU,EAAEvS,MAAM,CAAC,IAAI,EAAE,CACvB,0BAA0B,EAC1B,GAAGmC,oBAAoB,CACxB,CAAC;EACFqQ,eAAe,EAAExS,MAAM,CAAC,IAAI,EAAE,CAC5B,oCAAoC,EACpC,GAAGmC,oBAAoB,CACxB,CAAC;EACFsQ,OAAO,EAAEzS,MAAM,CAAC,IAAI,EAAE,CAAC,kBAAkB,CAAC,CAAC;EAC3C0S,KAAK,EAAE1S,MAAM,CAAC,gBAAgB,EAAE,CAAC,gBAAgB,CAAC,CAAC;EACnD2S,OAAO,EAAE3S,MAAM,CAAC,IAAI,EAAE,CAAC,yBAAyB,EAAE,GAAG4B,oBAAoB,CAAC,CAAC;EAC3EgR,KAAK,EAAE5S,MAAM,CAAC,IAAI,EAAE,CAAC,iBAAiB,CAAC,CAAC;EACxC6S,IAAI,EAAE7S,MAAM,CAAC,eAAe,EAAE,CAC5B,eAAe,EACf,kBAAkB,EAClB,GAAG4B,oBAAAA;AACH;AAAA,GACD,CAAC;EACFxB,IAAI,EAAEJ,MAAM,CAAC,eAAe,EAAE,CAAC,eAAe,CAAC,CAAC;EAChD8S,MAAM,EAAE9S,MAAM,CAAC,iBAAiB,EAAE,CAAC,iBAAiB,CAAC,CAAC;EACtDgO,KAAK,EAAEhO,MAAM,CAAC,IAAI,EAAE,CAAC,iBAAiB,EAAE,gBAAgB,CAAC,CAAC;EAC1D+S,UAAU,EAAE/S,MAAM,CAAC,sBAAsB,EAAE,CAAC,uBAAuB,CAAC,CAAC;EACrEgT,MAAM,EAAEhT,MAAM,CAAC,IAAI,EAAE,CAAC,kBAAkB,CAAC,CAAC;EAC1CiT,MAAM,EAAEjT,MAAM,CAAC,IAAI,EAAE,CAAC,kBAAkB,CAAC,CAAC;EAC1CkT,GAAG,EAAElT,MAAM,CAAC,IAAI,EAAE,CAAC,eAAe,CAAC,CAAC;EACpCmT,MAAM,EAAEnT,MAAM,CAAC,IAAI,EAAE,CAAC,kBAAkB,CAAC,CAAC;EAC1CoT,GAAG,EAAEpT,MAAM,CAAC,IAAI,EAAE,CAAC,eAAe,CAAC,CAAC;AACpCqT,EAAAA,IAAI,EAAErT,MAAM,CAAC,IAAI,EAAE,CACjB,kBAAkB,EAClB,GAAG4B,oBAAoB,EACvB,4BAA4B,EAC5B,GAAGF,yBAAyB,CAC7B,CAAC;EACF4R,IAAI,EAAEtT,MAAM,CAAC,IAAI,EAAE,CAAC,gBAAgB,EAAE,gBAAgB,CAAC,CAAC;AACxDuT,EAAAA,OAAO,EAAEvT,MAAM,CAAC,IAAI,EAAE,CACpB,sBAAsB,EACtB,GAAG4B,oBAAoB,EACvB,gCAAgC,EAChC,GAAGF,yBAAyB,CAC7B,CAAC;AACF8R,EAAAA,OAAO,EAAExT,MAAM,CAAC,IAAI,EAAE,CACpB,0BAA0B,EAC1B,GAAG4B,oBAAoB,EACvB,GAAGF,yBAAyB,EAC5B,GAAGC,2BAA2B,CAC/B,CAAC;EACF8R,aAAa,EAAEzT,MAAM,CAAC,IAAI,EAAE,CAAC,0BAA0B,CAAC,CAAC;EACzD0T,OAAO,EAAE1T,MAAM,CAAC,IAAI,EAAE,CAAC,oBAAoB,CAAC,CAAC;EAC7C2T,WAAW,EAAE3T,MAAM,CAAC,IAAI,EAAE,CAAC,uBAAuB,CAAC,CAAC;EACpD4T,WAAW,EAAE5T,MAAM,CAAC,IAAI,EAAE,CAAC,uBAAuB,CAAC,CAAC;EACpD6T,MAAM,EAAE7T,MAAM,CAAC,IAAI,EAAE,CAAC,iBAAiB,CAAC,CAAC;EACzC8T,WAAW,EAAE9T,MAAM,CAAC,IAAI,EAAE,CAAC,wBAAwB,CAAC,CAAC;EACrD+T,UAAU,EAAE/T,MAAM,CAAC,sBAAsB,EAAE,CAAC,sBAAsB,CAAC,CAAC;EACpEgU,QAAQ,EAAEhU,MAAM,CAAC,oBAAoB,EAAE,CACrC,oBAAoB,EACpB,eAAe,CAChB,CAAC;EACFiU,SAAS,EAAEjU,MAAM,CAAC,qBAAqB,EAAE,CAAC,qBAAqB,CAAC,CAAC;AACjEkU,EAAAA,QAAQ,EAAElU,MAAM,CAAC,IAAI,EAAE,CACrB,qBAAqB,EACrB,oBAAoB,EACpB,mBAAmB,EACnB,qBAAqB,CACtB,CAAC;EACFmU,YAAY,EAAEnU,MAAM,CAAC,yBAAyB,EAAE,CAAC,0BAA0B,CAAC,CAAC;EAC7EoU,IAAI,EAAEpU,MAAM,CAAC,eAAe,EAAE,CAAC,gBAAgB,CAAC,CAAC;EACjDqU,OAAO,EAAErU,MAAM,CAAC,mBAAmB,EAAE,CAAC,oBAAoB,CAAC,CAAC;EAC5DsU,QAAQ,EAAEtU,MAAM,CAAC,oBAAoB,EAAE,CAAC,sBAAsB,CAAC,CAAC;EAChEuU,SAAS,EAAEvU,MAAM,CAAC,qBAAqB,EAAE,CAAC,oBAAoB,CAAC,CAAC;EAChEwU,SAAS,EAAExU,MAAM,CAAC,qBAAqB,EAAE,CAAC,sBAAsB,CAAC,CAAC;EAClEyU,QAAQ,EAAEzU,MAAM,CAAC,oBAAoB,EAAE,CAAC,wBAAwB,EAAE,QAAQ,CAAC,CAAC;EAC5E0U,OAAO,EAAE1U,MAAM,CAAC,kBAAkB,EAAE,CAAC,kBAAkB,CAAC,CAAC;EACzD2U,MAAM,EAAE3U,MAAM,CAAC,kBAAkB,EAAE,CAAC,yBAAyB,CAAC,CAAC;AAC/D8K,EAAAA,MAAM,EAAE9K,MAAM,CAAC,iBAAiB,EAAEY,2BAA2B,CAAC;EAC9DgU,OAAO,EAAE5U,MAAM,CAAC,IAAI,EAAE,CAAC,yBAAyB,EAAE,GAAG4B,oBAAoB,CAAC,CAAC;EAC3EiT,IAAI,EAAE7U,MAAM,CAAC,eAAe,EAAE,CAAC,eAAe,CAAC,CAAC;EAChD8U,gBAAgB,EAAE9U,MAAM,CAAC,IAAI,EAAE,CAAC,yBAAyB,CAAC,CAAC;EAC3D+U,gBAAgB,EAAE/U,MAAM,CAAC,IAAI,EAAE,CAAC,yBAAyB,CAAC,CAAC;EAC3DgV,gBAAgB,EAAEhV,MAAM,CAAC,IAAI,EAAE,CAAC,yBAAyB,CAAC,CAAC;EAC3DiV,gBAAgB,EAAEjV,MAAM,CAAC,IAAI,EAAE,CAAC,yBAAyB,CAAC,CAAC;EAC3D,CAAC,WAAW,GAAGA,MAAM,CAAC,IAAI,EAAE,CAAC,iBAAiB,CAAC,CAAA;AACjD,CAAC;;AC3gCD;AACA;AACA;;AAEO,MAAMkV,MAAM,GAAG,IAAI1V,GAAG,CAAC,CAC5B,OAAO,EACP,YAAY,EACZ,gBAAgB,EAChB,UAAU,EACV,iBAAiB,EACjB,UAAU,EACV,eAAe,EACf,wBAAwB,EACxB,iBAAiB,EACjB,sBAAsB,EACtB,oBAAoB,EACpB,kBAAkB,EAClB,gBAAgB,EAChB,eAAe,EACf,iBAAiB,EACjB,eAAe,EACf,qBAAqB,EACrB,gBAAgB,EAChB,eAAe,EACf,mBAAmB,EACnB,mBAAmB,EACnB,mBAAmB,EACnB,mBAAmB,EACnB,eAAe,EACf,wBAAwB,EACxB,cAAc,EACd,kBAAkB,EAClB,oBAAoB,EACpB,iBAAiB,EACjB,uBAAuB,EACvB,iBAAiB,EACjB,kBAAkB,EAClB,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,iBAAiB,EACjB,sBAAsB,EACtB,eAAe,EACf,mBAAmB,EACnB,oBAAoB,EACpB,qBAAqB,EACrB,qBAAqB,EACrB,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,EACL,YAAY,EACZ,YAAY,EACZ,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,aAAa,EACb,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,YAAY,EACZ,WAAW,EACX,WAAW,EACX,WAAW,EACX,WAAW,EACX,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,mBAAmB,EACnB,eAAe,EACf,wBAAwB,EACxB,yBAAyB,EACzB,yBAAyB,EACzB,oBAAoB,EACpB,kBAAkB,EAClB,eAAe,EACf,eAAe,EACf,0BAA0B,EAC1B,wBAAwB,EACxB,gBAAgB,EAChB,eAAe,EACf,qBAAqB,EACrB,oCAAoC,EACpC,qCAAqC,EACrC,+BAA+B,EAC/B,iCAAiC,EACjC,yBAAyB,EACzB,WAAW,EACX,sBAAsB,EACtB,kBAAkB,EAClB,kBAAkB,EAClB,aAAa,EACb,2BAA2B,EAC3B,aAAa,EACb,yBAAyB,EACzB,eAAe,EACf,aAAa,EACb,WAAW,EACX,SAAS,EACT,iBAAiB,EACjB,eAAe,EACf,mBAAmB,EACnB,yBAAyB,EACzB,yBAAyB,EACzB,aAAa,EACb,qCAAqC,EACrC,0BAA0B,EAC1B,aAAa,EACb,uBAAuB,EACvB,kBAAkB,EAClB,4BAA4B,EAC5B,aAAa,EACb,0BAA0B,EAC1B,KAAK,EACL,eAAe,EACf,cAAc,EACd,aAAa,EACb,wBAAwB,EACxB,YAAY,EACZ,QAAQ,EACR,uBAAuB,EACvB,YAAY,EACZ,qBAAqB,EACrB,6BAA6B,EAC7B,iBAAiB,EACjB,gBAAgB,EAChB,cAAc,EACd,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,cAAc,EACd,qBAAqB,EACrB,sBAAsB,EACtB,oBAAoB,EACpB,KAAK,EACL,mBAAmB,EACnB,UAAU,EACV,UAAU,CACX,CAAC,CAAA;AAEK,MAAM2V,SAAS,GAAG,IAAI3V,GAAG,CAAC,CAC/B,GAAG0V,MAAM,EACT,iBAAiB,EACjB,eAAe,EACf,kBAAkB,EAClB,aAAa,EACb,aAAa,EACb,sBAAsB,EACtB,oBAAoB,EACpB,sBAAsB,EACtB,YAAY,EACZ,cAAc,EACd,kBAAkB,EAClB,aAAa,EACb,YAAY,EACZ,YAAY,EACZ,YAAY,EACZ,kBAAkB,EAClB,cAAc,EACd,YAAY,EACZ,kBAAkB,EAClB,cAAc,EACd,YAAY,EACZ,oBAAoB,EACpB,YAAY,EACZ,yBAAyB,EACzB,yBAAyB,EACzB,sBAAsB,EACtB,2BAA2B,EAC3B,0BAA0B,EAC1B,+BAA+B,EAC/B,sBAAsB,EACtB,0BAA0B,EAC1B,kBAAkB,EAClB,gBAAgB,EAChB,mBAAmB,EACnB,sBAAsB,CACvB,CAAC;;;ACjLOE,EAAAA,KAAK,EAAIC,GAAAA;AAAC,CAAA,GAAAC,MAAA,CAAAC,OAAA,IAAAD,MAAA,CAAA;AAEJ,SAASE,eAAeA,CACrCC,IAA8B,EAC9BC,IAAc,EACd;EACA,MAAM;IAAEC,IAAI;AAAEC,IAAAA,MAAAA;AAAO,GAAC,GAAGF,IAAI,CAAA;EAC7B,QAAQD,IAAI,CAAC3V,IAAI;AACf,IAAA,KAAK,iBAAiB;AAAE,MAAA;AACtB,QAAA,IAAI,CAACuV,GAAC,CAACQ,gBAAgB,CAACD,MAAM,EAAE;AAAEE,UAAAA,MAAM,EAAEH,IAAAA;SAAM,CAAC,EAAE,OAAO,KAAK,CAAA;QAC/D,IAAIC,MAAM,CAACG,SAAS,CAACC,MAAM,GAAG,CAAC,EAAE,OAAO,IAAI,CAAA;AAC5C,QAAA,MAAMC,QAAQ,GAAGL,MAAM,CAACG,SAAS,CAAC,CAAC,CAAC,CAAA;AACpC,QAAA,OAAOV,GAAC,CAACa,eAAe,CAACD,QAAQ,CAAC,IAAIZ,GAAC,CAACc,iBAAiB,CAACF,QAAQ,CAAC,CAAA;AACrE,OAAA;AACF,GAAA;AACF;;;AChBSb,EAAAA,KAAK,EAAIC,GAAAA;AAAC,CAAA,GAAAC,MAAA,CAAAC,OAAA,IAAAD,MAAA,CAAA;AAGZ,MAAMc,aAAa,GAAG,wBAAwB,CAAA;AAE9C,SAASC,UAAUA,CACxBX,IAAS,EACTY,EAAgB,EAChBC,YAAsB,EACtBC,UAAmD,EACnD;AACA,EAAA,MAAM,CAACC,QAAQ,EAAEC,QAAQ,CAAC,GAAGC,mBAAmB,CAACjB,IAAI,CAACC,IAAI,EAAED,IAAI,CAACkB,KAAK,CAAC,CAAA;EAEvE,IAAId,MAAoB,GAAGT,GAAC,CAACwB,cAAc,CAACP,EAAE,EAAE,CAACG,QAAQ,CAAC,CAAC,CAAA;AAC3D,EAAA,IAAID,UAAU,EAAEV,MAAM,GAAGU,UAAU,CAACV,MAAM,CAAC,CAAA;AAE3C,EAAA,MAAMgB,IAAI,GAAGzB,GAAC,CAAC0B,UAAU,CAAC,MAAM,CAAC,CAAA;EAEjCrB,IAAI,CAACsB,WAAW,CACdT,YAAY,GACRlB,GAAC,CAAC4B,wBAAwB,CAACnB,MAAM,EAAEgB,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,GACrDzB,GAAC,CAAC6B,gBAAgB,CAACpB,MAAM,EAAEgB,IAAI,CACrC,CAAC,CAAA;EAEDpB,IAAI,CAACyB,UAAU,CAACC,gBAAgB,CAAC,WAAW,EAAEV,QAAQ,CAAC,CAAA;AACzD,CAAA;AAEO,SAASC,mBAAmBA,CACjChB,IAAqD,EACrDiB,KAAwB,EACxB;EACA,MAAM;AAAES,IAAAA,MAAAA;AAAO,GAAC,GAAG1B,IAAI,CAAA;EAEvB,IAAIc,QAAQ,EAAEC,QAAQ,CAAA;AACtB,EAAA,IAAIrB,GAAC,CAACiC,YAAY,CAACD,MAAM,CAAC,EAAE;AAC1BX,IAAAA,QAAQ,GAAGW,MAAM,CAAA;AACjBZ,IAAAA,QAAQ,GAAGpB,GAAC,CAACkC,SAAS,CAACF,MAAM,CAAC,CAAA;AAChC,GAAC,MAAM;AACLX,IAAAA,QAAQ,GAAGE,KAAK,CAACY,6BAA6B,CAAC,SAAS,CAAC,CAAA;AACzDf,IAAAA,QAAQ,GAAGpB,GAAC,CAACoC,oBAAoB,CAAC,GAAG,EAAEpC,GAAC,CAACkC,SAAS,CAACb,QAAQ,CAAC,EAAEW,MAAM,CAAC,CAAA;AACvE,GAAA;AAEA,EAAA,OAAO,CAACZ,QAAQ,EAAEC,QAAQ,CAAC,CAAA;AAC7B,CAAA;AAEO,SAASgB,oBAAoBA,CAClCd,KAAwB,EACxBjB,IAAgC,EAChC;EACA,IAAIgC,YAAY,GAAGhC,IAAI,CAAA;AACvB,EAAA,OACE,CAACgC,YAAY,CAACC,QAAQ,IACtBvC,GAAC,CAACwC,0BAA0B,CAACF,YAAY,CAACN,MAAM,CAAC,EACjD;IACAM,YAAY,GAAGA,YAAY,CAACN,MAAM,CAAA;AACpC,GAAA;EACAM,YAAY,CAACC,QAAQ,GAAG,KAAK,CAAA;AAE7B,EAAA,MAAME,GAAG,GAAGlB,KAAK,CAACY,6BAA6B,CAAC,SAAS,CAAC,CAAA;AAC1D,EAAA,MAAM9N,MAAM,GAAG2L,GAAC,CAACoC,oBAAoB,CAAC,GAAG,EAAEK,GAAG,EAAEH,YAAY,CAACN,MAAM,CAAC,CAAA;EACpEM,YAAY,CAACN,MAAM,GAAGhC,GAAC,CAACkC,SAAS,CAACO,GAAG,CAAC,CAAA;AAEtC,EAAA,OAAOC,YAAY,IACjB1C,GAAC,CAAC2C,qBAAqB,CACrB3C,GAAC,CAAC4C,gBAAgB,CAAC,IAAI,EAAEvO,MAAM,EAAE2L,GAAC,CAAC6C,WAAW,EAAE,CAAC,EACjD7C,GAAC,CAAC8C,eAAe,CAAC,MAAM,EAAE9C,GAAC,CAAC+C,cAAc,CAAC,CAAC,CAAC,CAAC,EAC9CL,YACF,CAAC,CAAA;AACL,CAAA;AAEO,SAASM,cAAcA,CAACC,MAAc,EAAE;AAC7C,EAAA,IAAI,OAAOA,MAAM,KAAK,QAAQ,EAAE;AAC9BA,IAAAA,MAAM,GAAGA,MAAM,CACZzK,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CACnBA,OAAO,CAAC,wBAAwB,EAAE,EAAE,CAAC,CACrC0K,WAAW,EAAE,CAAA;AAClB,GAAA;AAEA,EAAA,OACE7Y,MAAM,CAAC8Y,SAAS,CAACC,cAAc,CAAC3B,IAAI,CAAC4B,aAAa,EAAEJ,MAAM,CAAC,IAC3DI,aAAa,CAACJ,MAAM,CAAC,CAAA;AAEzB,CAAA;AAEO,SAASK,YAAYA,CAAC7Y,IAAY,EAAE;EACzC,OAAO,CAAA,gBAAA,EAAmBA,IAAI,CAAK,GAAA,CAAA,CAAA;AACrC,CAAA;AAEO,SAAS8Y,gBAAgBA,CAC9B9Y,IAAY,EACZ+Y,eAAwB,EACxBC,GAAW,EACX;AACA,EAAA,OAAOD,eAAe,GAClB,CAAGzC,EAAAA,aAAa,CAAYtW,SAAAA,EAAAA,IAAI,CAAGgZ,EAAAA,GAAG,CAAE,CAAA,GACxC,CAAyBhZ,sBAAAA,EAAAA,IAAI,CAAK,GAAA,CAAA,CAAA;AACxC;;AClF8C,MAAA;AAGrCsV,EAAAA,KAAK,EAAIC,CAAC;AAAE0D,EAAAA,QAAQ,EAARA,QAAAA;AAAQ,CAAA,GAAAzD,MAAA,CAAAC,OAAA,IAAAD,MAAA,CAAA;AAa7B,MAAM0D,eAAe,GAAG,iDAAiD,CAAA;AACzE,MAAMC,aAAa,GAAG,8CAA8C,CAAA;AAapE,MAAMC,aAAa,GAAG,CACpB,OAAO,EACP,QAAQ,EAER,UAAU,EACV,gBAAgB,EAChB,iBAAiB,CAClB,CAACpH,GAAG,CAACqH,CAAC,IAAI,IAAInV,MAAM,CAAC,CAAYmV,SAAAA,EAAAA,CAAC,CAAO,KAAA,CAAA,CAAC,CAAC,CAAA;AAE5C,MAAMC,cAAc,GAAGA,CACrBtZ,IAAY,EACZuZ,EAA6B,KACjB;AACZ,EAAA,IAAIA,EAAE,CAACvZ,IAAI,CAAC,EAAE,OAAO,IAAI,CAAA;EACzB,IAAI,CAACA,IAAI,CAACiT,UAAU,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAA;EACzC,MAAMuG,QAAQ,GAAG,CAAUxZ,OAAAA,EAAAA,IAAI,CAAC4S,KAAK,CAAC,CAAC,CAAC,CAAE,CAAA,CAAA;AAC1C,EAAA,IAAI,CAAC9S,gBAAgB,CAAC0Z,QAAQ,CAAC,EAAE,OAAO,KAAK,CAAA;EAC7C,OAAOD,EAAE,CAACC,QAAQ,CAAC,CAAA;AACrB,CAAC,CAAA;AAED,YAAeC,cAAc,CAAU,UACrC;EAAEC,QAAQ;EAAEC,MAAM;EAAEC,oBAAoB;EAAEC,kBAAkB;EAAEC,KAAK;AAAEC,EAAAA,KAAAA;AAAM,CAAC,EAC5E;AACEC,EAAAA,OAAO,GAAG,CAAC;aACX3E,WAAS;EACT4E,gBAAgB;AAChB,EAAA,CAACf,eAAe,GAAG;AAAEgB,IAAAA,aAAa,GAAG,KAAA;GAAO,GAAG,EAAE;AACjD,EAAA,CAACf,aAAa,GAAG;AAAEJ,IAAAA,eAAe,GAAG,KAAK;AAAEC,IAAAA,GAAG,GAAG,KAAA;AAAM,GAAC,GAAG,EAAC;AAC/D,CAAC,EACD;AACA,EAAA,MAAMmB,SAAS,GAAGJ,KAAK,CAACK,MAAM,CAACA,MAAM,IAAI,CAAAA,MAAM,oBAANA,MAAM,CAAEpa,IAAI,MAAK,cAAc,CAAC,CAAA;EAEzE,MAAMqa,OAAO,GAAGR,kBAAkB,CAAC;AACjCzZ,IAAAA,MAAM,EAAEkC,QAAQ;AAChBgY,IAAAA,MAAM,EAAEzU,gBAAgB;AACxB0U,IAAAA,QAAQ,EAAEzL,kBAAAA;AACZ,GAAC,CAAC,CAAA;EAEF,MAAM0L,SAAS,GAAG,IAAI9a,GAAG,CAAC+a,8BAA8B,CAACT,OAAO,CAAC,CAAC,CAAA;EAElE,SAASU,iBAAiBA,CAACC,eAAe,EAAE;AAC1C,IAAA,OAAO5B,eAAe,GAClB4B,eAAe,GACb,CAAA,EAAGrE,aAAa,CAAU,QAAA,CAAA,GAC1B,CAAGA,EAAAA,aAAa,iBAAiB,GACnCqE,eAAe,GACb,uBAAuB,GACvB,qBAAqB,CAAA;AAC7B,GAAA;AAEA,EAAA,SAASC,qBAAqBA,CAAC5a,IAAY,EAAE6a,KAAK,EAAE;AAClD,IAAA,IAAIjB,oBAAoB,CAAC5Z,IAAI,CAAC,EAAE;MAC9B8Z,KAAK,CAAC9Z,IAAI,CAAC,CAAA;MACX6a,KAAK,CAACC,kBAAkB,CAACjC,YAAY,CAAC7Y,IAAI,CAAC,EAAEA,IAAI,CAAC,CAAA;AAClD,MAAA,OAAO,IAAI,CAAA;AACb,KAAA;AACA,IAAA,OAAO,KAAK,CAAA;AACd,GAAA;EAEA,SAAS+a,iBAAiBA,CAACC,KAAe,EAAEH,KAAK,EAAErB,QAAQ,GAAG,IAAI,EAAE;AAClE,IAAA,KAAK,MAAMxZ,IAAI,IAAIgb,KAAK,EAAE;AACxB,MAAA,IAAIxB,QAAQ,EAAE;QACZF,cAAc,CAACtZ,IAAI,EAAEA,IAAI,IAAI4a,qBAAqB,CAAC5a,IAAI,EAAE6a,KAAK,CAAC,CAAC,CAAA;AAClE,OAAC,MAAM;AACLD,QAAAA,qBAAqB,CAAC5a,IAAI,EAAE6a,KAAK,CAAC,CAAA;AACpC,OAAA;AACF,KAAA;AACF,GAAA;EAEA,SAASI,eAAeA,CACtBtF,IAA8B,EAC9BuF,IAAY,EACZL,KAAkC,EAClCtD,MAAe,EACf;AACA,IAAA,IACE5B,IAAI,CAACxV,IAAI,IACT,EAAEoX,MAAM,IAAI5B,IAAI,CAACtV,OAAO,IAAIsV,IAAI,CAACtV,OAAO,CAACiR,QAAQ,CAACiG,MAAM,CAAC,CAAC,IAC1D+B,cAAc,CAAC3D,IAAI,CAAC3V,IAAI,EAAE4Z,oBAAoB,CAAC,EAC/C;MACA,MAAM;AAAE5Z,QAAAA,IAAAA;AAAK,OAAC,GAAG2V,IAAI,CAAA;MACrB,IAAIgF,eAAe,GAAG,KAAK,CAAA;MAC3B,IAAItF,WAAS,IAAK4E,gBAAgB,IAAIja,IAAI,CAACiT,UAAU,CAAC,SAAS,CAAE,EAAE;AACjE0H,QAAAA,eAAe,GAAG,IAAI,CAAA;AACxB,OAAC,MAAM,IAAI3a,IAAI,CAACiT,UAAU,CAAC,KAAK,CAAC,IAAI,CAACuH,SAAS,CAACvO,GAAG,CAACjM,IAAI,CAAC,EAAE;AACzD2a,QAAAA,eAAe,GAAG,IAAI,CAAA;AACxB,OAAA;MACA,IACE5B,eAAe,IACf,CAAC,CACC4B,eAAe,GACXQ,SAA2B,GAC3BA,MAAwB,EAC5BlP,GAAG,CAAC0J,IAAI,CAACxV,IAAI,CAAC,EAChB;AACA,QAAA,OAAA;AACF,OAAA;AACA,MAAA,MAAMib,cAAc,GAAGV,iBAAiB,CAACC,eAAe,CAAC,CAAA;AACzD,MAAA,OAAOE,KAAK,CAACQ,mBAAmB,CAC9B,GAAGD,cAAc,CAAA,CAAA,EAAIzF,IAAI,CAACxV,IAAI,CAAG6Y,EAAAA,GAAG,CAAE,CAAA,EACtCkC,IACF,CAAC,CAAA;AACH,KAAA;AACF,GAAA;EAEA,SAASI,eAAeA,CAACtb,IAAI,EAAE;AAC7B,IAAA,IAAIA,IAAI,CAACiT,UAAU,CAAC,SAAS,CAAC,EAAE;MAC9B,MAAMsI,MAAM,GAAG,CAAMvb,GAAAA,EAAAA,IAAI,CAAC4S,KAAK,CAAC,CAAC,CAAC,CAAE,CAAA,CAAA;AACpC;AACA;MACA,OAAO2I,MAAM,IAAIzb,gBAAgB,CAAA;AACnC,KAAA;AACA,IAAA,OAAO,IAAI,CAAA;AACb,GAAA;EAEA,OAAO;AACLE,IAAAA,IAAI,EAAE,SAAS;AAEfwb,IAAAA,WAAW,EAAEtB,aAAa,GAAG,IAAI,GAAG5D,aAAa;AAEjDmF,IAAAA,SAAS,EAAE3b,gBAAgB;IAE3B4b,eAAeA,CAAC1b,IAAI,EAAE;MACpB,IAAI,CAACwa,SAAS,CAACvO,GAAG,CAACjM,IAAI,CAAC,EAAE,OAAO,KAAK,CAAA;AACtC,MAAA,IAAIqV,WAAS,IAAIsE,MAAM,KAAK,cAAc,EAAE,OAAO,IAAI,CAAA;MACvD,IAAIM,gBAAgB,IAAI0B,2BAA2B,CAAC1P,GAAG,CAACjM,IAAI,CAAC,EAAE;AAC7D,QAAA,OAAO,IAAI,CAAA;AACb,OAAA;MACA,OAAOsb,eAAe,CAACtb,IAAI,CAAC,CAAA;KAC7B;AAED4b,IAAAA,WAAWA,CAACC,IAAI,EAAEhB,KAAK,EAAEjF,IAAI,EAAE;AAC7B,MAAA,IAAIiG,IAAI,CAACC,IAAI,KAAK,QAAQ,EAAE,OAAA;AAE5B,MAAA,MAAMpb,OAAO,GAAG6X,cAAc,CAACsD,IAAI,CAACrD,MAAM,CAAC,CAAA;MAC3C,IAAI,CAAC9X,OAAO,EAAE,OAAA;MAEd,IACEA,OAAO,CAACwV,MAAM,KAAK,CAAC,IACpB2F,IAAI,CAACrD,MAAM,KAAKK,YAAY,CAACnY,OAAO,CAAC,CAAC,CAAC,CAAC,IACxCkZ,oBAAoB,CAAClZ,OAAO,CAAC,CAAC,CAAC,CAAC,EAChC;AACA;AACA;QACAoZ,KAAK,CAAC,IAAI,CAAC,CAAA;AACX,QAAA,OAAA;AACF,OAAA;AAEA,MAAA,MAAMiC,UAAU,GAAG,IAAIrc,GAAG,CAACgB,OAAO,CAAC,CAAA;AACnC,MAAA,MAAMsb,eAAe,GAAGtb,OAAO,CAACyP,MAAM,CAAC8L,MAAM,IAAI;QAC/C,IAAI,CAACA,MAAM,CAAChJ,UAAU,CAAC,SAAS,CAAC,EAAE,OAAO,IAAI,CAAA;QAC9C,MAAMmC,MAAM,GAAG6G,MAAM,CAAClO,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAA;QAC/C,IAAIgO,UAAU,CAAC9P,GAAG,CAACmJ,MAAM,CAAC,IAAIwE,oBAAoB,CAACxE,MAAM,CAAC,EAAE;AAC1D,UAAA,OAAO,KAAK,CAAA;AACd,SAAA;AACA,QAAA,OAAO,IAAI,CAAA;AACb,OAAC,CAAC,CAAA;AAEF2F,MAAAA,iBAAiB,CAACiB,eAAe,EAAEnB,KAAK,EAAE,KAAK,CAAC,CAAA;MAChDjF,IAAI,CAACsG,MAAM,EAAE,CAAA;KACd;AAEDC,IAAAA,WAAWA,CAACN,IAAI,EAAEhB,KAAK,EAAEjF,IAAI,EAAE;AAC7B,MAAA,MAAMwG,QAAQ,GAAG/B,OAAO,CAACwB,IAAI,CAAC,CAAA;MAC9B,IAAI,CAACO,QAAQ,EAAE,OAAA;MAEf,IAAI1G,eAAe,CAAC0G,QAAQ,CAACzG,IAAI,EAAEC,IAAI,CAAC,EAAE,OAAA;AAE1C,MAAA,IAAIyG,IAAI,GAAGD,QAAQ,CAACzG,IAAI,CAACvV,MAAM,CAAA;AAE/B,MAAA,IACEgc,QAAQ,CAACN,IAAI,KAAK,QAAQ,IAC1B,QAAQ,IAAID,IAAI,IAChBA,IAAI,CAACtE,MAAM,IACXsE,IAAI,CAACS,SAAS,KAAK,WAAW,EAC9B;QACA,MAAMC,GAAG,GAAGV,IAAI,CAACtE,MAAM,CAACkB,WAAW,EAAE,CAAA;AACrC4D,QAAAA,IAAI,GAAGA,IAAI,CAAClM,MAAM,CAACqM,CAAC,IAClBpD,aAAa,CAACrG,IAAI,CAACsG,CAAC,IAAIA,CAAC,CAAC7F,IAAI,CAACgJ,CAAC,CAAC,CAAC,GAAGA,CAAC,CAAClL,QAAQ,CAACiL,GAAG,CAAC,GAAG,IACzD,CAAC,CAAA;AACH,OAAA;AAEAxB,MAAAA,iBAAiB,CAACsB,IAAI,EAAExB,KAAK,CAAC,CAAA;AAE9B,MAAA,OAAO,IAAI,CAAA;KACZ;AAED4B,IAAAA,SAASA,CAACZ,IAAI,EAAEhB,KAAK,EAAEjF,IAAI,EAAE;AAC3B,MAAA,IAAIiG,IAAI,CAACC,IAAI,KAAK,IAAI,EAAE;AACtB,QAAA,IAAID,IAAI,CAACa,GAAG,KAAK,iBAAiB,EAAE;AAClC9G,UAAAA,IAAI,CAACsB,WAAW,CACd3B,CAAC,CAACwB,cAAc,CACd8D,KAAK,CAACQ,mBAAmB,CACvBvC,gBAAgB,CAAC,aAAa,EAAEC,eAAe,EAAEC,GAAG,CAAC,EACrD,YACF,CAAC,EACD,CAAEpD,IAAI,CAACC,IAAI,CAAwB8G,KAAK,CAAC;AAC3C,WACF,CAAC,CAAA;AACH,SAAA;AACA,QAAA,OAAA;AACF,OAAA;AAEA,MAAA,IAAI/G,IAAI,CAACyB,UAAU,CAACuF,iBAAiB,CAAC;AAAEC,QAAAA,QAAQ,EAAE,QAAA;AAAS,OAAC,CAAC,EAAE,OAAA;AAE/D,MAAA,IAAIhB,IAAI,CAACC,IAAI,KAAK,UAAU,EAAE;AAC5B;AACA,QAAA,IAAI,CAAClG,IAAI,CAACkH,kBAAkB,EAAE,IAAI,CAAClH,IAAI,CAACmC,0BAA0B,EAAE,EAAE;AACpE,UAAA,OAAA;AACF,SAAA;AACA,QAAA,IAAI,CAACnC,IAAI,CAACmH,YAAY,EAAE,EAAE,OAAA;AAC1B,QAAA,IAAInH,IAAI,CAACyB,UAAU,CAAC2F,kBAAkB,EAAE,EAAE,OAAA;QAC1C,IAAIzH,CAAC,CAAC0H,OAAO,CAACrH,IAAI,CAACC,IAAI,CAAC0B,MAAM,CAAC,EAAE;AAC/B,UAAA,OAAA;AACF,SAAA;AAEA,QAAA,IAAIsE,IAAI,CAACa,GAAG,KAAK,iBAAiB,EAAE;AAClC,UAAA,IAAI,CAAC9C,oBAAoB,CAAC,oBAAoB,CAAC,EAAE,OAAA;UAEjD,MAAM;YAAE9D,MAAM;AAAED,YAAAA,IAAAA;AAAK,WAAC,GAAGD,IAAI,CAAA;AAC7B,UAAA,IAAIL,CAAC,CAACQ,gBAAgB,CAACD,MAAM,EAAE;AAAEE,YAAAA,MAAM,EAAEH,IAAAA;AAAK,WAAC,CAAC,EAAE;AAChD,YAAA,IAAIC,MAAM,CAACG,SAAS,CAACC,MAAM,KAAK,CAAC,EAAE;AACjCN,cAAAA,IAAI,CAACyB,UAAU,CAACH,WAAW,CACzB3B,CAAC,CAACwB,cAAc,CACd8D,KAAK,CAACQ,mBAAmB,CACvBvC,gBAAgB,CAAC,cAAc,EAAEC,eAAe,EAAEC,GAAG,CAAC,EACtD,aACF,CAAC,EACD,CAACnD,IAAI,CAAC0B,MAAM,CACd,CACF,CAAC,CAAA;cACD3B,IAAI,CAACsH,IAAI,EAAE,CAAA;AACb,aAAC,MAAM;AACL3G,cAAAA,UAAU,CACRX,IAAI,EACJiF,KAAK,CAACQ,mBAAmB,CACvBvC,gBAAgB,CAAC,qBAAqB,EAAEC,eAAe,EAAEC,GAAG,CAAC,EAC7D,mBACF,CACF,CAAC,CAAA;AACH,aAAA;AACF,WAAC,MAAM;AACLpD,YAAAA,IAAI,CAACsB,WAAW,CACd3B,CAAC,CAACwB,cAAc,CACd8D,KAAK,CAACQ,mBAAmB,CACvBvC,gBAAgB,CAAC,qBAAqB,EAAEC,eAAe,EAAEC,GAAG,CAAC,EAC7D,mBACF,CAAC,EACD,CAACpD,IAAI,CAACC,IAAI,CAAC0B,MAAM,CACnB,CACF,CAAC,CAAA;AACH,WAAA;AAEA,UAAA,OAAA;AACF,SAAA;AACF,OAAA;AAEA,MAAA,IAAI6E,QAAQ,GAAG/B,OAAO,CAACwB,IAAI,CAAC,CAAA;MAC5B,IAAI,CAACO,QAAQ,EAAE,OAAA;MAEf,IAAI1G,eAAe,CAAC0G,QAAQ,CAACzG,IAAI,EAAEC,IAAI,CAAC,EAAE,OAAA;MAE1C,IACEmD,eAAe,IACfqD,QAAQ,CAACzG,IAAI,CAACxV,IAAI,IAClBic,QAAQ,CAACzG,IAAI,CAACxV,IAAI,CAACyS,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,QAAQ,EACzC;AACA;AACAwJ,QAAAA,QAAQ,GAAG;AACT,UAAA,GAAGA,QAAQ;AACXzG,UAAAA,IAAI,EAAE;YACJ,GAAGyG,QAAQ,CAACzG,IAAI;AAChBxV,YAAAA,IAAI,EAAEic,QAAQ,CAACzG,IAAI,CAACxV,IAAI,CAACyS,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;AACtC,WAAA;SACD,CAAA;AACH,OAAA;AAEA,MAAA,IAAIwJ,QAAQ,CAACN,IAAI,KAAK,QAAQ,EAAE;AAC9B,QAAA,MAAMtF,EAAE,GAAGyE,eAAe,CAACmB,QAAQ,CAACzG,IAAI,EAAEyG,QAAQ,CAACpc,IAAI,EAAE6a,KAAK,CAAC,CAAA;AAC/D,QAAA,IAAIrE,EAAE,EAAEZ,IAAI,CAACsB,WAAW,CAACV,EAAE,CAAC,CAAA;AAC9B,OAAC,MAAM,IAAI4F,QAAQ,CAACN,IAAI,KAAK,QAAQ,EAAE;AACrC,QAAA,MAAMtF,EAAE,GAAGyE,eAAe,CACxBmB,QAAQ,CAACzG,IAAI,EACbyG,QAAQ,CAACpc,IAAI,EACb6a,KAAK;AACL;QACAgB,IAAI,CAACtE,MACP,CAAC,CAAA;AACD,QAAA,IAAIf,EAAE,EAAE;AACNZ,UAAAA,IAAI,CAACsB,WAAW,CAACV,EAAE,CAAC,CAAA;UACpB,IAAI;AAAEa,YAAAA,UAAAA;AAAW,WAAC,GAAGzB,IAAI,CAAA;UACzB,IACEyB,UAAU,CAACU,0BAA0B,EAAE,IACvCV,UAAU,CAAC8F,wBAAwB,EAAE,EACrC;YACA,GAAG;cACD,MAAMC,mBAAmB,GAAG/F,UAE3B,CAAA;AACD+F,cAAAA,mBAAmB,CAACC,IAAI,GAAGD,mBAAmB,CAACvH,IAAI,CAACwH,IAAI,GACtDhG,UAAU,CAACgG,IAAI,KAAK,0BAA0B,GAC1C,kBAAkB,GAClB,gBAAgB,CAAA;AACtB,cAAA,OAAOD,mBAAmB,CAACvH,IAAI,CAACiC,QAAQ,CAAA;cAExC,CAAC;AAAET,gBAAAA,UAAAA;AAAW,eAAC,GAAGA,UAAU,EAAA;AAC9B,aAAC,QACC,CAACA,UAAU,CAACU,0BAA0B,EAAE,IACtCV,UAAU,CAAC8F,wBAAwB,EAAE,KACvC,CAAC9F,UAAU,CAACxB,IAAI,CAACiC,QAAQ,EAAA;AAE7B,WAAA;AACF,SAAA;AACF,OAAC,MAAM,IAAIsE,QAAQ,CAACN,IAAI,KAAK,UAAU,EAAE;AACvC,QAAA,MAAMtF,EAAE,GAAGyE,eAAe,CACxBmB,QAAQ,CAACzG,IAAI,EACb,CAAA,EAAGyG,QAAQ,CAACpc,IAAI,CAAA,gBAAA,CAAkB,EAClC6a,KAAK;AACL;QACAgB,IAAI,CAACtE,MACP,CAAC,CAAA;QACD,IAAI,CAACf,EAAE,EAAE,OAAA;QAET,MAAM;UAAEX,IAAI;AAAEC,UAAAA,MAAAA;AAAO,SAAC,GAAGF,IAExB,CAAA;AAED,QAAA,IAAIL,CAAC,CAAC4H,wBAAwB,CAACrH,MAAM,CAAC,IAAIA,MAAM,CAACE,MAAM,KAAKH,IAAI,EAAE;AAChE,UAAA,MAAMyH,WAAW,GAAGxH,MAAM,CAACgC,QAAQ,CAAA;AACnChC,UAAAA,MAAM,CAACgC,QAAQ,GAAG,CAACwF,WAAW,CAAA;UAE9B,IAAI,CAACA,WAAW,EAAE;YAChB,MAAMC,KAAK,GAAG3F,oBAAoB,CAChChC,IAAI,CAACkB,KAAK,EACVjB,IACF,CAAC,CAAA;AACD,YAAA,MAAM,CAAC2H,OAAO,EAAEC,QAAQ,CAAC,GAAG5G,mBAAmB,CAAChB,IAAI,EAAED,IAAI,CAACkB,KAAK,CAAC,CAAA;YAEjElB,IAAI,CAACsB,WAAW,CACdqG,KAAK,CACHtE,QAAQ,CAACyE,UAAU,CAACC,GAAG,CAAA;AACvC,qCAAA,EAAuCnH,EAAE,CAAA,CAAA,EAAIgH,OAAO,CAAA,GAAA,EAAMC,QAAQ,CAAA;AAClE,gBAAA,CACc,CACF,CAAC,CAAA;WACF,MAAM,IAAIlI,CAAC,CAACwC,0BAA0B,CAAClC,IAAI,CAAC,EAAE;YAC7C,MAAM0H,KAAK,GAAG3F,oBAAoB,CAAChC,IAAI,CAACkB,KAAK,EAAEjB,IAAI,CAAC,CAAA;YACpDU,UAAU,CAACX,IAAI,EAAEY,EAAE,EAAE,IAAI,EAAE+G,KAAK,CAAC,CAAA;AACnC,WAAC,MAAM;AACLhH,YAAAA,UAAU,CAACX,IAAI,EAAEY,EAAE,EAAE,IAAI,CAAC,CAAA;AAC5B,WAAA;AACF,SAAC,MAAM,IAAIjB,CAAC,CAACQ,gBAAgB,CAACD,MAAM,CAAC,IAAIA,MAAM,CAACE,MAAM,KAAKH,IAAI,EAAE;AAC/DU,UAAAA,UAAU,CAACX,IAAI,EAAEY,EAAE,EAAE,KAAK,CAAC,CAAA;SAC5B,MAAM,IAAIjB,CAAC,CAACwC,0BAA0B,CAAClC,IAAI,CAAC,EAAE;UAC7C,MAAM0H,KAAK,GAAG3F,oBAAoB,CAAChC,IAAI,CAACkB,KAAK,EAAEjB,IAAI,CAAC,CAAA;AACpDD,UAAAA,IAAI,CAACsB,WAAW,CAACqG,KAAK,CAAChI,CAAC,CAACwB,cAAc,CAACP,EAAE,EAAE,CAACX,IAAI,CAAC0B,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;UAC5D,IAAIhC,CAAC,CAACwC,0BAA0B,CAACjC,MAAM,CAAC,EAAEA,MAAM,CAACgC,QAAQ,GAAG,IAAI,CAAA;AAClE,SAAC,MAAM;AACLlC,UAAAA,IAAI,CAACsB,WAAW,CAAC3B,CAAC,CAACwB,cAAc,CAACP,EAAE,EAAE,CAACX,IAAI,CAAC0B,MAAM,CAAC,CAAC,CAAC,CAAA;AACvD,SAAA;AACF,OAAA;KACD;AAEDqG,IAAAA,OAAO,EAAEjE,MAAM,KAAK,cAAc,IAAI;AACpC;MACAkE,cAAcA,CAACjI,IAAgC,EAAE;QAC/C,IAAIA,IAAI,CAAChK,GAAG,CAAC,QAAQ,CAAC,CAACkS,QAAQ,EAAE,EAAE;AACjC,UAAA,MAAMjD,KAAK,GAAGnB,QAAQ,CAAC9D,IAAI,CAAC,CAAA;AAE5B,UAAA,IAAIuE,SAAS,EAAE;AACb;AACAY,YAAAA,iBAAiB,CAAC3Z,gCAAgC,EAAEyZ,KAAK,CAAC,CAAA;AAC5D,WAAC,MAAM;AACLE,YAAAA,iBAAiB,CAAC5Z,mBAAmB,EAAE0Z,KAAK,CAAC,CAAA;AAC/C,WAAA;AACF,SAAA;OACD;AAED;MACAvU,QAAQA,CAACsP,IAA0B,EAAE;AACnC,QAAA,IAAIA,IAAI,CAACC,IAAI,CAACkI,KAAK,EAAE;AACnBhD,UAAAA,iBAAiB,CAAC5Z,mBAAmB,EAAEuY,QAAQ,CAAC9D,IAAI,CAAC,CAAC,CAAA;AACxD,SAAA;OACD;AAED;MACA,6BAA6BoI,CAC3BpI,IAAiD,EACjD;AACAmF,QAAAA,iBAAiB,CAACla,eAAe,EAAE6Y,QAAQ,CAAC9D,IAAI,CAAC,CAAC,CAAA;OACnD;AAED;MACAqI,aAAaA,CAACrI,IAA+B,EAAE;QAC7C,IAAI,CAACA,IAAI,CAACyB,UAAU,CAAC6G,kBAAkB,EAAE,EAAE;AACzCnD,UAAAA,iBAAiB,CAACla,eAAe,EAAE6Y,QAAQ,CAAC9D,IAAI,CAAC,CAAC,CAAA;AACpD,SAAA;OACD;AAED;MACAuI,eAAeA,CAACvI,IAAiC,EAAE;AACjD,QAAA,IAAIA,IAAI,CAACC,IAAI,CAACuI,QAAQ,EAAE;AACtBrD,UAAAA,iBAAiB,CAACla,eAAe,EAAE6Y,QAAQ,CAAC9D,IAAI,CAAC,CAAC,CAAA;AACpD,SAAA;OACD;AAED;MACAyI,KAAKA,CAACzI,IAAuB,EAAE;AAAA,QAAA,IAAA0I,qBAAA,CAAA;QAC7B,MAAMC,aAAa,GACjB,CAAA,CAAAD,qBAAA,GAAA1I,IAAI,CAACC,IAAI,CAAC2I,UAAU,KAApBF,IAAAA,GAAAA,KAAAA,CAAAA,GAAAA,qBAAA,CAAsBpI,MAAM,KAC5BN,IAAI,CAACC,IAAI,CAAC4I,IAAI,CAACA,IAAI,CAAC1L,IAAI,CACtB2L,EAAE,IAAA;AAAA,UAAA,IAAAC,WAAA,CAAA;UAAA,OAAAA,CAAAA,WAAA,GAAKD,EAAE,CAAmBF,UAAU,KAAhCG,IAAAA,GAAAA,KAAAA,CAAAA,GAAAA,WAAA,CAAkCzI,MAAM,CAAA;AAAA,SAChD,CAAC,CAAA;AACH,QAAA,IAAIqI,aAAa,EAAE;AACjBxD,UAAAA,iBAAiB,CAAChZ,6BAA6B,EAAE2X,QAAQ,CAAC9D,IAAI,CAAC,CAAC,CAAA;AAClE,SAAA;AACF,OAAA;AACF,KAAA;GACD,CAAA;AACH,CAAC,CAAC;;;;"} \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-corejs3/lib/babel-runtime-corejs3-paths.js b/node_modules/babel-plugin-polyfill-corejs3/lib/babel-runtime-corejs3-paths.js new file mode 100644 index 0000000000000000000000000000000000000000..dc6c904bebf870769f798de5049f0eb3219cc10c --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs3/lib/babel-runtime-corejs3-paths.js @@ -0,0 +1,10 @@ +"use strict"; + +exports.__esModule = true; +exports.stable = exports.proposals = void 0; +// This file contains the list of paths supported by @babel/runtime-corejs3. +// It must _not_ be edited, as all new features should go through direct +// injection of core-js-pure imports. + +const stable = exports.stable = new Set(["array", "array/from", "array/is-array", "array/of", "clear-immediate", "date/now", "instance/bind", "instance/code-point-at", "instance/concat", "instance/copy-within", "instance/ends-with", "instance/entries", "instance/every", "instance/fill", "instance/filter", "instance/find", "instance/find-index", "instance/flags", "instance/flat", "instance/flat-map", "instance/for-each", "instance/includes", "instance/index-of", "instance/keys", "instance/last-index-of", "instance/map", "instance/pad-end", "instance/pad-start", "instance/reduce", "instance/reduce-right", "instance/repeat", "instance/reverse", "instance/slice", "instance/some", "instance/sort", "instance/splice", "instance/starts-with", "instance/trim", "instance/trim-end", "instance/trim-left", "instance/trim-right", "instance/trim-start", "instance/values", "json/stringify", "map", "math/acosh", "math/asinh", "math/atanh", "math/cbrt", "math/clz32", "math/cosh", "math/expm1", "math/fround", "math/hypot", "math/imul", "math/log10", "math/log1p", "math/log2", "math/sign", "math/sinh", "math/tanh", "math/trunc", "number/epsilon", "number/is-finite", "number/is-integer", "number/is-nan", "number/is-safe-integer", "number/max-safe-integer", "number/min-safe-integer", "number/parse-float", "number/parse-int", "object/assign", "object/create", "object/define-properties", "object/define-property", "object/entries", "object/freeze", "object/from-entries", "object/get-own-property-descriptor", "object/get-own-property-descriptors", "object/get-own-property-names", "object/get-own-property-symbols", "object/get-prototype-of", "object/is", "object/is-extensible", "object/is-frozen", "object/is-sealed", "object/keys", "object/prevent-extensions", "object/seal", "object/set-prototype-of", "object/values", "parse-float", "parse-int", "promise", "queue-microtask", "reflect/apply", "reflect/construct", "reflect/define-property", "reflect/delete-property", "reflect/get", "reflect/get-own-property-descriptor", "reflect/get-prototype-of", "reflect/has", "reflect/is-extensible", "reflect/own-keys", "reflect/prevent-extensions", "reflect/set", "reflect/set-prototype-of", "set", "set-immediate", "set-interval", "set-timeout", "string/from-code-point", "string/raw", "symbol", "symbol/async-iterator", "symbol/for", "symbol/has-instance", "symbol/is-concat-spreadable", "symbol/iterator", "symbol/key-for", "symbol/match", "symbol/replace", "symbol/search", "symbol/species", "symbol/split", "symbol/to-primitive", "symbol/to-string-tag", "symbol/unscopables", "url", "url-search-params", "weak-map", "weak-set"]); +const proposals = exports.proposals = new Set([...stable, "aggregate-error", "composite-key", "composite-symbol", "global-this", "instance/at", "instance/code-points", "instance/match-all", "instance/replace-all", "math/clamp", "math/degrees", "math/deg-per-rad", "math/fscale", "math/iaddh", "math/imulh", "math/isubh", "math/rad-per-deg", "math/radians", "math/scale", "math/seeded-prng", "math/signbit", "math/umulh", "number/from-string", "observable", "reflect/define-metadata", "reflect/delete-metadata", "reflect/get-metadata", "reflect/get-metadata-keys", "reflect/get-own-metadata", "reflect/get-own-metadata-keys", "reflect/has-metadata", "reflect/has-own-metadata", "reflect/metadata", "symbol/dispose", "symbol/observable", "symbol/pattern-match"]); \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-corejs3/lib/built-in-definitions.js b/node_modules/babel-plugin-polyfill-corejs3/lib/built-in-definitions.js new file mode 100644 index 0000000000000000000000000000000000000000..73e4ad6dfae76e0abae6cfa25fe36923e2a57407 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs3/lib/built-in-definitions.js @@ -0,0 +1,474 @@ +"use strict"; + +exports.__esModule = true; +exports.StaticProperties = exports.PromiseDependenciesWithIterators = exports.PromiseDependencies = exports.InstanceProperties = exports.DecoratorMetadataDependencies = exports.CommonIterators = exports.BuiltIns = void 0; +var _data = _interopRequireDefault(require("../core-js-compat/data.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } +const polyfillsOrder = {}; +Object.keys(_data.default).forEach((name, index) => { + polyfillsOrder[name] = index; +}); +const define = (pure, global, name = global[0], exclude) => { + return { + name, + pure, + global: global.sort((a, b) => polyfillsOrder[a] - polyfillsOrder[b]), + exclude + }; +}; +const typed = (...modules) => define(null, [...modules, ...TypedArrayDependencies]); +const ArrayNatureIterators = ["es.array.iterator", "web.dom-collections.iterator"]; +const CommonIterators = exports.CommonIterators = ["es.string.iterator", ...ArrayNatureIterators]; +const ArrayNatureIteratorsWithTag = ["es.object.to-string", ...ArrayNatureIterators]; +const CommonIteratorsWithTag = ["es.object.to-string", ...CommonIterators]; +const ErrorDependencies = ["es.error.cause", "es.error.to-string"]; +const SuppressedErrorDependencies = ["es.suppressed-error.constructor", ...ErrorDependencies]; +const ArrayBufferDependencies = ["es.array-buffer.constructor", "es.array-buffer.slice", "es.data-view", "es.array-buffer.detached", "es.array-buffer.transfer", "es.array-buffer.transfer-to-fixed-length", "es.object.to-string"]; +const TypedArrayDependencies = ["es.typed-array.at", "es.typed-array.copy-within", "es.typed-array.every", "es.typed-array.fill", "es.typed-array.filter", "es.typed-array.find", "es.typed-array.find-index", "es.typed-array.find-last", "es.typed-array.find-last-index", "es.typed-array.for-each", "es.typed-array.includes", "es.typed-array.index-of", "es.typed-array.iterator", "es.typed-array.join", "es.typed-array.last-index-of", "es.typed-array.map", "es.typed-array.reduce", "es.typed-array.reduce-right", "es.typed-array.reverse", "es.typed-array.set", "es.typed-array.slice", "es.typed-array.some", "es.typed-array.sort", "es.typed-array.subarray", "es.typed-array.to-locale-string", "es.typed-array.to-reversed", "es.typed-array.to-sorted", "es.typed-array.to-string", "es.typed-array.with", "es.object.to-string", "es.array.iterator", "esnext.typed-array.filter-reject", "esnext.typed-array.group-by", "esnext.typed-array.to-spliced", "esnext.typed-array.unique-by", ...ArrayBufferDependencies]; +const PromiseDependencies = exports.PromiseDependencies = ["es.promise", "es.object.to-string"]; +const PromiseDependenciesWithIterators = exports.PromiseDependenciesWithIterators = [...PromiseDependencies, ...CommonIterators]; +const SymbolDependencies = ["es.symbol", "es.symbol.description", "es.object.to-string"]; +const MapDependencies = ["es.map", "es.map.get-or-insert", "es.map.get-or-insert-computed", "esnext.map.delete-all", "esnext.map.emplace", "esnext.map.every", "esnext.map.filter", "esnext.map.find", "esnext.map.find-key", "esnext.map.includes", "esnext.map.key-of", "esnext.map.map-keys", "esnext.map.map-values", "esnext.map.merge", "esnext.map.reduce", "esnext.map.some", "esnext.map.update", ...CommonIteratorsWithTag]; +const SetDependencies = ["es.set", "es.set.difference.v2", "es.set.intersection.v2", "es.set.is-disjoint-from.v2", "es.set.is-subset-of.v2", "es.set.is-superset-of.v2", "es.set.symmetric-difference.v2", "es.set.union.v2", "esnext.set.add-all", "esnext.set.delete-all", "esnext.set.difference", "esnext.set.every", "esnext.set.filter", "esnext.set.find", "esnext.set.intersection", "esnext.set.is-disjoint-from", "esnext.set.is-subset-of", "esnext.set.is-superset-of", "esnext.set.join", "esnext.set.map", "esnext.set.reduce", "esnext.set.some", "esnext.set.symmetric-difference", "esnext.set.union", ...CommonIteratorsWithTag]; +const WeakMapDependencies = ["es.weak-map", "es.weak-map.get-or-insert", "es.weak-map.get-or-insert-computed", "esnext.weak-map.delete-all", "esnext.weak-map.emplace", ...CommonIteratorsWithTag]; +const WeakSetDependencies = ["es.weak-set", "esnext.weak-set.add-all", "esnext.weak-set.delete-all", ...CommonIteratorsWithTag]; +const DOMExceptionDependencies = ["web.dom-exception.constructor", "web.dom-exception.stack", "web.dom-exception.to-string-tag", "es.error.to-string"]; +const URLSearchParamsDependencies = ["web.url-search-params", "web.url-search-params.delete", "web.url-search-params.has", "web.url-search-params.size", ...CommonIteratorsWithTag]; +const AsyncIteratorDependencies = ["esnext.async-iterator.constructor", ...PromiseDependencies]; +const AsyncIteratorProblemMethods = ["esnext.async-iterator.every", "esnext.async-iterator.filter", "esnext.async-iterator.find", "esnext.async-iterator.flat-map", "esnext.async-iterator.for-each", "esnext.async-iterator.map", "esnext.async-iterator.reduce", "esnext.async-iterator.some"]; +const IteratorDependencies = ["es.iterator.constructor", "es.object.to-string"]; +const DecoratorMetadataDependencies = exports.DecoratorMetadataDependencies = ["esnext.symbol.metadata", "esnext.function.metadata"]; +const TypedArrayStaticMethods = base => ({ + from: define(null, ["es.typed-array.from", base, ...TypedArrayDependencies]), + fromAsync: define(null, ["esnext.typed-array.from-async", base, ...PromiseDependenciesWithIterators, ...TypedArrayDependencies]), + of: define(null, ["es.typed-array.of", base, ...TypedArrayDependencies]) +}); +const DataViewDependencies = ["es.data-view", ...ArrayBufferDependencies]; +const BuiltIns = exports.BuiltIns = { + AsyncDisposableStack: define("async-disposable-stack/index", ["es.async-disposable-stack.constructor", "es.object.to-string", "es.async-iterator.async-dispose", "es.iterator.dispose", ...PromiseDependencies, ...SuppressedErrorDependencies]), + AsyncIterator: define("async-iterator/index", AsyncIteratorDependencies), + AggregateError: define("aggregate-error", ["es.aggregate-error", ...ErrorDependencies, ...CommonIteratorsWithTag, "es.aggregate-error.cause"]), + ArrayBuffer: define(null, ArrayBufferDependencies), + DataView: define(null, DataViewDependencies), + Date: define(null, ["es.date.to-string"]), + DOMException: define("dom-exception/index", DOMExceptionDependencies), + DisposableStack: define("disposable-stack/index", ["es.disposable-stack.constructor", "es.object.to-string", "es.iterator.dispose", ...SuppressedErrorDependencies]), + Error: define(null, ErrorDependencies), + EvalError: define(null, ErrorDependencies), + Float32Array: typed("es.typed-array.float32-array"), + Float64Array: typed("es.typed-array.float64-array"), + Int8Array: typed("es.typed-array.int8-array"), + Int16Array: typed("es.typed-array.int16-array"), + Int32Array: typed("es.typed-array.int32-array"), + Iterator: define("iterator/index", IteratorDependencies), + Uint8Array: typed("es.typed-array.uint8-array", "es.uint8-array.set-from-base64", "es.uint8-array.set-from-hex", "es.uint8-array.to-base64", "es.uint8-array.to-hex"), + Uint8ClampedArray: typed("es.typed-array.uint8-clamped-array"), + Uint16Array: typed("es.typed-array.uint16-array"), + Uint32Array: typed("es.typed-array.uint32-array"), + Map: define("map/index", MapDependencies), + Number: define(null, ["es.number.constructor"]), + Observable: define("observable/index", ["esnext.observable", "esnext.symbol.observable", "es.object.to-string", ...CommonIteratorsWithTag]), + Promise: define("promise/index", PromiseDependencies), + RangeError: define(null, ErrorDependencies), + ReferenceError: define(null, ErrorDependencies), + Reflect: define(null, ["es.reflect.to-string-tag", "es.object.to-string"]), + RegExp: define(null, ["es.regexp.constructor", "es.regexp.dot-all", "es.regexp.exec", "es.regexp.sticky", "es.regexp.to-string"]), + Set: define("set/index", SetDependencies), + SuppressedError: define("suppressed-error", SuppressedErrorDependencies), + Symbol: define("symbol/index", SymbolDependencies), + SyntaxError: define(null, ErrorDependencies), + TypeError: define(null, ErrorDependencies), + URIError: define(null, ErrorDependencies), + URL: define("url/index", ["web.url", "web.url.to-json", ...URLSearchParamsDependencies]), + URLSearchParams: define("url-search-params/index", URLSearchParamsDependencies), + WeakMap: define("weak-map/index", WeakMapDependencies), + WeakSet: define("weak-set/index", WeakSetDependencies), + atob: define("atob", ["web.atob", ...DOMExceptionDependencies]), + btoa: define("btoa", ["web.btoa", ...DOMExceptionDependencies]), + clearImmediate: define("clear-immediate", ["web.immediate"]), + compositeKey: define("composite-key", ["esnext.composite-key"]), + compositeSymbol: define("composite-symbol", ["esnext.composite-symbol"]), + escape: define("escape", ["es.escape"]), + fetch: define(null, PromiseDependencies), + globalThis: define("global-this", ["es.global-this"]), + parseFloat: define("parse-float", ["es.parse-float"]), + parseInt: define("parse-int", ["es.parse-int"]), + queueMicrotask: define("queue-microtask", ["web.queue-microtask"]), + self: define("self", ["web.self"]), + setImmediate: define("set-immediate", ["web.immediate"]), + setInterval: define("set-interval", ["web.timers"]), + setTimeout: define("set-timeout", ["web.timers"]), + structuredClone: define("structured-clone", ["web.structured-clone", ...DOMExceptionDependencies, "es.array.iterator", "es.object.keys", "es.object.to-string", "es.map", "es.set"]), + unescape: define("unescape", ["es.unescape"]) +}; +const StaticProperties = exports.StaticProperties = { + AsyncIterator: { + from: define("async-iterator/from", ["esnext.async-iterator.from", ...AsyncIteratorDependencies, ...AsyncIteratorProblemMethods, ...CommonIterators]) + }, + Array: { + from: define("array/from", ["es.array.from", "es.string.iterator"]), + fromAsync: define("array/from-async", ["es.array.from-async", ...PromiseDependenciesWithIterators]), + isArray: define("array/is-array", ["es.array.is-array"]), + isTemplateObject: define("array/is-template-object", ["esnext.array.is-template-object"]), + of: define("array/of", ["es.array.of"]) + }, + ArrayBuffer: { + isView: define(null, ["es.array-buffer.is-view"]) + }, + BigInt: { + range: define("bigint/range", ["esnext.bigint.range", "es.object.to-string"]) + }, + Date: { + now: define("date/now", ["es.date.now"]) + }, + Error: { + isError: define("error/is-error", ["es.error.is-error", "es.object.create"]) + }, + Function: { + isCallable: define("function/is-callable", ["esnext.function.is-callable"]), + isConstructor: define("function/is-constructor", ["esnext.function.is-constructor"]) + }, + Iterator: { + concat: define("iterator/concat", ["es.iterator.concat", ...IteratorDependencies, ...CommonIterators]), + from: define("iterator/from", ["es.iterator.from", ...IteratorDependencies, ...CommonIterators]), + range: define("iterator/range", ["esnext.iterator.range", ...IteratorDependencies]), + zip: define("iterator/zip", ["esnext.iterator.zip", ...IteratorDependencies, ...CommonIterators]), + zipKeyed: define("iterator/zip-keyed", ["esnext.iterator.zip-keyed", "es.object.create", "es.reflect.own-keys", ...IteratorDependencies, ...CommonIterators]) + }, + JSON: { + isRawJSON: define("json/is-raw-json", ["es.json.is-raw-json"]), + parse: define("json/parse", ["es.json.parse", "es.object.keys"]), + rawJSON: define("json/raw-json", ["es.json.raw-json", "es.object.create", "es.object.freeze"]), + stringify: define("json/stringify", ["es.json.stringify", "es.date.to-json"]) + }, + Math: { + DEG_PER_RAD: define("math/deg-per-rad", ["esnext.math.deg-per-rad"]), + RAD_PER_DEG: define("math/rad-per-deg", ["esnext.math.rad-per-deg"]), + acosh: define("math/acosh", ["es.math.acosh"]), + asinh: define("math/asinh", ["es.math.asinh"]), + atanh: define("math/atanh", ["es.math.atanh"]), + cbrt: define("math/cbrt", ["es.math.cbrt"]), + clamp: define("math/clamp", ["esnext.math.clamp"]), + clz32: define("math/clz32", ["es.math.clz32"]), + cosh: define("math/cosh", ["es.math.cosh"]), + degrees: define("math/degrees", ["esnext.math.degrees"]), + expm1: define("math/expm1", ["es.math.expm1"]), + fround: define("math/fround", ["es.math.fround"]), + f16round: define("math/f16round", ["es.math.f16round"]), + fscale: define("math/fscale", ["esnext.math.fscale"]), + hypot: define("math/hypot", ["es.math.hypot"]), + iaddh: define("math/iaddh", ["esnext.math.iaddh"]), + imul: define("math/imul", ["es.math.imul"]), + imulh: define("math/imulh", ["esnext.math.imulh"]), + isubh: define("math/isubh", ["esnext.math.isubh"]), + log10: define("math/log10", ["es.math.log10"]), + log1p: define("math/log1p", ["es.math.log1p"]), + log2: define("math/log2", ["es.math.log2"]), + radians: define("math/radians", ["esnext.math.radians"]), + scale: define("math/scale", ["esnext.math.scale"]), + seededPRNG: define("math/seeded-prng", ["esnext.math.seeded-prng"]), + sign: define("math/sign", ["es.math.sign"]), + signbit: define("math/signbit", ["esnext.math.signbit"]), + sinh: define("math/sinh", ["es.math.sinh"]), + sumPrecise: define("math/sum-precise", ["es.math.sum-precise", "es.array.iterator"]), + tanh: define("math/tanh", ["es.math.tanh"]), + trunc: define("math/trunc", ["es.math.trunc"]), + umulh: define("math/umulh", ["esnext.math.umulh"]) + }, + Map: { + from: define("map/from", ["esnext.map.from", ...MapDependencies]), + groupBy: define("map/group-by", ["es.map.group-by", ...MapDependencies]), + keyBy: define("map/key-by", ["esnext.map.key-by", ...MapDependencies]), + of: define("map/of", ["esnext.map.of", ...MapDependencies]) + }, + Number: { + EPSILON: define("number/epsilon", ["es.number.epsilon"]), + MAX_SAFE_INTEGER: define("number/max-safe-integer", ["es.number.max-safe-integer"]), + MIN_SAFE_INTEGER: define("number/min-safe-integer", ["es.number.min-safe-integer"]), + fromString: define("number/from-string", ["esnext.number.from-string"]), + isFinite: define("number/is-finite", ["es.number.is-finite"]), + isInteger: define("number/is-integer", ["es.number.is-integer"]), + isNaN: define("number/is-nan", ["es.number.is-nan"]), + isSafeInteger: define("number/is-safe-integer", ["es.number.is-safe-integer"]), + parseFloat: define("number/parse-float", ["es.number.parse-float"]), + parseInt: define("number/parse-int", ["es.number.parse-int"]), + range: define("number/range", ["esnext.number.range", "es.object.to-string"]) + }, + Object: { + assign: define("object/assign", ["es.object.assign"]), + create: define("object/create", ["es.object.create"]), + defineProperties: define("object/define-properties", ["es.object.define-properties"]), + defineProperty: define("object/define-property", ["es.object.define-property"]), + entries: define("object/entries", ["es.object.entries"]), + freeze: define("object/freeze", ["es.object.freeze"]), + fromEntries: define("object/from-entries", ["es.object.from-entries", "es.array.iterator"]), + getOwnPropertyDescriptor: define("object/get-own-property-descriptor", ["es.object.get-own-property-descriptor"]), + getOwnPropertyDescriptors: define("object/get-own-property-descriptors", ["es.object.get-own-property-descriptors"]), + getOwnPropertyNames: define("object/get-own-property-names", ["es.object.get-own-property-names"]), + getOwnPropertySymbols: define("object/get-own-property-symbols", ["es.symbol"]), + getPrototypeOf: define("object/get-prototype-of", ["es.object.get-prototype-of"]), + groupBy: define("object/group-by", ["es.object.group-by", "es.object.create"]), + hasOwn: define("object/has-own", ["es.object.has-own"]), + is: define("object/is", ["es.object.is"]), + isExtensible: define("object/is-extensible", ["es.object.is-extensible"]), + isFrozen: define("object/is-frozen", ["es.object.is-frozen"]), + isSealed: define("object/is-sealed", ["es.object.is-sealed"]), + keys: define("object/keys", ["es.object.keys"]), + preventExtensions: define("object/prevent-extensions", ["es.object.prevent-extensions"]), + seal: define("object/seal", ["es.object.seal"]), + setPrototypeOf: define("object/set-prototype-of", ["es.object.set-prototype-of"]), + values: define("object/values", ["es.object.values"]) + }, + Promise: { + all: define(null, PromiseDependenciesWithIterators), + allSettled: define("promise/all-settled", ["es.promise.all-settled", ...PromiseDependenciesWithIterators]), + any: define("promise/any", ["es.promise.any", "es.aggregate-error", ...PromiseDependenciesWithIterators]), + race: define(null, PromiseDependenciesWithIterators), + try: define("promise/try", ["es.promise.try", ...PromiseDependencies]), + withResolvers: define("promise/with-resolvers", ["es.promise.with-resolvers", ...PromiseDependencies]) + }, + Reflect: { + apply: define("reflect/apply", ["es.reflect.apply"]), + construct: define("reflect/construct", ["es.reflect.construct"]), + defineMetadata: define("reflect/define-metadata", ["esnext.reflect.define-metadata"]), + defineProperty: define("reflect/define-property", ["es.reflect.define-property"]), + deleteMetadata: define("reflect/delete-metadata", ["esnext.reflect.delete-metadata"]), + deleteProperty: define("reflect/delete-property", ["es.reflect.delete-property"]), + get: define("reflect/get", ["es.reflect.get"]), + getMetadata: define("reflect/get-metadata", ["esnext.reflect.get-metadata"]), + getMetadataKeys: define("reflect/get-metadata-keys", ["esnext.reflect.get-metadata-keys"]), + getOwnMetadata: define("reflect/get-own-metadata", ["esnext.reflect.get-own-metadata"]), + getOwnMetadataKeys: define("reflect/get-own-metadata-keys", ["esnext.reflect.get-own-metadata-keys"]), + getOwnPropertyDescriptor: define("reflect/get-own-property-descriptor", ["es.reflect.get-own-property-descriptor"]), + getPrototypeOf: define("reflect/get-prototype-of", ["es.reflect.get-prototype-of"]), + has: define("reflect/has", ["es.reflect.has"]), + hasMetadata: define("reflect/has-metadata", ["esnext.reflect.has-metadata"]), + hasOwnMetadata: define("reflect/has-own-metadata", ["esnext.reflect.has-own-metadata"]), + isExtensible: define("reflect/is-extensible", ["es.reflect.is-extensible"]), + metadata: define("reflect/metadata", ["esnext.reflect.metadata"]), + ownKeys: define("reflect/own-keys", ["es.reflect.own-keys"]), + preventExtensions: define("reflect/prevent-extensions", ["es.reflect.prevent-extensions"]), + set: define("reflect/set", ["es.reflect.set"]), + setPrototypeOf: define("reflect/set-prototype-of", ["es.reflect.set-prototype-of"]) + }, + RegExp: { + escape: define("regexp/escape", ["es.regexp.escape"]) + }, + Set: { + from: define("set/from", ["esnext.set.from", ...SetDependencies]), + of: define("set/of", ["esnext.set.of", ...SetDependencies]) + }, + String: { + cooked: define("string/cooked", ["esnext.string.cooked"]), + dedent: define("string/dedent", ["esnext.string.dedent", "es.string.from-code-point", "es.weak-map"]), + fromCodePoint: define("string/from-code-point", ["es.string.from-code-point"]), + raw: define("string/raw", ["es.string.raw"]) + }, + Symbol: { + asyncDispose: define("symbol/async-dispose", ["es.symbol.async-dispose", "es.async-iterator.async-dispose"]), + asyncIterator: define("symbol/async-iterator", ["es.symbol.async-iterator"]), + customMatcher: define("symbol/custom-matcher", ["esnext.symbol.custom-matcher"]), + dispose: define("symbol/dispose", ["es.symbol.dispose", "es.iterator.dispose"]), + for: define("symbol/for", [], "es.symbol"), + hasInstance: define("symbol/has-instance", ["es.symbol.has-instance", "es.function.has-instance"]), + isConcatSpreadable: define("symbol/is-concat-spreadable", ["es.symbol.is-concat-spreadable", "es.array.concat"]), + isRegistered: define("symbol/is-registered", ["esnext.symbol.is-registered", "es.symbol"]), + isRegisteredSymbol: define("symbol/is-registered-symbol", ["esnext.symbol.is-registered-symbol", "es.symbol"]), + isWellKnown: define("symbol/is-well-known", ["esnext.symbol.is-well-known", "es.symbol"]), + isWellKnownSymbol: define("symbol/is-well-known-symbol", ["esnext.symbol.is-well-known-symbol", "es.symbol"]), + iterator: define("symbol/iterator", ["es.symbol.iterator", ...CommonIteratorsWithTag]), + keyFor: define("symbol/key-for", [], "es.symbol"), + match: define("symbol/match", ["es.symbol.match", "es.string.match"]), + matcher: define("symbol/matcher", ["esnext.symbol.matcher"]), + matchAll: define("symbol/match-all", ["es.symbol.match-all", "es.string.match-all"]), + metadata: define("symbol/metadata", DecoratorMetadataDependencies), + metadataKey: define("symbol/metadata-key", ["esnext.symbol.metadata-key"]), + observable: define("symbol/observable", ["esnext.symbol.observable"]), + patternMatch: define("symbol/pattern-match", ["esnext.symbol.pattern-match"]), + replace: define("symbol/replace", ["es.symbol.replace", "es.string.replace"]), + search: define("symbol/search", ["es.symbol.search", "es.string.search"]), + species: define("symbol/species", ["es.symbol.species", "es.array.species"]), + split: define("symbol/split", ["es.symbol.split", "es.string.split"]), + toPrimitive: define("symbol/to-primitive", ["es.symbol.to-primitive", "es.date.to-primitive"]), + toStringTag: define("symbol/to-string-tag", ["es.symbol.to-string-tag", "es.object.to-string", "es.math.to-string-tag", "es.json.to-string-tag"]), + unscopables: define("symbol/unscopables", ["es.symbol.unscopables"]) + }, + URL: { + canParse: define("url/can-parse", ["web.url.can-parse", "web.url"]), + parse: define("url/parse", ["web.url.parse", "web.url"]) + }, + WeakMap: { + from: define("weak-map/from", ["esnext.weak-map.from", ...WeakMapDependencies]), + of: define("weak-map/of", ["esnext.weak-map.of", ...WeakMapDependencies]) + }, + WeakSet: { + from: define("weak-set/from", ["esnext.weak-set.from", ...WeakSetDependencies]), + of: define("weak-set/of", ["esnext.weak-set.of", ...WeakSetDependencies]) + }, + Int8Array: TypedArrayStaticMethods("es.typed-array.int8-array"), + Uint8Array: _extends({ + fromBase64: define(null, ["es.uint8-array.from-base64", ...TypedArrayDependencies]), + fromHex: define(null, ["es.uint8-array.from-hex", ...TypedArrayDependencies]) + }, TypedArrayStaticMethods("es.typed-array.uint8-array")), + Uint8ClampedArray: TypedArrayStaticMethods("es.typed-array.uint8-clamped-array"), + Int16Array: TypedArrayStaticMethods("es.typed-array.int16-array"), + Uint16Array: TypedArrayStaticMethods("es.typed-array.uint16-array"), + Int32Array: TypedArrayStaticMethods("es.typed-array.int32-array"), + Uint32Array: TypedArrayStaticMethods("es.typed-array.uint32-array"), + Float32Array: TypedArrayStaticMethods("es.typed-array.float32-array"), + Float64Array: TypedArrayStaticMethods("es.typed-array.float64-array"), + WebAssembly: { + CompileError: define(null, ErrorDependencies), + LinkError: define(null, ErrorDependencies), + RuntimeError: define(null, ErrorDependencies) + } +}; +["AggregateError", "EvalError", "RangeError", "ReferenceError", "SuppressedError", "SyntaxError", "TypeError", "URIError"].forEach(ERROR_SUBCLASS => { + StaticProperties[ERROR_SUBCLASS] = StaticProperties.Error; +}); +const InstanceProperties = exports.InstanceProperties = { + asIndexedPairs: define(null, ["esnext.async-iterator.as-indexed-pairs", ...AsyncIteratorDependencies, "esnext.iterator.as-indexed-pairs", ...IteratorDependencies]), + at: define("instance/at", [ + // TODO: We should introduce overloaded instance methods definition + // Before that is implemented, the `esnext.string.at` must be the first + // In pure mode, the provider resolves the descriptor as a "pure" `esnext.string.at` + // and treats the compat-data of `esnext.string.at` as the compat-data of + // pure import `instance/at`. The first polyfill here should have the lowest corejs + // supported versions. + "esnext.string.at", "es.string.at-alternative", "es.array.at"]), + anchor: define(null, ["es.string.anchor"]), + big: define(null, ["es.string.big"]), + bind: define("instance/bind", ["es.function.bind"]), + blink: define(null, ["es.string.blink"]), + bold: define(null, ["es.string.bold"]), + chunks: define(null, ["esnext.iterator.chunks", ...IteratorDependencies]), + clamp: define("instance/clamp", ["esnext.number.clamp"]), + codePointAt: define("instance/code-point-at", ["es.string.code-point-at"]), + codePoints: define("instance/code-points", ["esnext.string.code-points"]), + concat: define("instance/concat", ["es.array.concat"], undefined, ["String"]), + copyWithin: define("instance/copy-within", ["es.array.copy-within"]), + demethodize: define("instance/demethodize", ["esnext.function.demethodize"]), + description: define(null, ["es.symbol", "es.symbol.description"]), + dotAll: define(null, ["es.regexp.dot-all"]), + drop: define(null, ["es.iterator.drop", ...IteratorDependencies, "esnext.async-iterator.drop", ...AsyncIteratorDependencies]), + endsWith: define("instance/ends-with", ["es.string.ends-with"]), + entries: define("instance/entries", ArrayNatureIteratorsWithTag), + every: define("instance/every", ["es.array.every", "es.iterator.every", ...IteratorDependencies + // TODO: add async iterator dependencies when we support sub-dependencies + // esnext.async-iterator.every depends on es.promise + // but we don't want to pull es.promise when esnext.async-iterator is disabled + // + // "esnext.async-iterator.every", + // ...AsyncIteratorDependencies + ]), + exec: define(null, ["es.regexp.exec"]), + fill: define("instance/fill", ["es.array.fill"]), + filter: define("instance/filter", ["es.array.filter", "es.iterator.filter", ...IteratorDependencies + // "esnext.async-iterator.filter", + ]), + filterReject: define("instance/filter-reject", ["esnext.array.filter-reject"]), + finally: define(null, ["es.promise.finally", ...PromiseDependencies]), + find: define("instance/find", ["es.array.find", "es.iterator.find", ...IteratorDependencies + // "esnext.async-iterator.find", + ]), + findIndex: define("instance/find-index", ["es.array.find-index"]), + findLast: define("instance/find-last", ["es.array.find-last"]), + findLastIndex: define("instance/find-last-index", ["es.array.find-last-index"]), + fixed: define(null, ["es.string.fixed"]), + flags: define("instance/flags", ["es.regexp.flags"]), + flatMap: define("instance/flat-map", ["es.array.flat-map", "es.array.unscopables.flat-map", "es.iterator.flat-map", ...IteratorDependencies + // "esnext.async-iterator.flat-map", + ]), + flat: define("instance/flat", ["es.array.flat", "es.array.unscopables.flat"]), + getFloat16: define(null, ["es.data-view.get-float16", ...DataViewDependencies]), + getUint8Clamped: define(null, ["esnext.data-view.get-uint8-clamped", ...DataViewDependencies]), + getYear: define(null, ["es.date.get-year"]), + group: define("instance/group", ["esnext.array.group"]), + groupBy: define("instance/group-by", ["esnext.array.group-by"]), + groupByToMap: define("instance/group-by-to-map", ["esnext.array.group-by-to-map", "es.map", "es.object.to-string"]), + groupToMap: define("instance/group-to-map", ["esnext.array.group-to-map", "es.map", "es.object.to-string"]), + fontcolor: define(null, ["es.string.fontcolor"]), + fontsize: define(null, ["es.string.fontsize"]), + forEach: define("instance/for-each", ["es.array.for-each", "es.iterator.for-each", ...IteratorDependencies, + // "esnext.async-iterator.for-each", + "web.dom-collections.for-each"]), + includes: define("instance/includes", ["es.array.includes", "es.string.includes"]), + indexed: define(null, ["esnext.async-iterator.indexed", ...AsyncIteratorDependencies, "esnext.iterator.indexed", ...IteratorDependencies]), + indexOf: define("instance/index-of", ["es.array.index-of"]), + isWellFormed: define("instance/is-well-formed", ["es.string.is-well-formed"]), + italics: define(null, ["es.string.italics"]), + join: define(null, ["es.array.join"]), + keys: define("instance/keys", ArrayNatureIteratorsWithTag), + lastIndex: define(null, ["esnext.array.last-index"]), + lastIndexOf: define("instance/last-index-of", ["es.array.last-index-of"]), + lastItem: define(null, ["esnext.array.last-item"]), + link: define(null, ["es.string.link"]), + map: define("instance/map", ["es.array.map", "es.iterator.map", ...IteratorDependencies + // "esnext.async-iterator.map", + ]), + match: define(null, ["es.string.match", "es.regexp.exec"]), + matchAll: define("instance/match-all", ["es.string.match-all", "es.regexp.exec"]), + name: define(null, ["es.function.name"]), + padEnd: define("instance/pad-end", ["es.string.pad-end"]), + padStart: define("instance/pad-start", ["es.string.pad-start"]), + push: define("instance/push", ["es.array.push"]), + reduce: define("instance/reduce", ["es.array.reduce", "es.iterator.reduce", ...IteratorDependencies + // "esnext.async-iterator.reduce", + ]), + reduceRight: define("instance/reduce-right", ["es.array.reduce-right"]), + repeat: define("instance/repeat", ["es.string.repeat"]), + replace: define(null, ["es.string.replace", "es.regexp.exec"]), + replaceAll: define("instance/replace-all", ["es.string.replace-all", "es.string.replace", "es.regexp.exec"]), + reverse: define("instance/reverse", ["es.array.reverse"]), + search: define(null, ["es.string.search", "es.regexp.exec"]), + setFloat16: define(null, ["es.data-view.set-float16", ...DataViewDependencies]), + setUint8Clamped: define(null, ["esnext.data-view.set-uint8-clamped", ...DataViewDependencies]), + setYear: define(null, ["es.date.set-year"]), + slice: define("instance/slice", ["es.array.slice"]), + sliding: define(null, ["esnext.iterator.sliding", ...IteratorDependencies]), + small: define(null, ["es.string.small"]), + some: define("instance/some", ["es.array.some", "es.iterator.some", ...IteratorDependencies + // "esnext.async-iterator.some", + ]), + sort: define("instance/sort", ["es.array.sort"]), + splice: define("instance/splice", ["es.array.splice"]), + split: define(null, ["es.string.split", "es.regexp.exec"]), + startsWith: define("instance/starts-with", ["es.string.starts-with"]), + sticky: define(null, ["es.regexp.sticky"]), + strike: define(null, ["es.string.strike"]), + sub: define(null, ["es.string.sub"]), + substr: define(null, ["es.string.substr"]), + sup: define(null, ["es.string.sup"]), + take: define(null, ["es.iterator.take", ...IteratorDependencies, "esnext.async-iterator.take", ...AsyncIteratorDependencies]), + test: define(null, ["es.regexp.test", "es.regexp.exec"]), + toArray: define(null, ["es.iterator.to-array", ...IteratorDependencies, "esnext.async-iterator.to-array", ...AsyncIteratorDependencies]), + toAsync: define(null, ["esnext.iterator.to-async", ...IteratorDependencies, ...AsyncIteratorDependencies, ...AsyncIteratorProblemMethods]), + toExponential: define(null, ["es.number.to-exponential"]), + toFixed: define(null, ["es.number.to-fixed"]), + toGMTString: define(null, ["es.date.to-gmt-string"]), + toISOString: define(null, ["es.date.to-iso-string"]), + toJSON: define(null, ["es.date.to-json"]), + toPrecision: define(null, ["es.number.to-precision"]), + toReversed: define("instance/to-reversed", ["es.array.to-reversed"]), + toSorted: define("instance/to-sorted", ["es.array.to-sorted", "es.array.sort"]), + toSpliced: define("instance/to-spliced", ["es.array.to-spliced"]), + toString: define(null, ["es.object.to-string", "es.error.to-string", "es.date.to-string", "es.regexp.to-string"]), + toWellFormed: define("instance/to-well-formed", ["es.string.to-well-formed"]), + trim: define("instance/trim", ["es.string.trim"]), + trimEnd: define("instance/trim-end", ["es.string.trim-end"]), + trimLeft: define("instance/trim-left", ["es.string.trim-start"]), + trimRight: define("instance/trim-right", ["es.string.trim-end"]), + trimStart: define("instance/trim-start", ["es.string.trim-start"]), + uniqueBy: define("instance/unique-by", ["esnext.array.unique-by", "es.map"]), + unshift: define("instance/unshift", ["es.array.unshift"]), + unThis: define("instance/un-this", ["esnext.function.un-this"]), + values: define("instance/values", ArrayNatureIteratorsWithTag), + windows: define(null, ["esnext.iterator.windows", ...IteratorDependencies]), + with: define("instance/with", ["es.array.with"]), + __defineGetter__: define(null, ["es.object.define-getter"]), + __defineSetter__: define(null, ["es.object.define-setter"]), + __lookupGetter__: define(null, ["es.object.lookup-getter"]), + __lookupSetter__: define(null, ["es.object.lookup-setter"]), + ["__proto__"]: define(null, ["es.object.proto"]) +}; \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-corejs3/lib/index.js b/node_modules/babel-plugin-polyfill-corejs3/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ae34bf82b58d66d83885ec09dea6399a6daf24b1 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs3/lib/index.js @@ -0,0 +1,309 @@ +"use strict"; + +exports.__esModule = true; +exports.default = void 0; +var _data = _interopRequireDefault(require("../core-js-compat/data.js")); +var _shippedProposals = _interopRequireDefault(require("./shipped-proposals")); +var _getModulesListForTargetVersion = _interopRequireDefault(require("../core-js-compat/get-modules-list-for-target-version.js")); +var _builtInDefinitions = require("./built-in-definitions"); +var BabelRuntimePaths = _interopRequireWildcard(require("./babel-runtime-corejs3-paths")); +var _usageFilters = _interopRequireDefault(require("./usage-filters")); +var _babel = _interopRequireWildcard(require("@babel/core")); +var _utils = require("./utils"); +var _helperDefinePolyfillProvider = _interopRequireDefault(require("@babel/helper-define-polyfill-provider")); +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } +const { + types: t, + template: template +} = _babel.default || _babel; +const presetEnvCompat = "#__secret_key__@babel/preset-env__compatibility"; +const runtimeCompat = "#__secret_key__@babel/runtime__compatibility"; +const uniqueObjects = ["array", "string", "iterator", "async-iterator", "dom-collections"].map(v => new RegExp(`[a-z]*\\.${v}\\..*`)); +const esnextFallback = (name, cb) => { + if (cb(name)) return true; + if (!name.startsWith("es.")) return false; + const fallback = `esnext.${name.slice(3)}`; + if (!_data.default[fallback]) return false; + return cb(fallback); +}; +var _default = exports.default = (0, _helperDefinePolyfillProvider.default)(function ({ + getUtils, + method, + shouldInjectPolyfill, + createMetaResolver, + debug, + babel +}, { + version = 3, + proposals, + shippedProposals, + [presetEnvCompat]: { + noRuntimeName = false + } = {}, + [runtimeCompat]: { + useBabelRuntime = false, + ext = ".js" + } = {} +}) { + const isWebpack = babel.caller(caller => (caller == null ? void 0 : caller.name) === "babel-loader"); + const resolve = createMetaResolver({ + global: _builtInDefinitions.BuiltIns, + static: _builtInDefinitions.StaticProperties, + instance: _builtInDefinitions.InstanceProperties + }); + const available = new Set((0, _getModulesListForTargetVersion.default)(version)); + function getCoreJSPureBase(useProposalBase) { + return useBabelRuntime ? useProposalBase ? `${_utils.BABEL_RUNTIME}/core-js` : `${_utils.BABEL_RUNTIME}/core-js-stable` : useProposalBase ? "core-js-pure/features" : "core-js-pure/stable"; + } + function maybeInjectGlobalImpl(name, utils) { + if (shouldInjectPolyfill(name)) { + debug(name); + utils.injectGlobalImport((0, _utils.coreJSModule)(name), name); + return true; + } + return false; + } + function maybeInjectGlobal(names, utils, fallback = true) { + for (const name of names) { + if (fallback) { + esnextFallback(name, name => maybeInjectGlobalImpl(name, utils)); + } else { + maybeInjectGlobalImpl(name, utils); + } + } + } + function maybeInjectPure(desc, hint, utils, object) { + if (desc.pure && !(object && desc.exclude && desc.exclude.includes(object)) && esnextFallback(desc.name, shouldInjectPolyfill)) { + const { + name + } = desc; + let useProposalBase = false; + if (proposals || shippedProposals && name.startsWith("esnext.")) { + useProposalBase = true; + } else if (name.startsWith("es.") && !available.has(name)) { + useProposalBase = true; + } + if (useBabelRuntime && !(useProposalBase ? BabelRuntimePaths.proposals : BabelRuntimePaths.stable).has(desc.pure)) { + return; + } + const coreJSPureBase = getCoreJSPureBase(useProposalBase); + return utils.injectDefaultImport(`${coreJSPureBase}/${desc.pure}${ext}`, hint); + } + } + function isFeatureStable(name) { + if (name.startsWith("esnext.")) { + const esName = `es.${name.slice(7)}`; + // If its imaginative esName is not in latest compat data, it means + // the proposal is not stage 4 + return esName in _data.default; + } + return true; + } + return { + name: "corejs3", + runtimeName: noRuntimeName ? null : _utils.BABEL_RUNTIME, + polyfills: _data.default, + filterPolyfills(name) { + if (!available.has(name)) return false; + if (proposals || method === "entry-global") return true; + if (shippedProposals && _shippedProposals.default.has(name)) { + return true; + } + return isFeatureStable(name); + }, + entryGlobal(meta, utils, path) { + if (meta.kind !== "import") return; + const modules = (0, _utils.isCoreJSSource)(meta.source); + if (!modules) return; + if (modules.length === 1 && meta.source === (0, _utils.coreJSModule)(modules[0]) && shouldInjectPolyfill(modules[0])) { + // Avoid infinite loop: do not replace imports with a new copy of + // themselves. + debug(null); + return; + } + const modulesSet = new Set(modules); + const filteredModules = modules.filter(module => { + if (!module.startsWith("esnext.")) return true; + const stable = module.replace("esnext.", "es."); + if (modulesSet.has(stable) && shouldInjectPolyfill(stable)) { + return false; + } + return true; + }); + maybeInjectGlobal(filteredModules, utils, false); + path.remove(); + }, + usageGlobal(meta, utils, path) { + const resolved = resolve(meta); + if (!resolved) return; + if ((0, _usageFilters.default)(resolved.desc, path)) return; + let deps = resolved.desc.global; + if (resolved.kind !== "global" && "object" in meta && meta.object && meta.placement === "prototype") { + const low = meta.object.toLowerCase(); + deps = deps.filter(m => uniqueObjects.some(v => v.test(m)) ? m.includes(low) : true); + } + maybeInjectGlobal(deps, utils); + return true; + }, + usagePure(meta, utils, path) { + if (meta.kind === "in") { + if (meta.key === "Symbol.iterator") { + path.replaceWith(t.callExpression(utils.injectDefaultImport((0, _utils.coreJSPureHelper)("is-iterable", useBabelRuntime, ext), "isIterable"), [path.node.right] // meta.kind === "in" narrows this + )); + } + return; + } + if (path.parentPath.isUnaryExpression({ + operator: "delete" + })) return; + if (meta.kind === "property") { + // We can't compile destructuring and updateExpression. + if (!path.isMemberExpression() && !path.isOptionalMemberExpression()) { + return; + } + if (!path.isReferenced()) return; + if (path.parentPath.isUpdateExpression()) return; + if (t.isSuper(path.node.object)) { + return; + } + if (meta.key === "Symbol.iterator") { + if (!shouldInjectPolyfill("es.symbol.iterator")) return; + const { + parent, + node + } = path; + if (t.isCallExpression(parent, { + callee: node + })) { + if (parent.arguments.length === 0) { + path.parentPath.replaceWith(t.callExpression(utils.injectDefaultImport((0, _utils.coreJSPureHelper)("get-iterator", useBabelRuntime, ext), "getIterator"), [node.object])); + path.skip(); + } else { + (0, _utils.callMethod)(path, utils.injectDefaultImport((0, _utils.coreJSPureHelper)("get-iterator-method", useBabelRuntime, ext), "getIteratorMethod")); + } + } else { + path.replaceWith(t.callExpression(utils.injectDefaultImport((0, _utils.coreJSPureHelper)("get-iterator-method", useBabelRuntime, ext), "getIteratorMethod"), [path.node.object])); + } + return; + } + } + let resolved = resolve(meta); + if (!resolved) return; + if ((0, _usageFilters.default)(resolved.desc, path)) return; + if (useBabelRuntime && resolved.desc.pure && resolved.desc.pure.slice(-6) === "/index") { + // Remove /index, since it doesn't exist in @babel/runtime-corejs3s + resolved = _extends({}, resolved, { + desc: _extends({}, resolved.desc, { + pure: resolved.desc.pure.slice(0, -6) + }) + }); + } + if (resolved.kind === "global") { + const id = maybeInjectPure(resolved.desc, resolved.name, utils); + if (id) path.replaceWith(id); + } else if (resolved.kind === "static") { + const id = maybeInjectPure(resolved.desc, resolved.name, utils, + // @ts-expect-error + meta.object); + if (id) { + path.replaceWith(id); + let { + parentPath + } = path; + if (parentPath.isOptionalMemberExpression() || parentPath.isOptionalCallExpression()) { + do { + const parentAsNotOptional = parentPath; + parentAsNotOptional.type = parentAsNotOptional.node.type = parentPath.type === "OptionalMemberExpression" ? "MemberExpression" : "CallExpression"; + delete parentAsNotOptional.node.optional; + ({ + parentPath + } = parentPath); + } while ((parentPath.isOptionalMemberExpression() || parentPath.isOptionalCallExpression()) && !parentPath.node.optional); + } + } + } else if (resolved.kind === "instance") { + const id = maybeInjectPure(resolved.desc, `${resolved.name}InstanceProperty`, utils, + // @ts-expect-error + meta.object); + if (!id) return; + const { + node, + parent + } = path; + if (t.isOptionalCallExpression(parent) && parent.callee === node) { + const wasOptional = parent.optional; + parent.optional = !wasOptional; + if (!wasOptional) { + const check = (0, _utils.extractOptionalCheck)(path.scope, node); + const [thisArg, thisArg2] = (0, _utils.maybeMemoizeContext)(node, path.scope); + path.replaceWith(check(template.expression.ast` + Function.call.bind(${id}(${thisArg}), ${thisArg2}) + `)); + } else if (t.isOptionalMemberExpression(node)) { + const check = (0, _utils.extractOptionalCheck)(path.scope, node); + (0, _utils.callMethod)(path, id, true, check); + } else { + (0, _utils.callMethod)(path, id, true); + } + } else if (t.isCallExpression(parent) && parent.callee === node) { + (0, _utils.callMethod)(path, id, false); + } else if (t.isOptionalMemberExpression(node)) { + const check = (0, _utils.extractOptionalCheck)(path.scope, node); + path.replaceWith(check(t.callExpression(id, [node.object]))); + if (t.isOptionalMemberExpression(parent)) parent.optional = true; + } else { + path.replaceWith(t.callExpression(id, [node.object])); + } + } + }, + visitor: method === "usage-global" && { + // import("foo") + CallExpression(path) { + if (path.get("callee").isImport()) { + const utils = getUtils(path); + if (isWebpack) { + // Webpack uses Promise.all to handle dynamic import. + maybeInjectGlobal(_builtInDefinitions.PromiseDependenciesWithIterators, utils); + } else { + maybeInjectGlobal(_builtInDefinitions.PromiseDependencies, utils); + } + } + }, + // (async function () { }).finally(...) + Function(path) { + if (path.node.async) { + maybeInjectGlobal(_builtInDefinitions.PromiseDependencies, getUtils(path)); + } + }, + // for-of, [a, b] = c + "ForOfStatement|ArrayPattern"(path) { + maybeInjectGlobal(_builtInDefinitions.CommonIterators, getUtils(path)); + }, + // [...spread] + SpreadElement(path) { + if (!path.parentPath.isObjectExpression()) { + maybeInjectGlobal(_builtInDefinitions.CommonIterators, getUtils(path)); + } + }, + // yield* + YieldExpression(path) { + if (path.node.delegate) { + maybeInjectGlobal(_builtInDefinitions.CommonIterators, getUtils(path)); + } + }, + // Decorators metadata + Class(path) { + var _path$node$decorators; + const hasDecorators = ((_path$node$decorators = path.node.decorators) == null ? void 0 : _path$node$decorators.length) || path.node.body.body.some(el => { + var _decorators; + return (_decorators = el.decorators) == null ? void 0 : _decorators.length; + }); + if (hasDecorators) { + maybeInjectGlobal(_builtInDefinitions.DecoratorMetadataDependencies, getUtils(path)); + } + } + } + }; +}); \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-corejs3/lib/shipped-proposals.js b/node_modules/babel-plugin-polyfill-corejs3/lib/shipped-proposals.js new file mode 100644 index 0000000000000000000000000000000000000000..34cefc6d294698a0e7a5dbfac2a2996ca32a86e9 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs3/lib/shipped-proposals.js @@ -0,0 +1,6 @@ +"use strict"; + +exports.__esModule = true; +exports.default = void 0; +// This file is automatically generated by scripts/build-corejs3-shipped-proposals.mjs +var _default = exports.default = new Set(["esnext.array.group", "esnext.array.group-to-map", "esnext.iterator.zip", "esnext.iterator.zip-keyed", "esnext.symbol.metadata"]); \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-corejs3/lib/usage-filters.js b/node_modules/babel-plugin-polyfill-corejs3/lib/usage-filters.js new file mode 100644 index 0000000000000000000000000000000000000000..0a397e60c94239196f3ed5f859c5f99c0ec9406d --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs3/lib/usage-filters.js @@ -0,0 +1,26 @@ +"use strict"; + +exports.__esModule = true; +exports.default = canSkipPolyfill; +var _babel = _interopRequireWildcard(require("@babel/core")); +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +const { + types: t +} = _babel.default || _babel; +function canSkipPolyfill(desc, path) { + const { + node, + parent + } = path; + switch (desc.name) { + case "es.string.split": + { + if (!t.isCallExpression(parent, { + callee: node + })) return false; + if (parent.arguments.length < 1) return true; + const splitter = parent.arguments[0]; + return t.isStringLiteral(splitter) || t.isTemplateLiteral(splitter); + } + } +} \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-corejs3/lib/utils.js b/node_modules/babel-plugin-polyfill-corejs3/lib/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..67c7e79df81d7947cdff588693ba4eec563759f6 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs3/lib/utils.js @@ -0,0 +1,63 @@ +"use strict"; + +exports.__esModule = true; +exports.BABEL_RUNTIME = void 0; +exports.callMethod = callMethod; +exports.coreJSModule = coreJSModule; +exports.coreJSPureHelper = coreJSPureHelper; +exports.extractOptionalCheck = extractOptionalCheck; +exports.isCoreJSSource = isCoreJSSource; +exports.maybeMemoizeContext = maybeMemoizeContext; +var _babel = _interopRequireWildcard(require("@babel/core")); +var _entries = _interopRequireDefault(require("../core-js-compat/entries.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +const { + types: t +} = _babel.default || _babel; +const BABEL_RUNTIME = exports.BABEL_RUNTIME = "@babel/runtime-corejs3"; +function callMethod(path, id, optionalCall, wrapCallee) { + const [context1, context2] = maybeMemoizeContext(path.node, path.scope); + let callee = t.callExpression(id, [context1]); + if (wrapCallee) callee = wrapCallee(callee); + const call = t.identifier("call"); + path.replaceWith(optionalCall ? t.optionalMemberExpression(callee, call, false, true) : t.memberExpression(callee, call)); + path.parentPath.unshiftContainer("arguments", context2); +} +function maybeMemoizeContext(node, scope) { + const { + object + } = node; + let context1, context2; + if (t.isIdentifier(object)) { + context2 = object; + context1 = t.cloneNode(object); + } else { + context2 = scope.generateDeclaredUidIdentifier("context"); + context1 = t.assignmentExpression("=", t.cloneNode(context2), object); + } + return [context1, context2]; +} +function extractOptionalCheck(scope, node) { + let optionalNode = node; + while (!optionalNode.optional && t.isOptionalMemberExpression(optionalNode.object)) { + optionalNode = optionalNode.object; + } + optionalNode.optional = false; + const ctx = scope.generateDeclaredUidIdentifier("context"); + const assign = t.assignmentExpression("=", ctx, optionalNode.object); + optionalNode.object = t.cloneNode(ctx); + return ifNotNullish => t.conditionalExpression(t.binaryExpression("==", assign, t.nullLiteral()), t.unaryExpression("void", t.numericLiteral(0)), ifNotNullish); +} +function isCoreJSSource(source) { + if (typeof source === "string") { + source = source.replace(/\\/g, "/").replace(/(\/(index)?)?(\.js)?$/i, "").toLowerCase(); + } + return Object.prototype.hasOwnProperty.call(_entries.default, source) && _entries.default[source]; +} +function coreJSModule(name) { + return `core-js/modules/${name}.js`; +} +function coreJSPureHelper(name, useBabelRuntime, ext) { + return useBabelRuntime ? `${BABEL_RUNTIME}/core-js/${name}${ext}` : `core-js-pure/features/${name}.js`; +} \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-corejs3/package.json b/node_modules/babel-plugin-polyfill-corejs3/package.json new file mode 100644 index 0000000000000000000000000000000000000000..590a5f61875abc9e4703438421ddd9b8e0ebfa90 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-corejs3/package.json @@ -0,0 +1,49 @@ +{ + "name": "babel-plugin-polyfill-corejs3", + "version": "0.14.2", + "description": "A Babel plugin to inject imports to core-js@3 polyfills", + "repository": { + "type": "git", + "url": "https://github.com/babel/babel-polyfills.git", + "directory": "packages/babel-plugin-polyfill-corejs3" + }, + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "main": "lib/index.js", + "exports": { + ".": [ + { + "import": "./esm/index.mjs", + "default": "./lib/index.js" + }, + "./lib/index.js" + ], + "./package.json": "./package.json" + }, + "keywords": [ + "babel-plugin" + ], + "dependencies": { + "@babel/helper-define-polyfill-provider": "^0.6.8", + "core-js-compat": "^3.48.0" + }, + "devDependencies": { + "@babel/core": "^7.28.6", + "@babel/helper-plugin-test-runner": "^7.27.1", + "@babel/plugin-proposal-decorators": "^7.28.6", + "@babel/plugin-transform-class-properties": "^7.28.6", + "@babel/plugin-transform-classes": "^7.28.6", + "@babel/plugin-transform-for-of": "^7.27.1", + "@babel/plugin-transform-modules-commonjs": "^7.28.6", + "@babel/plugin-transform-runtime": "^7.28.5", + "@babel/plugin-transform-spread": "^7.28.6", + "core-js": "^3.48.0", + "core-js-pure": "^3.48.0" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + }, + "gitHead": "86eff78e98adc17cdf0eb9ba4d94140eb7cb0da0" +} \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-regenerator/LICENSE b/node_modules/babel-plugin-polyfill-regenerator/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b74971fede812cae3d1b3d7db474db739fac2d53 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-regenerator/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Nicolò Ribaudo and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/babel-plugin-polyfill-regenerator/README.md b/node_modules/babel-plugin-polyfill-regenerator/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e40b692e6e395c500a60510843ed4d07a9cc0089 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-regenerator/README.md @@ -0,0 +1,28 @@ +# babel-plugin-polyfill-regenerator + +## Install + +Using npm: + +```sh +npm install --save-dev babel-plugin-polyfill-regenerator +``` + +or using yarn: + +```sh +yarn add babel-plugin-polyfill-regenerator --dev +``` + +## Usage + +Add this plugin to your Babel configuration: + +```json +{ + "plugins": [["polyfill-regenerator", { "method": "usage-global" }]] +} +``` + +This package supports the `usage-pure`, `usage-global`, and `entry-global` methods. +When `entry-global` is used, it replaces imports to `regenerator-runtime`. diff --git a/node_modules/babel-plugin-polyfill-regenerator/esm/index.mjs b/node_modules/babel-plugin-polyfill-regenerator/esm/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bfaf2150eaf5fe8eaf244f3dfa65c6f1f3e9069a --- /dev/null +++ b/node_modules/babel-plugin-polyfill-regenerator/esm/index.mjs @@ -0,0 +1,46 @@ +import defineProvider from '@babel/helper-define-polyfill-provider'; + +const runtimeCompat = "#__secret_key__@babel/runtime__compatibility"; +var index = defineProvider(({ + debug, + targets, + babel +}, options) => { + if (!shallowEqual(targets, babel.targets())) { + throw new Error("This plugin does not use the targets option. Only preset-env's targets" + " or top-level targets need to be configured for this plugin to work." + " See https://github.com/babel/babel-polyfills/issues/36 for more" + " details."); + } + const { + [runtimeCompat]: { + moduleName = null, + useBabelRuntime = false + } = {} + } = options; + return { + name: "regenerator", + polyfills: ["regenerator-runtime"], + usageGlobal(meta, utils) { + if (isRegenerator(meta)) { + debug("regenerator-runtime"); + utils.injectGlobalImport("regenerator-runtime/runtime.js"); + } + }, + usagePure(meta, utils, path) { + if (isRegenerator(meta)) { + let pureName = "regenerator-runtime"; + if (useBabelRuntime) { + var _ref; + const runtimeName = (_ref = moduleName != null ? moduleName : path.hub.file.get("runtimeHelpersModuleName")) != null ? _ref : "@babel/runtime"; + pureName = `${runtimeName}/regenerator`; + } + path.replaceWith(utils.injectDefaultImport(pureName, "regenerator-runtime")); + } + } + }; +}); +const isRegenerator = meta => meta.kind === "global" && meta.name === "regeneratorRuntime"; +function shallowEqual(obj1, obj2) { + return JSON.stringify(obj1) === JSON.stringify(obj2); +} + +export { index as default }; +//# sourceMappingURL=index.mjs.map diff --git a/node_modules/babel-plugin-polyfill-regenerator/esm/index.mjs.map b/node_modules/babel-plugin-polyfill-regenerator/esm/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..28c7e8f1fd42feac66a02fcda7c55381940c8271 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-regenerator/esm/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sources":["../src/index.ts"],"sourcesContent":["import defineProvider from \"@babel/helper-define-polyfill-provider\";\nimport type { PluginPass } from \"@babel/core\";\n\nconst runtimeCompat = \"#__secret_key__@babel/runtime__compatibility\";\n\ntype Options = {\n \"#__secret_key__@babel/runtime__compatibility\": void | {\n useBabelRuntime: boolean;\n moduleName: string;\n };\n};\n\nexport default defineProvider(({ debug, targets, babel }, options) => {\n if (!shallowEqual(targets, babel.targets())) {\n throw new Error(\n \"This plugin does not use the targets option. Only preset-env's targets\" +\n \" or top-level targets need to be configured for this plugin to work.\" +\n \" See https://github.com/babel/babel-polyfills/issues/36 for more\" +\n \" details.\",\n );\n }\n\n const {\n [runtimeCompat]: { moduleName = null, useBabelRuntime = false } = {},\n } = options;\n\n return {\n name: \"regenerator\",\n\n polyfills: [\"regenerator-runtime\"],\n\n usageGlobal(meta, utils): undefined {\n if (isRegenerator(meta)) {\n debug(\"regenerator-runtime\");\n utils.injectGlobalImport(\"regenerator-runtime/runtime.js\");\n }\n },\n usagePure(meta, utils, path) {\n if (isRegenerator(meta)) {\n let pureName = \"regenerator-runtime\";\n if (useBabelRuntime) {\n const runtimeName =\n moduleName ??\n ((path.hub as any).file as PluginPass).get(\n \"runtimeHelpersModuleName\",\n ) ??\n \"@babel/runtime\";\n pureName = `${runtimeName}/regenerator`;\n }\n\n path.replaceWith(\n utils.injectDefaultImport(pureName, \"regenerator-runtime\"),\n );\n }\n },\n };\n});\n\nconst isRegenerator = meta =>\n meta.kind === \"global\" && meta.name === \"regeneratorRuntime\";\n\nfunction shallowEqual(obj1: any, obj2: any) {\n return JSON.stringify(obj1) === JSON.stringify(obj2);\n}\n"],"names":["runtimeCompat","defineProvider","debug","targets","babel","options","shallowEqual","Error","moduleName","useBabelRuntime","name","polyfills","usageGlobal","meta","utils","isRegenerator","injectGlobalImport","usagePure","path","pureName","_ref","runtimeName","hub","file","get","replaceWith","injectDefaultImport","kind","obj1","obj2","JSON","stringify"],"mappings":";;AAGA,MAAMA,aAAa,GAAG,8CAA8C,CAAA;AASpE,YAAeC,cAAc,CAAU,CAAC;EAAEC,KAAK;EAAEC,OAAO;AAAEC,EAAAA,KAAAA;AAAM,CAAC,EAAEC,OAAO,KAAK;EAC7E,IAAI,CAACC,YAAY,CAACH,OAAO,EAAEC,KAAK,CAACD,OAAO,EAAE,CAAC,EAAE;IAC3C,MAAM,IAAII,KAAK,CACb,wEAAwE,GACtE,sEAAsE,GACtE,kEAAkE,GAClE,WACJ,CAAC,CAAA;AACH,GAAA;EAEA,MAAM;AACJ,IAAA,CAACP,aAAa,GAAG;AAAEQ,MAAAA,UAAU,GAAG,IAAI;AAAEC,MAAAA,eAAe,GAAG,KAAA;AAAM,KAAC,GAAG,EAAC;AACrE,GAAC,GAAGJ,OAAO,CAAA;EAEX,OAAO;AACLK,IAAAA,IAAI,EAAE,aAAa;IAEnBC,SAAS,EAAE,CAAC,qBAAqB,CAAC;AAElCC,IAAAA,WAAWA,CAACC,IAAI,EAAEC,KAAK,EAAa;AAClC,MAAA,IAAIC,aAAa,CAACF,IAAI,CAAC,EAAE;QACvBX,KAAK,CAAC,qBAAqB,CAAC,CAAA;AAC5BY,QAAAA,KAAK,CAACE,kBAAkB,CAAC,gCAAgC,CAAC,CAAA;AAC5D,OAAA;KACD;AACDC,IAAAA,SAASA,CAACJ,IAAI,EAAEC,KAAK,EAAEI,IAAI,EAAE;AAC3B,MAAA,IAAIH,aAAa,CAACF,IAAI,CAAC,EAAE;QACvB,IAAIM,QAAQ,GAAG,qBAAqB,CAAA;AACpC,QAAA,IAAIV,eAAe,EAAE;AAAA,UAAA,IAAAW,IAAA,CAAA;UACnB,MAAMC,WAAW,IAAAD,IAAA,GACfZ,UAAU,IAAVA,IAAAA,GAAAA,UAAU,GACRU,IAAI,CAACI,GAAG,CAASC,IAAI,CAAgBC,GAAG,CACxC,0BACF,CAAC,KAAA,IAAA,GAAAJ,IAAA,GACD,gBAAgB,CAAA;UAClBD,QAAQ,GAAG,CAAGE,EAAAA,WAAW,CAAc,YAAA,CAAA,CAAA;AACzC,SAAA;QAEAH,IAAI,CAACO,WAAW,CACdX,KAAK,CAACY,mBAAmB,CAACP,QAAQ,EAAE,qBAAqB,CAC3D,CAAC,CAAA;AACH,OAAA;AACF,KAAA;GACD,CAAA;AACH,CAAC,CAAC,CAAA;AAEF,MAAMJ,aAAa,GAAGF,IAAI,IACxBA,IAAI,CAACc,IAAI,KAAK,QAAQ,IAAId,IAAI,CAACH,IAAI,KAAK,oBAAoB,CAAA;AAE9D,SAASJ,YAAYA,CAACsB,IAAS,EAAEC,IAAS,EAAE;AAC1C,EAAA,OAAOC,IAAI,CAACC,SAAS,CAACH,IAAI,CAAC,KAAKE,IAAI,CAACC,SAAS,CAACF,IAAI,CAAC,CAAA;AACtD;;;;"} \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-regenerator/lib/index.js b/node_modules/babel-plugin-polyfill-regenerator/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bee8bfa246d68d71e5b8dda486d0a080ab3fe9cc --- /dev/null +++ b/node_modules/babel-plugin-polyfill-regenerator/lib/index.js @@ -0,0 +1,47 @@ +"use strict"; + +exports.__esModule = true; +exports.default = void 0; +var _helperDefinePolyfillProvider = _interopRequireDefault(require("@babel/helper-define-polyfill-provider")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +const runtimeCompat = "#__secret_key__@babel/runtime__compatibility"; +var _default = exports.default = (0, _helperDefinePolyfillProvider.default)(({ + debug, + targets, + babel +}, options) => { + if (!shallowEqual(targets, babel.targets())) { + throw new Error("This plugin does not use the targets option. Only preset-env's targets" + " or top-level targets need to be configured for this plugin to work." + " See https://github.com/babel/babel-polyfills/issues/36 for more" + " details."); + } + const { + [runtimeCompat]: { + moduleName = null, + useBabelRuntime = false + } = {} + } = options; + return { + name: "regenerator", + polyfills: ["regenerator-runtime"], + usageGlobal(meta, utils) { + if (isRegenerator(meta)) { + debug("regenerator-runtime"); + utils.injectGlobalImport("regenerator-runtime/runtime.js"); + } + }, + usagePure(meta, utils, path) { + if (isRegenerator(meta)) { + let pureName = "regenerator-runtime"; + if (useBabelRuntime) { + var _ref; + const runtimeName = (_ref = moduleName != null ? moduleName : path.hub.file.get("runtimeHelpersModuleName")) != null ? _ref : "@babel/runtime"; + pureName = `${runtimeName}/regenerator`; + } + path.replaceWith(utils.injectDefaultImport(pureName, "regenerator-runtime")); + } + } + }; +}); +const isRegenerator = meta => meta.kind === "global" && meta.name === "regeneratorRuntime"; +function shallowEqual(obj1, obj2) { + return JSON.stringify(obj1) === JSON.stringify(obj2); +} \ No newline at end of file diff --git a/node_modules/babel-plugin-polyfill-regenerator/package.json b/node_modules/babel-plugin-polyfill-regenerator/package.json new file mode 100644 index 0000000000000000000000000000000000000000..937b5557a03ea9680cc0c2f517dfe053800f2970 --- /dev/null +++ b/node_modules/babel-plugin-polyfill-regenerator/package.json @@ -0,0 +1,41 @@ +{ + "name": "babel-plugin-polyfill-regenerator", + "version": "0.6.8", + "description": "A Babel plugin to inject imports to regenerator-runtime", + "repository": { + "type": "git", + "url": "https://github.com/babel/babel-polyfills.git", + "directory": "packages/babel-plugin-polyfill-regenerator" + }, + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "main": "lib/index.js", + "exports": { + ".": [ + { + "import": "./esm/index.mjs", + "default": "./lib/index.js" + }, + "./lib/index.js" + ], + "./package.json": "./package.json" + }, + "keywords": [ + "babel-plugin" + ], + "dependencies": { + "@babel/helper-define-polyfill-provider": "^0.6.8" + }, + "devDependencies": { + "@babel/core": "^7.28.6", + "@babel/helper-plugin-test-runner": "^7.27.1", + "@babel/plugin-transform-regenerator": "~7.14.5", + "regenerator-runtime": "^0.14.1" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + }, + "gitHead": "86eff78e98adc17cdf0eb9ba4d94140eb7cb0da0" +} \ No newline at end of file diff --git a/node_modules/bail/index.d.ts b/node_modules/bail/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..88fe9aa699939acb8b7ce087cd3f6cc6d41fe0b8 --- /dev/null +++ b/node_modules/bail/index.d.ts @@ -0,0 +1,10 @@ +/** + * Throw a given error. + * + * @param {Error|null|undefined} [error] + * Maybe error. + * @returns {asserts error is null|undefined} + */ +export function bail( + error?: Error | null | undefined +): asserts error is null | undefined diff --git a/node_modules/bail/index.js b/node_modules/bail/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d0bc4424c8cebe77d2fe92aa7dc7a4bd9ffc061f --- /dev/null +++ b/node_modules/bail/index.js @@ -0,0 +1,12 @@ +/** + * Throw a given error. + * + * @param {Error|null|undefined} [error] + * Maybe error. + * @returns {asserts error is null|undefined} + */ +export function bail(error) { + if (error) { + throw error + } +} diff --git a/node_modules/bail/license b/node_modules/bail/license new file mode 100644 index 0000000000000000000000000000000000000000..32e7a3d93ca5a2b8cce57405841a44e78f3fbb55 --- /dev/null +++ b/node_modules/bail/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2015 Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/bail/package.json b/node_modules/bail/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d56f6faf0f0e2fd66a1f5eb0ccaf33d444f8ef2b --- /dev/null +++ b/node_modules/bail/package.json @@ -0,0 +1,73 @@ +{ + "name": "bail", + "version": "2.0.2", + "description": "Throw a given error", + "license": "MIT", + "keywords": [ + "fail", + "bail", + "throw", + "callback", + "error" + ], + "repository": "wooorm/bail", + "bugs": "https://github.com/wooorm/bail/issues", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + }, + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "main": "index.js", + "types": "index.d.ts", + "files": [ + "index.d.ts", + "index.js" + ], + "devDependencies": { + "@types/tape": "^4.0.0", + "c8": "^7.0.0", + "prettier": "^2.0.0", + "remark-cli": "^10.0.0", + "remark-preset-wooorm": "^9.0.0", + "rimraf": "^3.0.0", + "tape": "^5.0.0", + "tsd": "^0.18.0", + "type-coverage": "^2.0.0", + "typescript": "^4.0.0", + "xo": "^0.46.0" + }, + "scripts": { + "prepublishOnly": "npm run build && npm run format", + "build": "rimraf \"*.d.ts\" && tsc && tsd && type-coverage", + "format": "remark . -qfo && prettier . -w --loglevel warn && xo --fix", + "test-api": "node --conditions development test.js", + "test-coverage": "c8 --check-coverage --branches 100 --functions 100 --lines 100 --statements 100 --reporter lcov npm run test-api", + "test": "npm run build && npm run format && npm run test-coverage" + }, + "prettier": { + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "bracketSpacing": false, + "semi": false, + "trailingComma": "none" + }, + "xo": { + "prettier": true + }, + "remarkConfig": { + "plugins": [ + "preset-wooorm" + ] + }, + "typeCoverage": { + "atLeast": 100, + "detail": true, + "strict": true + } +} diff --git a/node_modules/bail/readme.md b/node_modules/bail/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..8cd18235efa0a7c81e7510f28f40376492b27f8b --- /dev/null +++ b/node_modules/bail/readme.md @@ -0,0 +1,147 @@ +# bail + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] + +Throw if given an error. + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`bail(err?)`](#bailerr) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Related](#related) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package throws a given error. + +## When should I use this? + +Use this package if you’re building some scripts that might theoretically get +errors but frequently don’t and you keep writing `if (error) throw error` over +and over again and you’re just really done with that. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 12.20+, 14.14+, or 16.0+), install with [npm][]: + +```sh +npm install bail +``` + +In Deno with [Skypack][]: + +```js +import {bail} from 'https://cdn.skypack.dev/bail@2?dts' +``` + +In browsers with [Skypack][]: + +```html + +``` + +## Use + +```js +import {bail} from 'bail' + +bail() + +bail(new Error('failure')) +// Error: failure +// at repl:1:6 +// at REPLServer.defaultEval (repl.js:154:27) +// … +``` + +## API + +This package exports the following identifier: `bail`. +There is no default export. + +### `bail(err?)` + +Throw a given error (`Error?`). + +## Types + +This package is fully typed with [TypeScript][]. +There are no extra exported types. + +## Compatibility + +This package is at least compatible with all maintained versions of Node.js. +As of now, that is Node.js 12.20+, 14.14+, and 16.0+. +It also works in Deno and modern browsers. + +## Security + +This package is safe. + +## Related + +* [`noop`][noop] +* [`noop2`][noop2] +* [`noop3`][noop3] + +## Contribute + +Yes please! +See [How to Contribute to Open Source][contribute]. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/wooorm/bail/workflows/main/badge.svg + +[build]: https://github.com/wooorm/bail/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/bail.svg + +[coverage]: https://codecov.io/github/wooorm/bail + +[downloads-badge]: https://img.shields.io/npm/dm/bail.svg + +[downloads]: https://www.npmjs.com/package/bail + +[size-badge]: https://img.shields.io/bundlephobia/minzip/bail.svg + +[size]: https://bundlephobia.com/result?p=bail + +[npm]: https://docs.npmjs.com/cli/install + +[skypack]: https://www.skypack.dev + +[license]: license + +[author]: https://wooorm.com + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[typescript]: https://www.typescriptlang.org + +[contribute]: https://opensource.guide/how-to-contribute/ + +[noop]: https://www.npmjs.com/package/noop + +[noop2]: https://www.npmjs.com/package/noop2 + +[noop3]: https://www.npmjs.com/package/noop3 diff --git a/node_modules/balanced-match/.github/FUNDING.yml b/node_modules/balanced-match/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..cea8b16e9edc40b78b839e97f7d4b174ada0b41f --- /dev/null +++ b/node_modules/balanced-match/.github/FUNDING.yml @@ -0,0 +1,2 @@ +tidelift: "npm/balanced-match" +patreon: juliangruber diff --git a/node_modules/balanced-match/LICENSE.md b/node_modules/balanced-match/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..2cdc8e4148cc0aa1f788b25dbec4b22878644cdf --- /dev/null +++ b/node_modules/balanced-match/LICENSE.md @@ -0,0 +1,21 @@ +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/balanced-match/README.md b/node_modules/balanced-match/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d2a48b6b49f2cf17358262f911b997121d1c2a31 --- /dev/null +++ b/node_modules/balanced-match/README.md @@ -0,0 +1,97 @@ +# balanced-match + +Match balanced string pairs, like `{` and `}` or `` and ``. Supports regular expressions as well! + +[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) +[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) + +[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) + +## Example + +Get the first matching pair of braces: + +```js +var balanced = require('balanced-match'); + +console.log(balanced('{', '}', 'pre{in{nested}}post')); +console.log(balanced('{', '}', 'pre{first}between{second}post')); +console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); +``` + +The matches are: + +```bash +$ node example.js +{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } +{ start: 3, + end: 9, + pre: 'pre', + body: 'first', + post: 'between{second}post' } +{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } +``` + +## API + +### var m = balanced(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +object with those keys: + +* **start** the index of the first match of `a` +* **end** the index of the matching `b` +* **pre** the preamble, `a` and `b` not included +* **body** the match, `a` and `b` not included +* **post** the postscript, `a` and `b` not included + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. + +### var r = balanced.range(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +array with indexes: `[ , ]`. + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install balanced-match +``` + +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/balanced-match/index.js b/node_modules/balanced-match/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c67a64608df7f4d8e126c0a8eff2cc4a3d837e71 --- /dev/null +++ b/node_modules/balanced-match/index.js @@ -0,0 +1,62 @@ +'use strict'; +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} diff --git a/node_modules/balanced-match/package.json b/node_modules/balanced-match/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ce6073e0403b5a9aeef19a91624ad0256f5e61b8 --- /dev/null +++ b/node_modules/balanced-match/package.json @@ -0,0 +1,48 @@ +{ + "name": "balanced-match", + "description": "Match balanced character pairs, like \"{\" and \"}\"", + "version": "1.0.2", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/balanced-match.git" + }, + "homepage": "https://github.com/juliangruber/balanced-match", + "main": "index.js", + "scripts": { + "test": "tape test/test.js", + "bench": "matcha test/bench.js" + }, + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "keywords": [ + "match", + "regexp", + "test", + "balanced", + "parse" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/node_modules/bare-events/LICENSE b/node_modules/bare-events/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/node_modules/bare-events/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/bare-events/README.md b/node_modules/bare-events/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f56b4593c1e8619ac676d44151a937ae23e77016 --- /dev/null +++ b/node_modules/bare-events/README.md @@ -0,0 +1,25 @@ +# bare-events + +Event emitters for JavaScript. + +``` +npm install bare-events +``` + +## Usage + +```js +const EventEmitter = require('bare-events') + +const e = new EventEmitter() + +e.on('hello', function (data) { + console.log(data) +}) + +e.emit('hello', 'world') +``` + +## License + +Apache-2.0 diff --git a/node_modules/bare-events/global.d.ts b/node_modules/bare-events/global.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..92ea0d6e92ae0817c4ae3f1c8e9eb03ce9e453e9 --- /dev/null +++ b/node_modules/bare-events/global.d.ts @@ -0,0 +1,15 @@ +import * as events from './web' + +type EventConstructor = typeof events.Event +type CustomEventConstructor = typeof events.CustomEvent +type EventTargetConstructor = typeof events.EventTarget + +declare global { + type Event = events.Event + type CustomEvent = events.CustomEvent + type EventTarget = events.EventTarget + + const Event: EventConstructor + const CustomEvent: CustomEventConstructor + const EventTarget: EventTargetConstructor +} diff --git a/node_modules/bare-events/global.js b/node_modules/bare-events/global.js new file mode 100644 index 0000000000000000000000000000000000000000..d8caa0bf47fcb26c789f7e61205ea10869f3c393 --- /dev/null +++ b/node_modules/bare-events/global.js @@ -0,0 +1,5 @@ +const events = require('./web') + +global.Event = events.Event +global.CustomEvent = events.CustomEvent +global.EventTarget = events.EventTarget diff --git a/node_modules/bare-events/index.d.ts b/node_modules/bare-events/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a59b564e9b35d9c17adbddfe6feb47fb2876e58 --- /dev/null +++ b/node_modules/bare-events/index.d.ts @@ -0,0 +1,85 @@ +import { AbortSignal } from 'bare-abort-controller' + +interface EventMap { + [event: string | symbol]: unknown[] +} + +interface EventHandler { + (...args: A): R +} + +declare class EventEmitterError extends Error { + static OPERATION_ABORTED(cause: Error, msg?: string): EventEmitterError + static UNHANDLED_ERROR(cause: Error, msg?: string): EventEmitterError +} + +interface EventEmitter { + addListener(name: E, fn: EventHandler): this + + addOnceListener(name: E, fn: EventHandler): this + + prependListener(name: E, fn: EventHandler): this + + prependOnceListener(name: E, fn: EventHandler): this + + removeListener(name: E, fn: EventHandler): this + + removeAllListeners(name?: E): this + + on(name: E, fn: EventHandler): this + + once(name: E, fn: EventHandler): this + + off(name: E, fn: EventHandler): this + + emit(name: E, ...args: M[E]): boolean + + listeners(name: E): EventHandler + + rawListeners(name: E): EventHandler[] + + eventNames(): (keyof M)[] + + listenerCount(name: E): number + + getMaxListeners(): number + setMaxListeners(n: number): void +} + +declare class EventEmitter {} + +declare namespace EventEmitter { + export function on( + emitter: EventEmitter, + name: E, + opts?: { signal?: AbortSignal } + ): AsyncIterableIterator + + export function once( + emitter: EventEmitter, + name: E, + opts?: { signal?: AbortSignal } + ): Promise + + export function forward>( + from: EventEmitter, + to: EventEmitter, + names: E | E[], + opts?: { emit?: (name: E, ...args: T[E]) => void } + ): void + + export function listenerCount( + emitter: EventEmitter, + name: E + ): number + + export function getMaxListeners(emitter: EventEmitter): number + + export function setMaxListeners(n: number, ...emitters: EventEmitter[]): void + + export let defaultMaxListeners: number + + export { EventEmitter, EventEmitterError as errors, EventMap, EventHandler } +} + +export = EventEmitter